Open platform to collect and prioritize feedback
Remove open core licensing model, make all features available to self-hosters
Matt Roberts90003b6e77dc
diff --git a/.example.env b/.example.envindex a99492ca5..737c02333 100644--- a/.example.env+++ b/.example.env@@ -33,21 +33,3 @@ EMAIL_SMTP_HOST=localhostEMAIL_SMTP_PORT=1025EMAIL_SMTP_USERNAME=EMAIL_SMTP_PASSWORD=--# Commercial License (Optional)-#-# COMMERCIAL_KEY: Your commercial license key from the hosted Fider platform-# - Purchase a Pro subscription to get a license key-# - Add it here to enable commercial features (content moderation)-# - Leave blank to run Fider in free/open-source mode-# COMMERCIAL_KEY=FIDER-COMMERCIAL-123-1638360000-abc123...-#-# LICENSE_PUBLIC_KEY: (Advanced - usually not needed)-# - The public key is embedded in Fider and updates automatically-# - Only set this if instructed by support or for testing-# LICENSE_PUBLIC_KEY=lPHzCZhOBBihIusKWs5lzXCgGxZEKBpCiplkmZSjGpU=-#-# LICENSE_PRIVATE_KEY: (Internal - for hosted instance only)-# - Used by the hosted Fider platform to generate license keys-# - Self-hosted users should NOT set this-# LICENSE_PRIVATE_KEY=your-base64-encoded-private-key-herediff --git a/.test.env b/.test.envindex 58fed84ba..f5d61a25f 100644--- a/.test.env+++ b/.test.env@@ -40,7 +40,3 @@ EMAIL_MAILGUN_DOMAIN=mydomain.comUSER_LIST_ENABLED=trueUSER_LIST_APIKEY=abcdefg--# Ed25519 license keys for testing-LICENSE_PUBLIC_KEY=9o3OnNs9tnnD780fZcTYas8uhcA90MWtin1rWGhXVPE=-LICENSE_PRIVATE_KEY=fwRNcFEiusrH0Hx1aBlOobE+6hm2/CPXUkUTWXj3cQn2jc6c2z22ecPvzR9lxNhqzy6FwD3Qxa2KfWtYaFdU8Q==diff --git a/COMMERCIAL_MODERATION_PLAN.md b/COMMERCIAL_MODERATION_PLAN.mddeleted file mode 100644index f00566085..000000000--- a/COMMERCIAL_MODERATION_PLAN.md+++ /dev/null@@ -1,213 +0,0 @@-# Commercial Content Moderation Restructure Plan--## Overview--Moving Fider's content moderation feature from open source (AGPL) to commercial licensing using an "open core" model. The commercial code will reside in a `commercial/` folder with a restrictive license, while the open source core provides infrastructure and gracefully degrades when commercial features aren't licensed.--## Key Architectural Decisions--### 1. Webpack Integration (Simple Solution)-- Update `webpack.config.js` to scan both folders:- ```js- paths: [- ...glob.sync(`./public/**/*.{html,tsx}`, { nodir: true }),- ...glob.sync(`./commercial/**/*.{html,tsx}`, { nodir: true })- ]- ```-- Commercial code gets bundled but legal license prevents usage-- No complex conditional compilation needed--### 2. Backend Package Separation Strategy--**Handlers - Dynamic Route Registration**-- Open source: Register stub routes returning "upgrade" messages-- Commercial: Override routes with real handlers via dynamic registration-- License validation controls active routes--**Services - Stub + Override Pattern**-- Open source: Register stub bus handlers returning "not licensed" errors-- Commercial: Override with real implementations via bus registration-- Same command/query types, different implementations--## What Moves to Commercial (Strong Legal Protection)--### Commercial Folder Structure-```-commercial/-├── LICENSE (restrictive commercial license)-├── pages/-│ └── Administration/-│ └── ContentModeration.page.tsx (~300 lines)-├── components/-│ └── ModerationIndicator.tsx-├── handlers/-│ ├── moderation.go (ModerationPage, GetModerationItems, GetModerationCount)-│ └── apiv1/-│ ├── moderation.go (all API endpoints)-│ └── moderation_test.go-├── services/-│ └── moderation.go (approve/decline business logic)-└── init.go (service/route registration)-```--### Frontend (Moves to Commercial)-- Complete moderation admin UI (ContentModeration.page.tsx + styles)-- Moderation indicator component showing pending counts-- All moderation-specific UI components--### Backend (Moves to Commercial)-- All HTTP handlers (`ModerationPage`, `GetModerationItems`, `GetModerationCount`)-- All API endpoints (`/api/v1/admin/moderation/*` routes)-- Business logic implementations (approve/decline/verify/block functions)-- Route registrations for moderation endpoints-- Tests for commercial functionality--## What Stays Open Source (Minimal Infrastructure)--### Database/Models (Cannot Move - Bus System Dependency)-- `app/models/cmd/moderation.go` - Command type definitions-- `app/models/query/moderation.go` - Query type definitions-- Database schema, migrations (`is_moderation_enabled`, `is_approved` columns)-- Entity definitions (`ModerationItem` structs)--### Settings Infrastructure-- Privacy settings toggle (shows "upgrade" message if unlicensed)-- Basic tenant property (`isModerationEnabled`)-- License validation service--### Content Flow Logic-- Logic that marks content as needing approval-- Basic "content requires moderation" checks throughout codebase-- Content queuing when moderation is enabled--### Locale Files-- All `moderation.*` translation strings (used by upgrade messages too)--## Technical Implementation Details--### 1. Handler Registration Pattern-```go-// Open source routes.go - stub routes-ui.Get("/admin/moderation", upgradeHandler("content-moderation"))-ui.Get("/_api/admin/moderation/items", upgradeHandler("content-moderation"))--// Commercial init.go - overrides routes-func init() {- if license.IsCommercialFeatureEnabled("content-moderation") {- web.RegisterRoute("GET", "/admin/moderation", handlers.ModerationPage())- web.RegisterRoute("GET", "/_api/admin/moderation/items", handlers.GetModerationItems())- // ... all other moderation routes- }-}-```--### 2. Service Registration Pattern-```go-// Open source postgres.go - register stubs-func (s *Service) Init() {- bus.AddHandler(approvePostStub) // Returns "feature not licensed"- bus.AddHandler(declinePostStub)- bus.AddHandler(getModerationItemsStub)- // ... other stubs-}--// Commercial service init - override with real handlers-func (cs *CommercialService) Init() {- if license.IsCommercialFeatureEnabled("content-moderation") {- bus.AddHandler(approvePost) // Real implementation- bus.AddHandler(declinePost)- bus.AddHandler(getModerationItems)- // ... other real handlers- }-}-```--### 3. License Validation Service-```go-// app/services/license.go-type LicenseService interface {- IsCommercialFeatureEnabled(feature string) bool-}--// Implementation checks for valid commercial license-// Controls route registration and service overrides-```--## Implementation Phases--### Phase 1: Setup Commercial Infrastructure-1. Create `commercial/` folder structure-2. Add restrictive LICENSE file to commercial folder-3. Update webpack.config.js to scan commercial folder-4. Create license validation service interface--### Phase 2: Move Frontend Components-1. Move `ContentModeration.page.tsx` to `commercial/pages/Administration/`-2. Move `ModerationIndicator.tsx` to `commercial/components/`-3. Test that webpack builds both locations correctly-4. Add license checks in components to show upgrade messages--### Phase 3: Implement Backend Service Separation-1. Create stub implementations for all moderation commands/queries-2. Register stubs in open source postgres service-3. Move real implementations to `commercial/services/moderation.go`-4. Implement commercial service registration with license checks--### Phase 4: Implement Route Separation-1. Replace direct handler calls with upgrade handlers in routes.go-2. Move real handlers to `commercial/handlers/`-3. Implement dynamic route registration in commercial init-4. Test route overriding works correctly--### Phase 5: Testing & Validation-1. Move tests to commercial folder-2. Test open source build without commercial features-3. Test commercial build with license validation-4. Verify graceful degradation and upgrade messaging-5. Test that forking open source works without commercial parts--## Key Benefits--### Strong Commercial Protection-- Recreating moderation requires rebuilding entire UI + API + business logic-- Substantial engineering effort (days/weeks) to replicate functionality-- Clear legal separation under different licenses--### Clean Architecture-- Open source provides database infrastructure and settings-- Commercial enhances with actual moderation functionality-- No broken states - content flows normally when moderation disabled-- True open core model: commercial builds on open source foundation--### Simple Build Process-- Single repository with clear folder separation-- Standard webpack build process-- License provides protection, not technical hiding-- Easy development workflow--## Migration Considerations--### Existing Moderation Data-- All existing moderation settings and data remain compatible-- Database schema stays in open source (infrastructure)-- Only the management interface becomes commercial--### User Experience-- **With License**: Full moderation functionality as before-- **Without License**: Moderation simply disabled, standard user flow-- **Upgrade Path**: Clear messaging and sales funnel for commercial features--### Development Workflow-- Developers can see all code (legal license controls usage)-- Standard build process works for both open source and commercial-- Clean separation makes it easy to add more commercial features--## Success Metrics--1. **Legal Protection**: Someone forking open source cannot easily recreate moderation-2. **Functional Separation**: Open source works perfectly without moderation-3. **Build Compatibility**: Both open source and commercial versions build successfully-4. **Clean Boundaries**: Clear understanding of what's core vs commercial-5. **Scalability**: Pattern works for future commercial features--This plan provides genuine open core protection while maintaining clean architecture and manageable implementation complexity.\ No newline at end of filediff --git a/app/cmd/routes.go b/app/cmd/routes.goindex b55a39c98..04def8c4b 100644--- a/app/cmd/routes.go+++ b/app/cmd/routes.go@@ -166,10 +166,16 @@ func routes(r *web.Engine) *web.Engine {ui.Get("/admin/invitations", handlers.Page("Invitations · Site Settings", "", "Administration/pages/Invitations.page"))ui.Get("/admin/users", handlers.ManageMembers())ui.Get("/admin/tags", handlers.ManageTags())- ui.Get("/admin/moderation", handlers.GetModerationPageHandler())ui.Get("/admin/authentication", handlers.ManageAuthentication())ui.Get("/_api/admin/oauth/:provider", handlers.GetOAuthConfig())+ // Pro features (available to self-hosters and pro hosted customers)+ proUi := ui.Group()+ {+ proUi.Use(middlewares.RequirePro())+ proUi.Get("/admin/moderation", handlers.ModerationPage())+ }+// From this step, only Administrators are allowedui.Use(middlewares.IsAuthorized(enum.RoleAdministrator))@@ -194,8 +200,14 @@ func routes(r *web.Engine) *web.Engine {ui.Delete("/_api/admin/users/:userID/block", handlers.UnblockUser())ui.Put("/_api/admin/users/:userID/trust", handlers.TrustUser())ui.Delete("/_api/admin/users/:userID/trust", handlers.UntrustUser())- ui.Get("/_api/admin/moderation/items", handlers.GetModerationItemsHandler())- ui.Get("/_api/admin/moderation/count", handlers.GetModerationCountHandler())++ // Pro features (available to self-hosters and pro hosted customers)+ proAdmin := ui.Group()+ {+ proAdmin.Use(middlewares.RequirePro())+ proAdmin.Get("/_api/admin/moderation/items", handlers.GetModerationItems())+ proAdmin.Get("/_api/admin/moderation/count", handlers.GetModerationCount())+ }if env.IsBillingEnabled() {ui.Get("/admin/billing", handlers.ManageBilling())@@ -271,14 +283,19 @@ func routes(r *web.Engine) *web.Engine {adminApi.Put("/api/v1/tags/:slug", apiv1.CreateEditTag())adminApi.Delete("/api/v1/tags/:slug", apiv1.DeleteTag())- adminApi.Post("/api/v1/admin/moderation/posts/:id/approve-and-verify", apiv1.GetApprovePostAndVerifyHandler())- adminApi.Post("/api/v1/admin/moderation/posts/:id/decline-and-block", apiv1.GetDeclinePostAndBlockHandler())- adminApi.Post("/api/v1/admin/moderation/posts/:id/approve", apiv1.GetApprovePostHandler())- adminApi.Post("/api/v1/admin/moderation/posts/:id/decline", apiv1.GetDeclinePostHandler())- adminApi.Post("/api/v1/admin/moderation/comments/:id/approve-and-verify", apiv1.GetApproveCommentAndVerifyHandler())- adminApi.Post("/api/v1/admin/moderation/comments/:id/decline-and-block", apiv1.GetDeclineCommentAndBlockHandler())- adminApi.Post("/api/v1/admin/moderation/comments/:id/approve", apiv1.GetApproveCommentHandler())- adminApi.Post("/api/v1/admin/moderation/comments/:id/decline", apiv1.GetDeclineCommentHandler())+ // Pro features (available to self-hosters and pro hosted customers)+ proAdminApi := adminApi.Group()+ {+ proAdminApi.Use(middlewares.RequirePro())+ proAdminApi.Post("/api/v1/admin/moderation/posts/:id/approve-and-verify", apiv1.ApprovePostAndVerify())+ proAdminApi.Post("/api/v1/admin/moderation/posts/:id/decline-and-block", apiv1.DeclinePostAndBlock())+ proAdminApi.Post("/api/v1/admin/moderation/posts/:id/approve", apiv1.ApprovePost())+ proAdminApi.Post("/api/v1/admin/moderation/posts/:id/decline", apiv1.DeclinePost())+ proAdminApi.Post("/api/v1/admin/moderation/comments/:id/approve-and-verify", apiv1.ApproveCommentAndVerify())+ proAdminApi.Post("/api/v1/admin/moderation/comments/:id/decline-and-block", apiv1.DeclineCommentAndBlock())+ proAdminApi.Post("/api/v1/admin/moderation/comments/:id/approve", apiv1.ApproveComment())+ proAdminApi.Post("/api/v1/admin/moderation/comments/:id/decline", apiv1.DeclineComment())+ }adminApi.Use(middlewares.BlockLockedTenants())adminApi.Delete("/api/v1/posts/:number", apiv1.DeletePost())diff --git a/app/const.go b/app/const.goindex f5ffefa76..27c29a942 100644--- a/app/const.go+++ b/app/const.go@@ -5,9 +5,6 @@ import "errors"// ErrNotFound represents an object not found errorvar ErrNotFound = errors.New("object not found")-// ErrCommercialLicenseRequired is used when a commercial feature is accessed without a license-var ErrCommercialLicenseRequired = errors.New("content moderation requires a commercial license")-// InvitePlaceholder represents the placeholder used by members to invite other usersvar InvitePlaceholder = "%invite%"diff --git a/app/handlers/admin.go b/app/handlers/admin.goindex e21d3724a..6dfe7f360 100644--- a/app/handlers/admin.go+++ b/app/handlers/admin.go@@ -27,19 +27,12 @@ func GeneralSettingsPage() web.HandlerFunc {// AdvancedSettingsPage is the advanced settings pagefunc AdvancedSettingsPage() web.HandlerFunc {return func(c *web.Context) error {- billingState := &query.GetStripeBillingState{}- if err := bus.Dispatch(c, billingState); err != nil {- return c.Failure(err)- }-return c.Page(http.StatusOK, web.Props{Page: "Administration/pages/AdvancedSettings.page",Title: "Advanced · Site Settings",Data: web.Map{- "customCSS": c.Tenant().CustomCSS,- "allowedSchemes": c.Tenant().AllowedSchemes,- "licenseKey": billingState.Result.LicenseKey,- "hasCommercialFeatures": c.Tenant().HasCommercialFeatures,+ "customCSS": c.Tenant().CustomCSS,+ "allowedSchemes": c.Tenant().AllowedSchemes,},})}diff --git a/app/handlers/apiv1/moderation.go b/app/handlers/apiv1/moderation.goindex 7bf70ff60..722c91691 100644--- a/app/handlers/apiv1/moderation.go+++ b/app/handlers/apiv1/moderation.go@@ -1,61 +1,178 @@package apiv1import (+ "strconv"++ "github.com/getfider/fider/app/models/cmd"+ "github.com/getfider/fider/app/models/query"+ "github.com/getfider/fider/app/pkg/bus""github.com/getfider/fider/app/pkg/web")-// ApprovePost approves a post (stub - requires commercial license)+// ApprovePost approves a postfunc ApprovePost() web.HandlerFunc {return func(c *web.Context) error {- return c.BadRequest(web.Map{"error": "Content moderation requires commercial license"})+ postID, err := strconv.Atoi(c.Param("id"))+ if err != nil {+ return c.BadRequest(web.Map{"error": "Invalid post ID"})+ }++ if err := bus.Dispatch(c, &cmd.ApprovePost{PostID: postID}); err != nil {+ return c.Failure(err)+ }++ return c.Ok(web.Map{})}}-// DeclinePost declines (deletes) a post (stub - requires commercial license)+// DeclinePost declines (deletes) a postfunc DeclinePost() web.HandlerFunc {return func(c *web.Context) error {- return c.BadRequest(web.Map{"error": "Content moderation requires commercial license"})+ postID, err := strconv.Atoi(c.Param("id"))+ if err != nil {+ return c.BadRequest(web.Map{"error": "Invalid post ID"})+ }++ if err := bus.Dispatch(c, &cmd.DeclinePost{PostID: postID}); err != nil {+ return c.Failure(err)+ }++ return c.Ok(web.Map{})}}-// ApproveComment approves a comment (stub - requires commercial license)+// ApproveComment approves a commentfunc ApproveComment() web.HandlerFunc {return func(c *web.Context) error {- return c.BadRequest(web.Map{"error": "Content moderation requires commercial license"})+ commentID, err := strconv.Atoi(c.Param("id"))+ if err != nil {+ return c.BadRequest(web.Map{"error": "Invalid comment ID"})+ }++ if err := bus.Dispatch(c, &cmd.ApproveComment{CommentID: commentID}); err != nil {+ return c.Failure(err)+ }++ return c.Ok(web.Map{})}}-// DeclineComment declines (deletes) a comment (stub - requires commercial license)+// DeclineComment declines (deletes) a commentfunc DeclineComment() web.HandlerFunc {return func(c *web.Context) error {- return c.BadRequest(web.Map{"error": "Content moderation requires commercial license"})+ commentID, err := strconv.Atoi(c.Param("id"))+ if err != nil {+ return c.BadRequest(web.Map{"error": "Invalid comment ID"})+ }++ if err := bus.Dispatch(c, &cmd.DeclineComment{CommentID: commentID}); err != nil {+ return c.Failure(err)+ }++ return c.Ok(web.Map{})}}-// DeclinePostAndBlock declines (deletes) a post and blocks the user (stub - requires commercial license)+// DeclinePostAndBlock declines (deletes) a post and blocks the userfunc DeclinePostAndBlock() web.HandlerFunc {return func(c *web.Context) error {- return c.BadRequest(web.Map{"error": "Content moderation requires commercial license"})+ postID, err := strconv.Atoi(c.Param("id"))+ if err != nil {+ return c.BadRequest(web.Map{"error": "Invalid post ID"})+ }++ getPost := &query.GetPostByID{PostID: postID}+ if err := bus.Dispatch(c, getPost); err != nil {+ return c.Failure(err)+ }++ err = bus.Dispatch(c, &cmd.BlockUser{UserID: getPost.Result.User.ID})+ if err != nil {+ return c.Failure(err)+ }++ err = bus.Dispatch(c, &cmd.DeclinePost{PostID: postID})+ if err != nil {+ return c.Failure(err)+ }++ return c.Ok(web.Map{})}}-// DeclineCommentAndBlock declines (deletes) a comment and blocks the user (stub - requires commercial license)+// DeclineCommentAndBlock declines (deletes) a comment and blocks the userfunc DeclineCommentAndBlock() web.HandlerFunc {return func(c *web.Context) error {- return c.BadRequest(web.Map{"error": "Content moderation requires commercial license"})+ commentID, err := strconv.Atoi(c.Param("id"))+ if err != nil {+ return c.BadRequest(web.Map{"error": "Invalid comment ID"})+ }++ getComment := &query.GetCommentByID{CommentID: commentID}+ if err := bus.Dispatch(c, getComment); err != nil {+ return c.Failure(err)+ }++ err = bus.Dispatch(c, &cmd.BlockUser{UserID: getComment.Result.User.ID})+ if err != nil {+ return c.Failure(err)+ }++ err = bus.Dispatch(c, &cmd.DeclineComment{CommentID: commentID})+ if err != nil {+ return c.Failure(err)+ }++ return c.Ok(web.Map{})}}-// ApprovePostAndVerify approves a post and verifies the user (stub - requires commercial license)+// ApprovePostAndVerify approves a post and trusts the userfunc ApprovePostAndVerify() web.HandlerFunc {return func(c *web.Context) error {- return c.BadRequest(web.Map{"error": "Content moderation requires commercial license"})+ postID, err := strconv.Atoi(c.Param("id"))+ if err != nil {+ return c.BadRequest(web.Map{"error": "Invalid post ID"})+ }++ getPost := &query.GetPostByID{PostID: postID}+ if err := bus.Dispatch(c, getPost); err != nil {+ return c.Failure(err)+ }++ if err := bus.Dispatch(c, &cmd.ApprovePost{PostID: postID}); err != nil {+ return c.Failure(err)+ }++ if err := bus.Dispatch(c, &cmd.TrustUser{UserID: getPost.Result.User.ID}); err != nil {+ return c.Failure(err)+ }++ return c.Ok(web.Map{})}}-// ApproveCommentAndVerify approves a comment and verifies the user (stub - requires commercial license)+// ApproveCommentAndVerify approves a comment and trusts the userfunc ApproveCommentAndVerify() web.HandlerFunc {return func(c *web.Context) error {- return c.BadRequest(web.Map{"error": "Content moderation requires commercial license"})+ commentID, err := strconv.Atoi(c.Param("id"))+ if err != nil {+ return c.BadRequest(web.Map{"error": "Invalid comment ID"})+ }++ getComment := &query.GetCommentByID{CommentID: commentID}+ if err := bus.Dispatch(c, getComment); err != nil {+ return c.Failure(err)+ }++ if err := bus.Dispatch(c, &cmd.ApproveComment{CommentID: commentID}); err != nil {+ return c.Failure(err)+ }++ if err := bus.Dispatch(c, &cmd.TrustUser{UserID: getComment.Result.User.ID}); err != nil {+ return c.Failure(err)+ }++ return c.Ok(web.Map{})}}diff --git a/app/handlers/apiv1/registry.go b/app/handlers/apiv1/registry.godeleted file mode 100644index 43e1baf3c..000000000--- a/app/handlers/apiv1/registry.go+++ /dev/null@@ -1,82 +0,0 @@-package apiv1--import (- "github.com/getfider/fider/app/pkg/web"-)--// Handler registry for commercial API v1 overrides-type HandlerRegistry struct {- ApprovePost func() web.HandlerFunc- DeclinePost func() web.HandlerFunc- ApproveComment func() web.HandlerFunc- DeclineComment func() web.HandlerFunc- DeclinePostAndBlock func() web.HandlerFunc- DeclineCommentAndBlock func() web.HandlerFunc- ApprovePostAndVerify func() web.HandlerFunc- ApproveCommentAndVerify func() web.HandlerFunc-}--var registry = &HandlerRegistry{- ApprovePost: ApprovePost,- DeclinePost: DeclinePost,- ApproveComment: ApproveComment,- DeclineComment: DeclineComment,- DeclinePostAndBlock: DeclinePostAndBlock,- DeclineCommentAndBlock: DeclineCommentAndBlock,- ApprovePostAndVerify: ApprovePostAndVerify,- ApproveCommentAndVerify: ApproveCommentAndVerify,-}--// RegisterModerationHandlers allows commercial package to override moderation handlers-func RegisterModerationHandlers(- approvePost func() web.HandlerFunc,- declinePost func() web.HandlerFunc,- approveComment func() web.HandlerFunc,- declineComment func() web.HandlerFunc,- declinePostAndBlock func() web.HandlerFunc,- declineCommentAndBlock func() web.HandlerFunc,- approvePostAndVerify func() web.HandlerFunc,- approveCommentAndVerify func() web.HandlerFunc,-) {- registry.ApprovePost = approvePost- registry.DeclinePost = declinePost- registry.ApproveComment = approveComment- registry.DeclineComment = declineComment- registry.DeclinePostAndBlock = declinePostAndBlock- registry.DeclineCommentAndBlock = declineCommentAndBlock- registry.ApprovePostAndVerify = approvePostAndVerify- registry.ApproveCommentAndVerify = approveCommentAndVerify-}--// Handler getters that return the registered handlers-func GetApprovePostHandler() web.HandlerFunc {- return registry.ApprovePost()-}--func GetDeclinePostHandler() web.HandlerFunc {- return registry.DeclinePost()-}--func GetApproveCommentHandler() web.HandlerFunc {- return registry.ApproveComment()-}--func GetDeclineCommentHandler() web.HandlerFunc {- return registry.DeclineComment()-}--func GetDeclinePostAndBlockHandler() web.HandlerFunc {- return registry.DeclinePostAndBlock()-}--func GetDeclineCommentAndBlockHandler() web.HandlerFunc {- return registry.DeclineCommentAndBlock()-}--func GetApprovePostAndVerifyHandler() web.HandlerFunc {- return registry.ApprovePostAndVerify()-}--func GetApproveCommentAndVerifyHandler() web.HandlerFunc {- return registry.ApproveCommentAndVerify()-}\ No newline at end of filediff --git a/app/handlers/billing.go b/app/handlers/billing.goindex ec6cd21ac..b55bace80 100644--- a/app/handlers/billing.go+++ b/app/handlers/billing.go@@ -27,9 +27,8 @@ func ManageBilling() web.HandlerFunc {Data: web.Map{"stripeCustomerID": billingState.Result.CustomerID,"stripeSubscriptionID": billingState.Result.SubscriptionID,- "licenseKey": billingState.Result.LicenseKey,- "paddleSubscriptionID": billingState.Result.PaddleSubscriptionID,- "hasCommercialFeatures": c.Tenant().HasCommercialFeatures,+ "paddleSubscriptionID": billingState.Result.PaddleSubscriptionID,+ "isPro": c.Tenant().IsPro,},})}diff --git a/app/handlers/moderation.go b/app/handlers/moderation.goindex 2dd2ea7b3..563a536aa 100644--- a/app/handlers/moderation.go+++ b/app/handlers/moderation.go@@ -1,30 +1,47 @@package handlersimport (- "github.com/getfider/fider/app"+ "net/http"++ "github.com/getfider/fider/app/models/query"+ "github.com/getfider/fider/app/pkg/bus""github.com/getfider/fider/app/pkg/web")-// ModerationPage is the moderation administration page (stub - requires commercial license)+// ModerationPage is the moderation administration pagefunc ModerationPage() web.HandlerFunc {return func(c *web.Context) error {- return c.Failure(app.ErrCommercialLicenseRequired)+ return c.Page(http.StatusOK, web.Props{+ Page: "Administration/pages/ContentModeration.page",+ Title: "Moderation · Site Settings",+ })}}-// GetModerationItems returns all unmoderated posts and comments (stub - requires commercial license)+// GetModerationItems returns all unmoderated posts and commentsfunc GetModerationItems() web.HandlerFunc {return func(c *web.Context) error {- return c.Failure(app.ErrCommercialLicenseRequired)+ q := &query.GetModerationItems{}+ if err := bus.Dispatch(c, q); err != nil {+ return c.Failure(err)+ }++ return c.Ok(web.Map{+ "items": q.Result,+ })}}-// GetModerationCount returns the count of items awaiting moderation (stub - requires commercial license)+// GetModerationCount returns the count of items awaiting moderationfunc GetModerationCount() web.HandlerFunc {return func(c *web.Context) error {- // Return 0 instead of error to allow UI to function normally+ q := &query.GetModerationCount{}+ if err := bus.Dispatch(c, q); err != nil {+ return c.Failure(err)+ }+return c.Ok(web.Map{- "count": 0,+ "count": q.Result,})}}diff --git a/app/handlers/registry.go b/app/handlers/registry.godeleted file mode 100644index 138708967..000000000--- a/app/handlers/registry.go+++ /dev/null@@ -1,42 +0,0 @@-package handlers--import (- "github.com/getfider/fider/app/pkg/web"-)--// Handler registry for commercial overrides-type HandlerRegistry struct {- ModerationPage func() web.HandlerFunc- GetModerationItems func() web.HandlerFunc- GetModerationCount func() web.HandlerFunc-}--var registry = &HandlerRegistry{- ModerationPage: ModerationPage,- GetModerationItems: GetModerationItems,- GetModerationCount: GetModerationCount,-}--// RegisterModerationHandlers allows commercial package to override moderation handlers-func RegisterModerationHandlers(- moderationPage func() web.HandlerFunc,- getModerationItems func() web.HandlerFunc,- getModerationCount func() web.HandlerFunc,-) {- registry.ModerationPage = moderationPage- registry.GetModerationItems = getModerationItems- registry.GetModerationCount = getModerationCount-}--// Handler getters that return the registered handlers-func GetModerationPageHandler() web.HandlerFunc {- return registry.ModerationPage()-}--func GetModerationItemsHandler() web.HandlerFunc {- return registry.GetModerationItems()-}--func GetModerationCountHandler() web.HandlerFunc {- return registry.GetModerationCount()-}\ No newline at end of filediff --git a/app/handlers/webhooks/stripe.go b/app/handlers/webhooks/stripe.goindex 0d5a0c536..6e013c010 100644--- a/app/handlers/webhooks/stripe.go+++ b/app/handlers/webhooks/stripe.go@@ -13,7 +13,6 @@ import ("github.com/getfider/fider/app/pkg/errors""github.com/getfider/fider/app/pkg/log""github.com/getfider/fider/app/pkg/web"- "github.com/getfider/fider/app/services/license""github.com/getfider/fider/app/tasks""github.com/stripe/stripe-go/v83""github.com/stripe/stripe-go/v83/webhook"@@ -60,14 +59,10 @@ func handleCheckoutSessionCompleted(c *web.Context, event stripe.Event) error {return c.Failure(errors.Wrap(err, "failed to parse tenant_id"))}- // Generate license key for this tenant- licenseKey := license.GenerateKey(tenantID)-activate := &cmd.ActivateStripeSubscription{TenantID: tenantID,CustomerID: session.Customer.ID,SubscriptionID: session.Subscription.ID,- LicenseKey: licenseKey,}if err := bus.Dispatch(c, activate); err != nil {diff --git a/app/middlewares/tenant.go b/app/middlewares/tenant.goindex 890875e43..03beb5bca 100644--- a/app/middlewares/tenant.go+++ b/app/middlewares/tenant.go@@ -136,6 +136,18 @@ func CheckTenantPrivacy() web.MiddlewareFunc {}}+// RequirePro blocks requests from non-pro tenants (free hosted customers)+func RequirePro() web.MiddlewareFunc {+ return func(next web.HandlerFunc) web.HandlerFunc {+ return func(c *web.Context) error {+ if !c.Tenant().IsPro {+ return c.Forbidden()+ }+ return next(c)+ }+ }+}+// BlockLockedTenants blocks requests on locked tenants as they are in read-only modefunc BlockLockedTenants() web.MiddlewareFunc {return func(next web.HandlerFunc) web.HandlerFunc {diff --git a/app/models/cmd/billing.go b/app/models/cmd/billing.goindex feb46c819..1ff09d32f 100644--- a/app/models/cmd/billing.go+++ b/app/models/cmd/billing.go@@ -12,7 +12,6 @@ type ActivateStripeSubscription struct {TenantID intCustomerID stringSubscriptionID string- LicenseKey string}type CancelStripeSubscription struct {diff --git a/app/models/entity/billing.go b/app/models/entity/billing.goindex 3ac91ef0a..79cca05de 100644--- a/app/models/entity/billing.go+++ b/app/models/entity/billing.go@@ -24,6 +24,5 @@ type BillingPayment struct {type StripeBillingState struct {CustomerID string `json:"customerID"`SubscriptionID string `json:"subscriptionID"`- LicenseKey string `json:"licenseKey"`PaddleSubscriptionID string `json:"paddleSubscriptionID"`}diff --git a/app/models/entity/tenant.go b/app/models/entity/tenant.goindex 064714600..e1d936b12 100644--- a/app/models/entity/tenant.go+++ b/app/models/entity/tenant.go@@ -22,8 +22,8 @@ type Tenant struct {IsEmailAuthAllowed bool `json:"isEmailAuthAllowed"`IsFeedEnabled bool `json:"isFeedEnabled"`PreventIndexing bool `json:"preventIndexing"`- IsModerationEnabled bool `json:"isModerationEnabled"`- HasCommercialFeatures bool `json:"hasCommercialFeatures"`+ IsModerationEnabled bool `json:"isModerationEnabled"`+ IsPro bool `json:"isPro"`}func (t *Tenant) IsDisabled() bool {diff --git a/app/pkg/env/env.go b/app/pkg/env/env.goindex fc1fee739..b6a988cbc 100644--- a/app/pkg/env/env.go+++ b/app/pkg/env/env.go@@ -146,11 +146,6 @@ type config struct {}GoogleAnalytics string `env:"GOOGLE_ANALYTICS"`SearchNoiseWords string `env:"SEARCH_NOISE_WORDS,default=add|support|for|implement|create|make|allow|enable|provide|some|also|include|very|make|and|for|to|a|able|function|feature|app"`- License struct {- PrivateKey string `env:"LICENSE_PRIVATE_KEY"` // Ed25519 private key for hosted instances (base64 encoded)- PublicKey string `env:"LICENSE_PUBLIC_KEY"` // Ed25519 public key for license validation (base64 encoded)- Key string `env:"COMMERCIAL_KEY"` // Self-hosted instance's license key- }}// Config is a strongly typed reference to all configuration parsed from Environment Variablesdiff --git a/app/pkg/web/context.go b/app/pkg/web/context.goindex 64f636400..4857bcded 100644--- a/app/pkg/web/context.go+++ b/app/pkg/web/context.go@@ -273,10 +273,6 @@ func (c *Context) Failure(err error) error {return c.NotFound()}- if cause == app.ErrCommercialLicenseRequired {- return c.Forbidden()- }-if renderErr := c.Page(http.StatusInternalServerError, Props{Page: "Error/Error500.page",Title: "Shoot! Well, this is unexpected…",diff --git a/app/pkg/web/testdata/home_ssr.html b/app/pkg/web/testdata/home_ssr.htmlindex 7d072bc97..c3c8670ff 100755--- a/app/pkg/web/testdata/home_ssr.html+++ b/app/pkg/web/testdata/home_ssr.html@@ -45,7 +45,7 @@<script id="server-data" type="application/json">- {"contextID":"CONTEXT_ID","description":"My Page Description","page":"Test.page","props":{"countPerStatus":{},"posts":[],"tags":[]},"sessionID":"","settings":{"allowAllowedSchemes":true,"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true},"tenant":{"id":0,"name":"","subdomain":"","invitation":"","welcomeMessage":"","welcomeHeader":"","cname":"","status":0,"locale":"en","isPrivate":false,"logoBlobKey":"","allowedSchemes":"","isEmailAuthAllowed":false,"isFeedEnabled":false,"preventIndexing":false,"isModerationEnabled":false,"hasCommercialFeatures":false},"title":"My Page Title · "}+ {"contextID":"CONTEXT_ID","description":"My Page Description","page":"Test.page","props":{"countPerStatus":{},"posts":[],"tags":[]},"sessionID":"","settings":{"allowAllowedSchemes":true,"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true},"tenant":{"id":0,"name":"","subdomain":"","invitation":"","welcomeMessage":"","welcomeHeader":"","cname":"","status":0,"locale":"en","isPrivate":false,"logoBlobKey":"","allowedSchemes":"","isEmailAuthAllowed":false,"isFeedEnabled":false,"preventIndexing":false,"isModerationEnabled":false,"isPro":false},"title":"My Page Title · "}</script>diff --git a/app/pkg/web/testdata/tenant.html b/app/pkg/web/testdata/tenant.htmlindex d8862b06a..40a9dd2d6 100755--- a/app/pkg/web/testdata/tenant.html+++ b/app/pkg/web/testdata/tenant.html@@ -45,7 +45,7 @@<script id="server-data" type="application/json">- {"contextID":"CONTEXT_ID","page":"","props":{},"sessionID":"","settings":{"allowAllowedSchemes":true,"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true},"tenant":{"id":0,"name":"Game of Thrones","subdomain":"","invitation":"","welcomeMessage":"","welcomeHeader":"","cname":"","status":0,"locale":"","isPrivate":false,"logoBlobKey":"","allowedSchemes":"","isEmailAuthAllowed":false,"isFeedEnabled":false,"preventIndexing":false,"isModerationEnabled":false,"hasCommercialFeatures":false},"title":"Game of Thrones"}+ {"contextID":"CONTEXT_ID","page":"","props":{},"sessionID":"","settings":{"allowAllowedSchemes":true,"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true},"tenant":{"id":0,"name":"Game of Thrones","subdomain":"","invitation":"","welcomeMessage":"","welcomeHeader":"","cname":"","status":0,"locale":"","isPrivate":false,"logoBlobKey":"","allowedSchemes":"","isEmailAuthAllowed":false,"isFeedEnabled":false,"preventIndexing":false,"isModerationEnabled":false,"isPro":false},"title":"Game of Thrones"}</script>diff --git a/app/services/license.go b/app/services/license.godeleted file mode 100644index 3e49f8f3f..000000000--- a/app/services/license.go+++ /dev/null@@ -1,46 +0,0 @@-package services--// LicenseService provides license validation for commercial features-type LicenseService interface {- // IsCommercialFeatureEnabled checks if a specific commercial feature is licensed- IsCommercialFeatureEnabled(feature string) bool-- // GetLicenseInfo returns information about the current license- GetLicenseInfo() *LicenseInfo-}--// LicenseInfo contains information about the current license-type LicenseInfo struct {- IsValid bool `json:"isValid"`- Features []string `json:"features"`- ExpiresAt *string `json:"expiresAt,omitempty"`- LicenseHolder string `json:"licenseHolder"`-}--// Commercial feature constants-const (- FeatureContentModeration = "content-moderation"-)--// Default implementation that denies all commercial features-type defaultLicenseService struct{}--func (s *defaultLicenseService) IsCommercialFeatureEnabled(feature string) bool {- return false-}--func (s *defaultLicenseService) GetLicenseInfo() *LicenseInfo {- return &LicenseInfo{- IsValid: false,- Features: []string{},- LicenseHolder: "Open Source",- }-}--// Global license service instance - can be overridden by commercial code-var License LicenseService = &defaultLicenseService{}--// Helper function for easy access-func IsCommercialFeatureEnabled(feature string) bool {- return License.IsCommercialFeatureEnabled(feature)-}\ No newline at end of filediff --git a/app/services/license/validator.go b/app/services/license/validator.godeleted file mode 100644index 2d474dc86..000000000--- a/app/services/license/validator.go+++ /dev/null@@ -1,144 +0,0 @@-package license--import (- "crypto/ed25519"- "encoding/base64"- "encoding/hex"- "fmt"- "strconv"- "strings"- "time"-- "github.com/getfider/fider/app/pkg/env"- "github.com/getfider/fider/app/pkg/errors"-)--// DefaultPublicKey is the embedded public key for license validation-// This is the public key from the hosted Fider instance-// Self-hosted instances automatically use this - no configuration needed-// Can be overridden via LICENSE_PUBLIC_KEY environment variable-const DefaultPublicKey = "Ldi94BbbFMnxOOSBGqJKxWyWCgdx4k0zu3zLtNaz3bA="--// GenerateKey generates a commercial license key for a tenant using Ed25519 signatures-// Format: FIDER-COMMERCIAL-{tenantID}-{timestamp}-{signature}-// Panics if LICENSE_PRIVATE_KEY is not set-func GenerateKey(tenantID int) string {- if env.Config.License.PrivateKey == "" {- panic("LICENSE_PRIVATE_KEY environment variable must be set to generate license keys. This is required for hosted Fider instances that sell Pro subscriptions.")- }-- privateKeyBytes, err := base64.StdEncoding.DecodeString(env.Config.License.PrivateKey)- if err != nil {- panic(fmt.Sprintf("Invalid LICENSE_PRIVATE_KEY: %v", err))- }-- if len(privateKeyBytes) != ed25519.PrivateKeySize {- panic(fmt.Sprintf("Invalid LICENSE_PRIVATE_KEY length: expected %d bytes, got %d", ed25519.PrivateKeySize, len(privateKeyBytes)))- }-- timestamp := time.Now().Unix()- data := fmt.Sprintf("%d-%d", tenantID, timestamp)- signature := ed25519.Sign(ed25519.PrivateKey(privateKeyBytes), []byte(data))- signatureHex := hex.EncodeToString(signature)-- return fmt.Sprintf("FIDER-COMMERCIAL-%d-%d-%s", tenantID, timestamp, signatureHex)-}--// ValidationResult contains the result of license key validation-type ValidationResult struct {- IsValid bool- TenantID int- Error error-}--// ValidateKey validates a commercial license key using Ed25519 signature verification-// Uses embedded DefaultPublicKey unless LICENSE_PUBLIC_KEY environment variable is set-func ValidateKey(key string) *ValidationResult {- if key == "" {- return &ValidationResult{- IsValid: false,- TenantID: 0,- Error: errors.New("license key is empty"),- }- }-- // Use environment variable if set, otherwise use embedded default- publicKey := env.Config.License.PublicKey- if publicKey == "" {- publicKey = DefaultPublicKey- }-- // Parse license key format- parts := strings.Split(key, "-")- if len(parts) != 5 || parts[0] != "FIDER" || parts[1] != "COMMERCIAL" {- return &ValidationResult{- IsValid: false,- TenantID: 0,- Error: errors.New("invalid key format: expected FIDER-COMMERCIAL-{tenantID}-{timestamp}-{signature}"),- }- }-- tenantID, err := strconv.Atoi(parts[2])- if err != nil {- return &ValidationResult{- IsValid: false,- TenantID: 0,- Error: errors.Wrap(err, "invalid tenant ID in license key"),- }- }-- timestamp, err := strconv.ParseInt(parts[3], 10, 64)- if err != nil {- return &ValidationResult{- IsValid: false,- TenantID: 0,- Error: errors.Wrap(err, "invalid timestamp in license key"),- }- }-- providedSignatureHex := parts[4]-- // Decode and validate the public key- publicKeyBytes, err := base64.StdEncoding.DecodeString(publicKey)- if err != nil {- return &ValidationResult{- IsValid: false,- TenantID: 0,- Error: errors.Wrap(err, "invalid public key configuration"),- }- }-- if len(publicKeyBytes) != ed25519.PublicKeySize {- return &ValidationResult{- IsValid: false,- TenantID: 0,- Error: fmt.Errorf("invalid public key length: expected %d bytes, got %d", ed25519.PublicKeySize, len(publicKeyBytes)),- }- }-- // Decode the signature from the license key- providedSignature, err := hex.DecodeString(providedSignatureHex)- if err != nil {- return &ValidationResult{- IsValid: false,- TenantID: 0,- Error: errors.Wrap(err, "invalid signature format in license key"),- }- }-- // Verify the signature- data := fmt.Sprintf("%d-%d", tenantID, timestamp)- if !ed25519.Verify(ed25519.PublicKey(publicKeyBytes), []byte(data), providedSignature) {- return &ValidationResult{- IsValid: false,- TenantID: 0,- Error: errors.New("invalid signature: license key verification failed"),- }- }-- return &ValidationResult{- IsValid: true,- TenantID: tenantID,- Error: nil,- }-}diff --git a/app/services/license/validator_test.go b/app/services/license/validator_test.godeleted file mode 100644index 3093eb68e..000000000--- a/app/services/license/validator_test.go+++ /dev/null@@ -1,171 +0,0 @@-package license_test--import (- "crypto/ed25519"- "crypto/rand"- "encoding/base64"- "testing"-- "github.com/getfider/fider/app/pkg/env"- "github.com/getfider/fider/app/services/license"-)--func TestGenerateAndValidateKey_Ed25519(t *testing.T) {- // Generate a test key pair- publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)- if err != nil {- t.Fatal(err)- }-- // Set up environment with Ed25519 keys- env.Config.License.PrivateKey = base64.StdEncoding.EncodeToString(privateKey)- env.Config.License.PublicKey = base64.StdEncoding.EncodeToString(publicKey)- defer func() {- env.Config.License.PrivateKey = ""- env.Config.License.PublicKey = ""- }()-- // Generate a license key- tenantID := 42- key := license.GenerateKey(tenantID)-- // Validate the license key- result := license.ValidateKey(key)-- if !result.IsValid {- t.Errorf("Expected license key to be valid, but got error: %v", result.Error)- }-- if result.TenantID != tenantID {- t.Errorf("Expected tenant ID %d, got %d", tenantID, result.TenantID)- }-}--func TestValidateKey_Ed25519_InvalidSignature(t *testing.T) {- // Generate a test key pair- publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)- if err != nil {- t.Fatal(err)- }-- env.Config.License.PrivateKey = base64.StdEncoding.EncodeToString(privateKey)- env.Config.License.PublicKey = base64.StdEncoding.EncodeToString(publicKey)- defer func() {- env.Config.License.PrivateKey = ""- env.Config.License.PublicKey = ""- }()-- // Generate a valid license key- key := license.GenerateKey(42)-- // Tamper with the signature (last part of the key)- tamperedKey := key[:len(key)-4] + "XXXX"-- // Validate the tampered key- result := license.ValidateKey(tamperedKey)-- if result.IsValid {- t.Error("Expected tampered license key to be invalid")- }-- if result.Error == nil {- t.Error("Expected validation error for tampered key")- }-}--func TestValidateKey_Ed25519_WrongPublicKey(t *testing.T) {- // Generate two different key pairs- _, privateKey1, err := ed25519.GenerateKey(rand.Reader)- if err != nil {- t.Fatal(err)- }-- publicKey2, _, err := ed25519.GenerateKey(rand.Reader)- if err != nil {- t.Fatal(err)- }-- // Generate key with one private key- env.Config.License.PrivateKey = base64.StdEncoding.EncodeToString(privateKey1)- env.Config.License.PublicKey = ""- defer func() {- env.Config.License.PrivateKey = ""- env.Config.License.PublicKey = ""- }()-- key := license.GenerateKey(42)-- // Try to validate with a different public key- env.Config.License.PrivateKey = ""- env.Config.License.PublicKey = base64.StdEncoding.EncodeToString(publicKey2)-- result := license.ValidateKey(key)-- if result.IsValid {- t.Error("Expected license key to be invalid when validated with wrong public key")- }-}--func TestValidateKey_EmptyKey(t *testing.T) {- result := license.ValidateKey("")-- if result.IsValid {- t.Error("Expected empty key to be invalid")- }-- if result.Error == nil {- t.Error("Expected validation error for empty key")- }-}--func TestValidateKey_InvalidFormat(t *testing.T) {- testCases := []string{- "INVALID-KEY",- "FIDER-INVALID-123-456-789",- "FIDER-COMMERCIAL-123", // Too few parts- "FIDER-COMMERCIAL-abc-456-789", // Invalid tenant ID- "FIDER-COMMERCIAL-123-abc-789", // Invalid timestamp- }-- for _, key := range testCases {- result := license.ValidateKey(key)-- if result.IsValid {- t.Errorf("Expected key '%s' to be invalid", key)- }-- if result.Error == nil {- t.Errorf("Expected validation error for key '%s'", key)- }- }-}--func TestValidateKey_UsesEmbeddedDefault(t *testing.T) {- // Clear LICENSE_PUBLIC_KEY to test embedded default- originalPrivateKey := env.Config.License.PrivateKey- originalPublicKey := env.Config.License.PublicKey-- // Set private key to match the embedded public key (lPHzCZhOBBihIusKWs5lzXCgGxZEKBpCiplkmZSjGpU=)- // This is the corresponding private key for the DefaultPublicKey- env.Config.License.PrivateKey = "iKNP8chE8EGTivUb/+3Sx907LwSaZAFOd1BmrMFahHwt2L3gFtsUyfE45IEaokrFbJYKB3HiTTO7fMu01rPdsA=="- env.Config.License.PublicKey = "" // Leave empty to test embedded default-- defer func() {- env.Config.License.PrivateKey = originalPrivateKey- env.Config.License.PublicKey = originalPublicKey- }()-- // Generate a key with the private key- key := license.GenerateKey(123)-- // Validate without setting LICENSE_PUBLIC_KEY - should use embedded default- result := license.ValidateKey(key)-- if !result.IsValid {- t.Errorf("Expected license key to be valid using embedded default public key, but got error: %v", result.Error)- }-- if result.TenantID != 123 {- t.Errorf("Expected tenant ID 123, got %d", result.TenantID)- }-}diff --git a/app/services/sqlstore/dbEntities/README.md b/app/services/sqlstore/dbEntities/README.mdindex 6d9106320..a3f4454d9 100644--- a/app/services/sqlstore/dbEntities/README.md+++ b/app/services/sqlstore/dbEntities/README.md@@ -10,12 +10,11 @@ The `dbEntities` package provides a centralized location for database-to-model c### User (and UserProvider)-The `User` type is **exported** for use in commercial/premium features:+The `User` type is **exported** so it can be used across packages:```goimport "github.com/getfider/fider/app/services/sqlstore/dbEntities"-// Use dbEntities.User in commercial codevar user dbEntities.Usererr := trx.Get(&user, "SELECT id, name, email... FROM users WHERE id = $1", userID)if err != nil {@@ -30,31 +29,10 @@ entityUser := user.ToModel(ctx)All other types (comment, post, tag, tenant, etc.) are **unexported** (lowercase) and only used internally by the `postgres` package. They can be exported later if needed by simply capitalizing the type name and its `toModel` method.-## Architecture--**Current State:**-- `postgres` package: Contains all the db* struct definitions and uses them directly-- `dbEntities` package: Contains the same struct definitions with User exported-- Both coexist without conflicts--**Usage Pattern:**-- Regular Fider code continues using `postgres` package as before-- Commercial/premium code can import and use `dbEntities.User` directly-- No changes needed to existing `postgres` code--## Converting Additional Types--To export another type for commercial use:--1. Open the corresponding file (e.g., `comment.go`, `post.go`)-2. Capitalize the struct name: `type comment` → `type Comment`-3. Capitalize the method: `func (c *comment) toModel` → `func (c *Comment) ToModel`-4. Update any internal references if needed-## TestingThe package includes unit tests for the exported User type. Run them with:```bashgodotenv -f .test.env go test ./app/services/sqlstore/dbEntities/...-```\ No newline at end of file+```diff --git a/app/services/sqlstore/dbEntities/billing.go b/app/services/sqlstore/dbEntities/billing.goindex 295078e37..2502084f2 100644--- a/app/services/sqlstore/dbEntities/billing.go+++ b/app/services/sqlstore/dbEntities/billing.go@@ -7,6 +7,5 @@ import (type StripeBillingState struct {StripeCustomerID dbx.NullString `db:"stripe_customer_id"`StripeSubscriptionID dbx.NullString `db:"stripe_subscription_id"`- LicenseKey dbx.NullString `db:"license_key"`PaddleSubscriptionID dbx.NullString `db:"paddle_subscription_id"`}diff --git a/app/services/sqlstore/dbEntities/tenant.go b/app/services/sqlstore/dbEntities/tenant.goindex dad5671d7..bdd710e90 100644--- a/app/services/sqlstore/dbEntities/tenant.go+++ b/app/services/sqlstore/dbEntities/tenant.go@@ -4,29 +4,28 @@ import ("github.com/getfider/fider/app/models/entity""github.com/getfider/fider/app/models/enum""github.com/getfider/fider/app/pkg/env"- "github.com/getfider/fider/app/services")type Tenant struct {- ID int `db:"id"`- Name string `db:"name"`- Subdomain string `db:"subdomain"`- CNAME string `db:"cname"`- Invitation string `db:"invitation"`- WelcomeMessage string `db:"welcome_message"`- WelcomeHeader string `db:"welcome_header"`- Status int `db:"status"`- Locale string `db:"locale"`- IsPrivate bool `db:"is_private"`- LogoBlobKey string `db:"logo_bkey"`- CustomCSS string `db:"custom_css"`- AllowedSchemes string `db:"allowed_schemes"`- IsEmailAuthAllowed bool `db:"is_email_auth_allowed"`- IsFeedEnabled bool `db:"is_feed_enabled"`- PreventIndexing bool `db:"prevent_indexing"`- IsModerationEnabled bool `db:"is_moderation_enabled"`- IsPro bool `db:"is_pro"`- HasPaddleSubscription bool `db:"has_paddle_subscription"`+ ID int `db:"id"`+ Name string `db:"name"`+ Subdomain string `db:"subdomain"`+ CNAME string `db:"cname"`+ Invitation string `db:"invitation"`+ WelcomeMessage string `db:"welcome_message"`+ WelcomeHeader string `db:"welcome_header"`+ Status int `db:"status"`+ Locale string `db:"locale"`+ IsPrivate bool `db:"is_private"`+ LogoBlobKey string `db:"logo_bkey"`+ CustomCSS string `db:"custom_css"`+ AllowedSchemes string `db:"allowed_schemes"`+ IsEmailAuthAllowed bool `db:"is_email_auth_allowed"`+ IsFeedEnabled bool `db:"is_feed_enabled"`+ PreventIndexing bool `db:"prevent_indexing"`+ IsModerationEnabled bool `db:"is_moderation_enabled"`+ IsPro bool `db:"is_pro"`+ HasPaddleSubscription bool `db:"has_paddle_subscription"`}func (t *Tenant) ToModel() *entity.Tenant {@@ -34,35 +33,32 @@ func (t *Tenant) ToModel() *entity.Tenant {return nil}- // Compute hasCommercialFeatures based on hosting mode- var hasCommercialFeatures bool- if env.IsSingleHostMode() {- // Self-hosted: check if license service validated successfully- hasCommercialFeatures = services.IsCommercialFeatureEnabled(services.FeatureContentModeration)- } else {- // Hosted multi-tenant: check if this tenant has Pro subscription or legacy Paddle subscription- hasCommercialFeatures = t.IsPro || t.HasPaddleSubscription+ // Self-hosted: all features are available (isPro = true)+ // Hosted multi-tenant: isPro based on subscription status+ isPro := true+ if env.IsMultiHostMode() {+ isPro = t.IsPro || t.HasPaddleSubscription}tenant := &entity.Tenant{- ID: t.ID,- Name: t.Name,- Subdomain: t.Subdomain,- CNAME: t.CNAME,- Invitation: t.Invitation,- WelcomeMessage: t.WelcomeMessage,- WelcomeHeader: t.WelcomeHeader,- Status: enum.TenantStatus(t.Status),- Locale: t.Locale,- IsPrivate: t.IsPrivate,- LogoBlobKey: t.LogoBlobKey,- CustomCSS: t.CustomCSS,- AllowedSchemes: t.AllowedSchemes,- IsEmailAuthAllowed: t.IsEmailAuthAllowed,- IsFeedEnabled: t.IsFeedEnabled,- PreventIndexing: t.PreventIndexing,- IsModerationEnabled: t.IsModerationEnabled,- HasCommercialFeatures: hasCommercialFeatures,+ ID: t.ID,+ Name: t.Name,+ Subdomain: t.Subdomain,+ CNAME: t.CNAME,+ Invitation: t.Invitation,+ WelcomeMessage: t.WelcomeMessage,+ WelcomeHeader: t.WelcomeHeader,+ Status: enum.TenantStatus(t.Status),+ Locale: t.Locale,+ IsPrivate: t.IsPrivate,+ LogoBlobKey: t.LogoBlobKey,+ CustomCSS: t.CustomCSS,+ AllowedSchemes: t.AllowedSchemes,+ IsEmailAuthAllowed: t.IsEmailAuthAllowed,+ IsFeedEnabled: t.IsFeedEnabled,+ PreventIndexing: t.PreventIndexing,+ IsModerationEnabled: isPro && t.IsModerationEnabled,+ IsPro: isPro,}return tenantdiff --git a/app/services/sqlstore/postgres/billing.go b/app/services/sqlstore/postgres/billing.goindex f153e4910..0d055bced 100644--- a/app/services/sqlstore/postgres/billing.go+++ b/app/services/sqlstore/postgres/billing.go@@ -50,7 +50,7 @@ func getStripeBillingState(ctx context.Context, q *query.GetStripeBillingState)return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {state := dbEntities.StripeBillingState{}err := trx.Get(&state,- `SELECT stripe_customer_id, stripe_subscription_id, license_key, paddle_subscription_id+ `SELECT stripe_customer_id, stripe_subscription_id, paddle_subscription_idFROM tenants_billingWHERE tenant_id = $1`, tenant.ID)@@ -66,7 +66,6 @@ func getStripeBillingState(ctx context.Context, q *query.GetStripeBillingState)q.Result = &entity.StripeBillingState{CustomerID: state.StripeCustomerID.String,SubscriptionID: state.StripeSubscriptionID.String,- LicenseKey: state.LicenseKey.String,PaddleSubscriptionID: state.PaddleSubscriptionID.String,}return nil@@ -92,11 +91,11 @@ func activateStripeSubscription(ctx context.Context, c *cmd.ActivateStripeSubscr}_, err = trx.Execute(`- INSERT INTO tenants_billing (tenant_id, stripe_customer_id, stripe_subscription_id, license_key)- VALUES ($1, $2, $3, $4)+ INSERT INTO tenants_billing (tenant_id, stripe_customer_id, stripe_subscription_id)+ VALUES ($1, $2, $3)ON CONFLICT (tenant_id) DO UPDATE- SET stripe_customer_id = $2, stripe_subscription_id = $3, license_key = $4, paddle_subscription_id = NULL- `, c.TenantID, c.CustomerID, c.SubscriptionID, c.LicenseKey)+ SET stripe_customer_id = $2, stripe_subscription_id = $3, paddle_subscription_id = NULL+ `, c.TenantID, c.CustomerID, c.SubscriptionID)if err != nil {return errors.Wrap(err, "failed to activate stripe subscription")}diff --git a/app/services/sqlstore/postgres/moderation.go b/app/services/sqlstore/postgres/moderation.goindex e4a76d3d4..7f3f02c38 100644--- a/app/services/sqlstore/postgres/moderation.go+++ b/app/services/sqlstore/postgres/moderation.go@@ -2,48 +2,272 @@ package postgresimport ("context"+ "fmt"+ "time""github.com/getfider/fider/app/models/cmd"+ "github.com/getfider/fider/app/models/entity"+ "github.com/getfider/fider/app/models/enum""github.com/getfider/fider/app/models/query"+ "github.com/getfider/fider/app/pkg/bus"+ "github.com/getfider/fider/app/pkg/dbx""github.com/getfider/fider/app/pkg/errors"+ "github.com/getfider/fider/app/services/sqlstore/dbEntities")-// Stub functions - commercial license required for content moderation-func approvePost(ctx context.Context, c *cmd.ApprovePost) error {- return errors.New("Content moderation requires commercial license")+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {+ _, err := trx.Execute(`+ UPDATE posts SET is_approved = true+ WHERE id = $1 AND tenant_id = $2`, c.PostID, tenant.ID)+ if err != nil {+ return errors.Wrap(err, "failed to approve post")+ }+ return nil+ })}func declinePost(ctx context.Context, c *cmd.DeclinePost) error {- return errors.New("Content moderation requires commercial license")+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {+ getPost := &query.GetPostByID{PostID: c.PostID}+ if err := bus.Dispatch(ctx, getPost); err != nil {+ return err+ }++ setResponse := &cmd.SetPostResponse{+ Post: getPost.Result,+ Text: "Post declined during moderation",+ Status: enum.PostDeleted,+ }++ return bus.Dispatch(ctx, setResponse)+ })}func approveComment(ctx context.Context, c *cmd.ApproveComment) error {- return errors.New("Content moderation requires commercial license")+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {+ _, err := trx.Execute(`+ UPDATE comments SET is_approved = true+ WHERE id = $1 AND tenant_id = $2`, c.CommentID, tenant.ID)+ if err != nil {+ return errors.Wrap(err, "failed to approve comment")+ }+ return nil+ })}func declineComment(ctx context.Context, c *cmd.DeclineComment) error {- return errors.New("Content moderation requires commercial license")+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {+ deleteComment := &cmd.DeleteComment{CommentID: c.CommentID}+ return bus.Dispatch(ctx, deleteComment)+ })}func bulkApproveItems(ctx context.Context, c *cmd.BulkApproveItems) error {- return errors.New("Content moderation requires commercial license")+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {+ if len(c.PostIDs) > 0 {+ postIDsStr := ""+ for i, id := range c.PostIDs {+ if i > 0 {+ postIDsStr += ","+ }+ postIDsStr += fmt.Sprintf("%d", id)+ }+ _, err := trx.Execute(fmt.Sprintf(`+ UPDATE posts SET is_approved = true+ WHERE id IN (%s) AND tenant_id = $1`, postIDsStr), tenant.ID)+ if err != nil {+ return errors.Wrap(err, "failed to bulk approve posts")+ }+ }++ if len(c.CommentIDs) > 0 {+ commentIDsStr := ""+ for i, id := range c.CommentIDs {+ if i > 0 {+ commentIDsStr += ","+ }+ commentIDsStr += fmt.Sprintf("%d", id)+ }+ _, err := trx.Execute(fmt.Sprintf(`+ UPDATE comments SET is_approved = true+ WHERE id IN (%s) AND tenant_id = $1`, commentIDsStr), tenant.ID)+ if err != nil {+ return errors.Wrap(err, "failed to bulk approve comments")+ }+ }++ return nil+ })}func bulkDeclineItems(ctx context.Context, c *cmd.BulkDeclineItems) error {- return errors.New("Content moderation requires commercial license")+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {+ if len(c.PostIDs) > 0 {+ for _, postID := range c.PostIDs {+ getPost := &query.GetPostByID{PostID: postID}+ if err := bus.Dispatch(ctx, getPost); err != nil {+ return errors.Wrap(err, "failed to get post for bulk decline")+ }++ setResponse := &cmd.SetPostResponse{+ Post: getPost.Result,+ Text: "Post declined during bulk moderation",+ Status: enum.PostDeleted,+ }++ if err := bus.Dispatch(ctx, setResponse); err != nil {+ return errors.Wrap(err, "failed to bulk decline post")+ }+ }+ }++ if len(c.CommentIDs) > 0 {+ for _, commentID := range c.CommentIDs {+ deleteComment := &cmd.DeleteComment{CommentID: commentID}+ if err := bus.Dispatch(ctx, deleteComment); err != nil {+ return errors.Wrap(err, "failed to bulk decline comment")+ }+ }+ }++ return nil+ })+}++type dbModerationPost struct {+ ID int `db:"id"`+ Number int `db:"number"`+ Title string `db:"title"`+ Slug string `db:"slug"`+ Description string `db:"description"`+ CreatedAt time.Time `db:"created_at"`+ User *dbEntities.User `db:"user"`+}++type dbModerationComment struct {+ ID int `db:"id"`+ PostID int `db:"post_id"`+ PostNumber int `db:"post_number"`+ PostSlug string `db:"post_slug"`+ Content string `db:"content"`+ CreatedAt time.Time `db:"created_at"`+ User *dbEntities.User `db:"user"`+ PostTitle string `db:"post_title"`}func getModerationItems(ctx context.Context, q *query.GetModerationItems) error {- q.Result = make([]*query.ModerationItem, 0)- return nil+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {+ q.Result = make([]*query.ModerationItem, 0)++ var posts []*dbModerationPost++ err := trx.Select(&posts, `+ SELECT p.id, p.number, p.title, p.slug, p.description, p.created_at,+ u.id AS user_id,+ u.name AS user_name,+ u.email AS user_email,+ u.role AS user_role,+ u.status AS user_status,+ u.avatar_type AS user_avatar_type,+ u.avatar_bkey AS user_avatar_bkey+ FROM posts p+ INNER JOIN users u ON u.id = p.user_id AND u.tenant_id = p.tenant_id+ WHERE p.tenant_id = $1 AND p.is_approved = false and p.status <> $2+ ORDER BY p.created_at DESC`, tenant.ID, enum.PostDeleted)+ if err != nil {+ return errors.Wrap(err, "failed to get unmoderated posts")+ }++ for _, post := range posts {+ userWithEmail := &entity.UserWithEmail{+ User: post.User.ToModel(ctx),+ }++ q.Result = append(q.Result, &query.ModerationItem{+ Type: "post",+ ID: post.ID,+ PostNumber: post.Number,+ PostSlug: post.Slug,+ Title: post.Title,+ Content: post.Description,+ CreatedAt: post.CreatedAt,+ User: userWithEmail,+ })+ }++ var comments []*dbModerationComment++ err = trx.Select(&comments, `+ SELECT c.id, c.post_id, p.number as post_number, p.slug as post_slug, c.content, c.created_at,+ u.id AS user_id,+ u.name AS user_name,+ u.email AS user_email,+ u.role AS user_role,+ u.status AS user_status,+ u.avatar_type AS user_avatar_type,+ u.avatar_bkey AS user_avatar_bkey,+ p.title as post_title+ FROM comments c+ INNER JOIN users u ON u.id = c.user_id AND u.tenant_id = c.tenant_id+ INNER JOIN posts p ON p.id = c.post_id AND p.tenant_id = c.tenant_id+ WHERE c.tenant_id = $1 AND c.is_approved = false and p.status <> $2+ AND c.deleted_at IS NULL+ ORDER BY c.created_at DESC`, tenant.ID, enum.PostDeleted)+ if err != nil {+ return errors.Wrap(err, "failed to get unmoderated comments")+ }++ for _, comment := range comments {+ userWithEmail := &entity.UserWithEmail{+ User: comment.User.ToModel(ctx),+ }++ q.Result = append(q.Result, &query.ModerationItem{+ Type: "comment",+ ID: comment.ID,+ PostID: comment.PostID,+ PostNumber: comment.PostNumber,+ PostSlug: comment.PostSlug,+ Content: comment.Content,+ CreatedAt: comment.CreatedAt,+ PostTitle: comment.PostTitle,+ User: userWithEmail,+ })+ }++ return nil+ })}func getModerationCount(ctx context.Context, q *query.GetModerationCount) error {- q.Result = 0- return nil+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {+ var count int++ err := trx.Get(&count, `+ SELECT+ (SELECT COUNT(*) FROM posts WHERE tenant_id = $1 AND is_approved = false and status <> $2) ++ (SELECT COUNT(*) FROM comments c JOIN posts p on c.post_id = p.id WHERE p.tenant_id = $1 AND c.is_approved = false AND p.status <> $2 AND c.deleted_at IS NULL)+ `, tenant.ID, enum.PostDeleted)++ if err != nil {+ return errors.Wrap(err, "failed to get moderation count")+ }++ q.Result = count+ return nil+ })}func trustUser(ctx context.Context, c *cmd.TrustUser) error {- return errors.New("Content moderation requires commercial license")-}\ No newline at end of file+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {+ _, err := trx.Execute(`+ UPDATE users SET is_trusted = true, status = $1+ WHERE id = $2 AND tenant_id = $3`, enum.UserActive, c.UserID, tenant.ID)+ if err != nil {+ return errors.Wrap(err, "failed to trust user")+ }++ return nil+ })+}diff --git a/app/services/sqlstore/postgres/postgres.go b/app/services/sqlstore/postgres/postgres.goindex ea34d695a..cc672ed5d 100644--- a/app/services/sqlstore/postgres/postgres.go+++ b/app/services/sqlstore/postgres/postgres.go@@ -4,7 +4,6 @@ import ("context""github.com/getfider/fider/app"- "github.com/getfider/fider/app/services""github.com/getfider/fider/app/models/entity""github.com/getfider/fider/app/pkg/bus"@@ -148,19 +147,15 @@ func (s Service) Init() {bus.AddHandler(AddMentionNotification)bus.AddHandler(getMentionsNotifications)- // Only register moderation handlers if commercial service is not available- // Check if commercial features are enabled via license service- if !services.IsCommercialFeatureEnabled(services.FeatureContentModeration) {- bus.AddHandler(approvePost)- bus.AddHandler(declinePost)- bus.AddHandler(approveComment)- bus.AddHandler(declineComment)- bus.AddHandler(bulkApproveItems)- bus.AddHandler(bulkDeclineItems)- bus.AddHandler(getModerationItems)- bus.AddHandler(getModerationCount)- bus.AddHandler(trustUser)- }+ bus.AddHandler(approvePost)+ bus.AddHandler(declinePost)+ bus.AddHandler(approveComment)+ bus.AddHandler(declineComment)+ bus.AddHandler(bulkApproveItems)+ bus.AddHandler(bulkDeclineItems)+ bus.AddHandler(getModerationItems)+ bus.AddHandler(getModerationCount)+ bus.AddHandler(trustUser)}type SqlHandler func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) errordiff --git a/app/tasks/userlist.go b/app/tasks/userlist.goindex c3bf9aa9d..8d2f1ef8a 100644--- a/app/tasks/userlist.go+++ b/app/tasks/userlist.go@@ -20,7 +20,7 @@ func UserListCreateCompany(tenant entity.Tenant, user entity.User) worker.Task {})plan := enum.PlanFree- if tenant.HasCommercialFeatures {+ if tenant.IsPro {plan = enum.PlanPro}diff --git a/commercial/LICENSE b/commercial/LICENSEdeleted file mode 100644index d630d59b4..000000000--- a/commercial/LICENSE+++ /dev/null@@ -1,30 +0,0 @@-Fider Commercial License--Copyright (c) 2026 Fider--This software and associated documentation files (the "Software") contained within this-"commercial" directory are proprietary and confidential to Fider.--RESTRICTIONS:--- You may NOT use, copy, modify, merge, publish, distribute, sublicense, or sell copies- of this Software without a valid commercial license from Fider.-- You may NOT create derivative works based on this Software.-- You may NOT reverse engineer, decompile, or disassemble this Software.--PERMITTED USES:--- You may view this Software's source code for evaluation purposes only.-- You may use this Software in non-production development and testing environments.-- Licensed users with valid commercial agreements may use this Software in production- in accordance with their license terms.--NO WARRANTY:-This Software is provided "as is", without warranty of any kind, express or implied,-including but not limited to the warranties of merchantability, fitness for a particular-purpose and noninfringement.--For commercial licensing inquiries, please contact: [[email protected]]--All other code in this repository (outside this "commercial" directory) remains under-the AGPL-3.0 license as specified in the root LICENSE file.diff --git a/commercial/handlers/apiv1/moderation.go b/commercial/handlers/apiv1/moderation.godeleted file mode 100644index a930ec17c..000000000--- a/commercial/handlers/apiv1/moderation.go+++ /dev/null@@ -1,193 +0,0 @@-package apiv1--import (- "strconv"-- "github.com/getfider/fider/app/models/cmd"- "github.com/getfider/fider/app/models/query"- "github.com/getfider/fider/app/pkg/bus"- "github.com/getfider/fider/app/pkg/log"- "github.com/getfider/fider/app/pkg/web"-)--// ApprovePost approves a post-func ApprovePost() web.HandlerFunc {- return func(c *web.Context) error {- postID, err := strconv.Atoi(c.Param("id"))- if err != nil {- return c.BadRequest(web.Map{"error": "Invalid post ID"})- }-- if err := bus.Dispatch(c, &cmd.ApprovePost{PostID: postID}); err != nil {- return c.Failure(err)- }-- return c.Ok(web.Map{})- }-}--// DeclinePost declines (deletes) a post-func DeclinePost() web.HandlerFunc {- return func(c *web.Context) error {- postID, err := strconv.Atoi(c.Param("id"))- if err != nil {- return c.BadRequest(web.Map{"error": "Invalid post ID"})- }-- if err := bus.Dispatch(c, &cmd.DeclinePost{PostID: postID}); err != nil {- return c.Failure(err)- }-- return c.Ok(web.Map{})- }-}--// ApproveComment approves a comment-func ApproveComment() web.HandlerFunc {- return func(c *web.Context) error {- commentID, err := strconv.Atoi(c.Param("id"))- if err != nil {- return c.BadRequest(web.Map{"error": "Invalid comment ID"})- }-- if err := bus.Dispatch(c, &cmd.ApproveComment{CommentID: commentID}); err != nil {- return c.Failure(err)- }-- return c.Ok(web.Map{})- }-}--// DeclineComment declines (deletes) a comment-func DeclineComment() web.HandlerFunc {- return func(c *web.Context) error {- commentID, err := strconv.Atoi(c.Param("id"))- if err != nil {- return c.BadRequest(web.Map{"error": "Invalid comment ID"})- }-- if err := bus.Dispatch(c, &cmd.DeclineComment{CommentID: commentID}); err != nil {- return c.Failure(err)- }-- return c.Ok(web.Map{})- }-}--// DeclinePostAndBlock declines (deletes) a post and blocks the user-func DeclinePostAndBlock() web.HandlerFunc {- return func(c *web.Context) error {-- // Get the post that is being declined- postID, err := strconv.Atoi(c.Param("id"))- if err != nil {- return c.BadRequest(web.Map{"error": "Invalid post ID"})- }-- getPost := &query.GetPostByID{PostID: postID}- if err := bus.Dispatch(c, getPost); err != nil {- return c.Failure(err)- }-- // Call the existing BlockUser command inside the DeclinePostAndBlock handler- err = bus.Dispatch(c, &cmd.BlockUser{UserID: getPost.Result.User.ID})- if err != nil {- return c.Failure(err)- }-- // Finally call the existing DeclinePost command- err = bus.Dispatch(c, &cmd.DeclinePost{PostID: postID})- if err != nil {- return c.Failure(err)- }-- return c.Ok(web.Map{})- }-}--// DeclineCommentAndBlock declines (deletes) a comment and blocks the user-func DeclineCommentAndBlock() web.HandlerFunc {- return func(c *web.Context) error {- // Get the comment that is being declined- commentID, err := strconv.Atoi(c.Param("id"))- if err != nil {- return c.BadRequest(web.Map{"error": "Invalid comment ID"})- }-- getComment := &query.GetCommentByID{CommentID: commentID}- if err := bus.Dispatch(c, getComment); err != nil {- return c.Failure(err)- }-- // Call the existing BlockUser command inside the DeclinePostAndBlock handler- err = bus.Dispatch(c, &cmd.BlockUser{UserID: getComment.Result.User.ID})- if err != nil {- return c.Failure(err)- }-- // Finally call the existing DeclinePost command- err = bus.Dispatch(c, &cmd.DeclineComment{CommentID: commentID})- if err != nil {- return c.Failure(err)- }-- return c.Ok(web.Map{})- }-}--// ApprovePostAndVerify approves a post and verifies the user-func ApprovePostAndVerify() web.HandlerFunc {- return func(c *web.Context) error {- postID, err := strconv.Atoi(c.Param("id"))- if err != nil {- return c.BadRequest(web.Map{"error": "Invalid post ID"})- }-- // Get the post that is being approved- getPost := &query.GetPostByID{PostID: postID}- if err := bus.Dispatch(c, getPost); err != nil {- return c.Failure(err)- }-- // First approve the post- if err := bus.Dispatch(c, &cmd.ApprovePost{PostID: postID}); err != nil {- return c.Failure(err)- }-- // Then trust the user- if err := bus.Dispatch(c, &cmd.TrustUser{UserID: getPost.Result.User.ID}); err != nil {- return c.Failure(err)- }-- return c.Ok(web.Map{})- }-}--// ApproveCommentAndVerify approves a comment and verifies the user-func ApproveCommentAndVerify() web.HandlerFunc {- return func(c *web.Context) error {- log.Info(c, "Approving comment and verifying user")- commentID, err := strconv.Atoi(c.Param("id"))- if err != nil {- return c.BadRequest(web.Map{"error": "Invalid comment ID"})- }-- // Get the comment that is being approved- getComment := &query.GetCommentByID{CommentID: commentID}- if err := bus.Dispatch(c, getComment); err != nil {- return c.Failure(err)- }-- // First approve the comment- if err := bus.Dispatch(c, &cmd.ApproveComment{CommentID: commentID}); err != nil {- return c.Failure(err)- }-- // Then trust the user- if err := bus.Dispatch(c, &cmd.TrustUser{UserID: getComment.Result.User.ID}); err != nil {- return c.Failure(err)- }-- return c.Ok(web.Map{})- }-}\ No newline at end of filediff --git a/commercial/handlers/moderation.go b/commercial/handlers/moderation.godeleted file mode 100644index 4aaa05b6c..000000000--- a/commercial/handlers/moderation.go+++ /dev/null@@ -1,49 +0,0 @@-package handlers--import (- "net/http"-- "github.com/getfider/fider/app/models/query"- "github.com/getfider/fider/app/pkg/bus"- "github.com/getfider/fider/app/pkg/log"- "github.com/getfider/fider/app/pkg/web"-)--// ModerationPage is the commercial moderation administration page-func ModerationPage() web.HandlerFunc {- return func(c *web.Context) error {- return c.Page(http.StatusOK, web.Props{- Page: "Administration/pages/ContentModeration.page",- Title: "Moderation · Site Settings",- })- }-}--// GetModerationItems returns all unmoderated posts and comments-func GetModerationItems() web.HandlerFunc {- return func(c *web.Context) error {- q := &query.GetModerationItems{}- if err := bus.Dispatch(c, q); err != nil {- return c.Failure(err)- }-- return c.Ok(web.Map{- "items": q.Result,- })- }-}--// GetModerationCount returns the count of items awaiting moderation-func GetModerationCount() web.HandlerFunc {- return func(c *web.Context) error {- log.Info(c, "Getting the moderation count commercial")- q := &query.GetModerationCount{}- if err := bus.Dispatch(c, q); err != nil {- return c.Failure(err)- }-- return c.Ok(web.Map{- "count": q.Result,- })- }-}diff --git a/commercial/init.go b/commercial/init.godeleted file mode 100644index 6380a8908..000000000--- a/commercial/init.go+++ /dev/null@@ -1,104 +0,0 @@-package commercial--import (- "context"-- "github.com/getfider/fider/app/handlers"- "github.com/getfider/fider/app/handlers/apiv1"- "github.com/getfider/fider/app/models/dto"- "github.com/getfider/fider/app/pkg/env"- "github.com/getfider/fider/app/pkg/log"- "github.com/getfider/fider/app/services"- "github.com/getfider/fider/app/services/license"- commercialHandlers "github.com/getfider/fider/commercial/handlers"- commercialApiv1 "github.com/getfider/fider/commercial/handlers/apiv1"-)--// Commercial license service implementation-type commercialLicenseService struct {- isValid bool- tenantID int-}--func init() {- ctx := context.Background()- var svc *commercialLicenseService-- // Development/test mode: enable all commercial features without license key- // Note: Production use of commercial features requires a valid license- if env.Config.Environment != "production" {- svc = &commercialLicenseService{- isValid: true,- tenantID: 0,- }- log.Warnf(ctx, "Running in @{Environment} mode - commercial features enabled for development/testing. Production use requires a license from https://fider.io", dto.Props{- "Environment": env.Config.Environment,- })- } else if env.IsSingleHostMode() && env.Config.License.Key != "" {- // Production self-hosted with license key: validate at startup- result := license.ValidateKey(env.Config.License.Key)- if !result.IsValid {- panic(result.Error)- }-- svc = &commercialLicenseService{- isValid: true,- tenantID: result.TenantID,- }-- log.Infof(ctx, "Commercial license validated for tenant @{TenantID}", dto.Props{- "TenantID": result.TenantID,- })- } else {- // Multi-tenant hosted OR self-hosted without key- svc = &commercialLicenseService{isValid: env.IsMultiHostMode()}- }-- // Register commercial license service- services.License = svc-- // Always register commercial handlers (they check licensing internally)- handlers.RegisterModerationHandlers(- commercialHandlers.ModerationPage,- commercialHandlers.GetModerationItems,- commercialHandlers.GetModerationCount,- )-- apiv1.RegisterModerationHandlers(- commercialApiv1.ApprovePost,- commercialApiv1.DeclinePost,- commercialApiv1.ApproveComment,- commercialApiv1.DeclineComment,- commercialApiv1.DeclinePostAndBlock,- commercialApiv1.DeclineCommentAndBlock,- commercialApiv1.ApprovePostAndVerify,- commercialApiv1.ApproveCommentAndVerify,- )-}--func (s *commercialLicenseService) IsCommercialFeatureEnabled(feature string) bool {- // In self-hosted mode, check license validity- if env.IsSingleHostMode() {- return s.isValid && feature == services.FeatureContentModeration- }-- // In multi-tenant mode, this is a global check- // Per-tenant checking happens via tenant.HasCommercialFeatures- return true-}--func (s *commercialLicenseService) GetLicenseInfo() *services.LicenseInfo {- if s.isValid {- return &services.LicenseInfo{- IsValid: true,- Features: []string{services.FeatureContentModeration},- LicenseHolder: "Licensed",- }- }-- return &services.LicenseInfo{- IsValid: false,- Features: []string{},- LicenseHolder: "Unlicensed",- }-}diff --git a/commercial/pages/Administration/ContentModeration.page.tsx b/commercial/pages/Administration/ContentModeration.page.tsxdeleted file mode 100644index 92de3cfd2..000000000--- a/commercial/pages/Administration/ContentModeration.page.tsx+++ /dev/null@@ -1,294 +0,0 @@-import "./ContentModeration.page.scss"--import React, { useState, useEffect } from "react"-import { Button, Avatar, Loader, Icon, Markdown } from "@fider/components/common"-import { Header } from "@fider/components"-import { HStack, VStack } from "@fider/components/layout"-import { actions, chopString, http, notify } from "@fider/services"-import { User, UserStatus } from "@fider/models"-import { useFider } from "@fider/hooks"-import { Trans } from "@lingui/react/macro"-import IconCheck from "@fider/assets/images/heroicons-check.svg"-import IconX from "@fider/assets/images/heroicons-x.svg"-import IconShieldCheck from "@fider/assets/images/heroicons-shieldcheck.svg"-import IconBan from "@fider/assets/images/heroicons-x-circle.svg"-import { Moment } from "@fider/components/common"--interface ModerationItem {- type: "post" | "comment"- id: number- postId?: number- postNumber?: number- postSlug?: string- title?: string- content: string- user: User- createdAt: string- postTitle?: string-}--interface ContentModerationPageState {- items: ModerationItem[]- loading: boolean-}--const ContentModerationPage = () => {- const [state, setState] = useState<ContentModerationPageState>({- items: [],- loading: true,- })- const fider = useFider()-- const fetchItems = async () => {- setState((prev) => ({ ...prev, loading: true }))- const result = await http.get<{ items: ModerationItem[] }>("/_api/admin/moderation/items")- if (result.ok) {- setState({ items: result.data.items, loading: false })- } else {- setState((prev) => ({ ...prev, loading: false }))- notify.error(<Trans id="moderation.fetch.error">Failed to fetch moderation items</Trans>)- }- }-- useEffect(() => {- fetchItems()- }, [])-- const handleApprovePost = async (postId: number) => {- const result = await actions.approvePost(postId)- if (result.ok) {- notify.success(<Trans id="moderation.post.published">Post published successfully</Trans>)- setState((prev) => ({- ...prev,- items: prev.items.filter((item) => !(item.type === "post" && item.id === postId)),- }))- } else {- notify.error(<Trans id="moderation.post.publish.error">Failed to publish post</Trans>)- }- }-- const handleDeclinePost = async (postId: number) => {- const result = await actions.declinePost(postId)- if (result.ok) {- notify.success(<Trans id="moderation.post.deleted">Post deleted successfully</Trans>)- setState((prev) => ({- ...prev,- items: prev.items.filter((item) => !(item.type === "post" && item.id === postId)),- }))- } else {- notify.error(<Trans id="moderation.post.delete.error">Failed to delete post</Trans>)- }- }-- const handleApproveComment = async (commentId: number) => {- const result = await actions.approveComment(commentId)- if (result.ok) {- notify.success(<Trans id="moderation.comment.published">Comment published successfully</Trans>)- setState((prev) => ({- ...prev,- items: prev.items.filter((item) => !(item.type === "comment" && item.id === commentId)),- }))- } else {- notify.error(<Trans id="moderation.comment.publish.error">Failed to publish comment</Trans>)- }- }-- const handleDeclineComment = async (commentId: number) => {- const result = await actions.declineComment(commentId)- if (result.ok) {- notify.success(<Trans id="moderation.comment.deleted">Comment deleted successfully</Trans>)- setState((prev) => ({- ...prev,- items: prev.items.filter((item) => !(item.type === "comment" && item.id === commentId)),- }))- } else {- notify.error(<Trans id="moderation.comment.delete.error">Failed to delete comment</Trans>)- }- }-- const handleApprovePostAndVerify = async (postId: number) => {- const result = await actions.approvePostAndVerify(postId)- if (result.ok) {- notify.success(<Trans id="moderation.post.published.verified">Post published and user verified</Trans>)- setState((prev) => ({- ...prev,- items: prev.items.filter((item) => !(item.type === "post" && item.id === postId)),- }))- } else {- notify.error(<Trans id="moderation.post.publish.verify.error">Failed to publish post and verify user</Trans>)- }- }-- const handleDeclinePostAndBlock = async (postId: number) => {- const result = await actions.declinePostAndBlock(postId)- if (result.ok) {- notify.success(<Trans id="moderation.post.deleted.blocked">Post deleted and user blocked</Trans>)- setState((prev) => ({- ...prev,- items: prev.items.filter((item) => !(item.type === "post" && item.id === postId)),- }))- } else {- notify.error(<Trans id="moderation.post.delete.block.error">Failed to delete post and block user</Trans>)- }- }-- const handleApproveCommentAndVerify = async (commentId: number) => {- const result = await actions.approveCommentAndVerify(commentId)- if (result.ok) {- notify.success(<Trans id="moderation.comment.published.verified">Comment published and user verified</Trans>)- setState((prev) => ({- ...prev,- items: prev.items.filter((item) => !(item.type === "comment" && item.id === commentId)),- }))- } else {- notify.error(<Trans id="moderation.comment.publish.verify.error">Failed to publish comment and verify user</Trans>)- }- }-- const handleDeclineCommentAndBlock = async (commentId: number) => {- const result = await actions.declineCommentAndBlock(commentId)- if (result.ok) {- notify.success(<Trans id="moderation.comment.deleted.blocked">Comment deleted and user blocked</Trans>)- setState((prev) => ({- ...prev,- items: prev.items.filter((item) => !(item.type === "comment" && item.id === commentId)),- }))- } else {- notify.error(<Trans id="moderation.comment.delete.block.error">Failed to delete comment and block user</Trans>)- }- }-- const renderDivider = (title: string, count: number) => {- return (- <div className="c-moderation-page__divider">- <div className="c-moderation-page__divider-title">- {title} ({count})- </div>- </div>- )- }-- const handlePostClick = (link: string) => {- window.location.href = link- }-- const renderModerationItem = (item: ModerationItem) => {- const title = item.type == "post" ? item.title : item.postTitle- const link = item.type == "post" ? `/posts/${item.postNumber}/${item.postSlug}` : `/posts/${item.postNumber}/${item.postSlug}#comment-${item.id}`- const blocked = item.user.status === UserStatus.Blocked && <span className="text-red-700">blocked</span>-- return (- <div key={`${item.type}-${item.id}`} className="c-moderation-item" onClick={() => handlePostClick(link)}>- <div className="c-moderation-item__content">- <div className="c-moderation-item__header">- <HStack spacing={4} align="start">- <Avatar user={item.user} size="large" />- <VStack spacing={1} className="flex-grow c-moderation-item__user-info">- <div className="text-semibold c-moderation-item__user-name">{item.user.name}</div>- <div className="c-moderation-item__user-email"><{item.user.email}></div>- {blocked && <span className="text-red-700">{blocked}</span>}- </VStack>- </HStack>- <div className="c-moderation-item__timestamp">- <Moment date={item.createdAt} locale={fider.currentLocale} />- </div>- </div>-- <VStack spacing={2} className="c-moderation-item__body">- {item.type === "post" && <h3 className="text-semibold m-0">{title}</h3>}- <div className="text-body text-break">- <Markdown text={chopString(item.content, 200)} style="plainText" />- </div>- {item.type === "comment" && <div className="text-muted text-break">{title}</div>}-- <div className="c-moderation-item__actions invisible" onClick={(e) => e.stopPropagation()}>- <Button size="small" variant="secondary" onClick={() => (item.type === "post" ? handleApprovePost(item.id) : handleApproveComment(item.id))}>- <Icon sprite={IconCheck} />- <span>- <Trans id="action.publish">Publish</Trans>- </span>- </Button>- <Button size="small" variant="secondary" onClick={() => (item.type === "post" ? handleDeclinePost(item.id) : handleDeclineComment(item.id))}>- <Icon sprite={IconX} />- <span>- <Trans id="action.delete">Delete</Trans>- </span>- </Button>- <Button- size="small"- variant="secondary"- onClick={() => (item.type === "post" ? handleApprovePostAndVerify(item.id) : handleApproveCommentAndVerify(item.id))}- >- <Icon sprite={IconShieldCheck} />- <span>- <Trans id="action.publish.verify">Publish & Trust</Trans>- </span>- </Button>- <Button- size="small"- variant="secondary"- onClick={() => (item.type === "post" ? handleDeclinePostAndBlock(item.id) : handleDeclineCommentAndBlock(item.id))}- >- <Icon sprite={IconBan} />- <span>- <Trans id="action.delete.block">Delete & Block</Trans>- </span>- </Button>- </div>- </VStack>- </div>- </div>- )- }-- const posts = state.items.filter((item) => item.type === "post")- const comments = state.items.filter((item) => item.type === "comment")-- return (- <>- <Header />- <div id="p-admin-moderation" className="page container">- <VStack spacing={2}>- <h1 className="text-display">- <Trans id="moderation.title">Moderation Queue</Trans>- </h1>- <p className="text-body">- <Trans id="moderation.subtitle">- These ideas and comments are from people outside of your trusted users list, you decide if they get published.- </Trans>- </p>- </VStack>-- <div className="c-moderation-page">- {state.loading ? (- <Loader />- ) : state.items.length === 0 ? (- <div className="text-center p-8 rounded mt-4">- <p>- <Trans id="moderation.empty">All content has been moderated. You're all caught up!</Trans>- </p>- </div>- ) : (- <>- {posts.length > 0 && (- <>- {renderDivider("New ideas", posts.length)}- <div className="c-moderation-page__list">{posts.map(renderModerationItem)}</div>- </>- )}-- {comments.length > 0 && (- <>- {renderDivider("New comments", comments.length)}- <div className="c-moderation-page__list">{comments.map(renderModerationItem)}</div>- </>- )}- </>- )}- </div>- </div>- </>- )-}--export default ContentModerationPagediff --git a/commercial/services/sqlstore/postgres/moderation.go b/commercial/services/sqlstore/postgres/moderation.godeleted file mode 100644index b72d30380..000000000--- a/commercial/services/sqlstore/postgres/moderation.go+++ /dev/null@@ -1,292 +0,0 @@-package postgres--import (- "context"- "fmt"- "time"-- "github.com/getfider/fider/app"- "github.com/getfider/fider/app/models/cmd"- "github.com/getfider/fider/app/models/entity"- "github.com/getfider/fider/app/models/enum"- "github.com/getfider/fider/app/models/query"- "github.com/getfider/fider/app/pkg/bus"- "github.com/getfider/fider/app/pkg/dbx"- "github.com/getfider/fider/app/pkg/errors"- "github.com/getfider/fider/app/services/sqlstore/dbEntities"-)--func ApprovePost(ctx context.Context, c *cmd.ApprovePost) error {- return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {- _, err := trx.Execute(`- UPDATE posts SET is_approved = true- WHERE id = $1 AND tenant_id = $2`, c.PostID, tenant.ID)- if err != nil {- return errors.Wrap(err, "failed to approve post")- }- return nil- })-}--func DeclinePost(ctx context.Context, c *cmd.DeclinePost) error {- return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {- // Use existing query to get the post- getPost := &query.GetPostByID{PostID: c.PostID}- if err := bus.Dispatch(ctx, getPost); err != nil {- return err- }-- // Use SetPostResponse to properly delete the post- setResponse := &cmd.SetPostResponse{- Post: getPost.Result,- Text: "Post declined during moderation",- Status: enum.PostDeleted,- }-- return bus.Dispatch(ctx, setResponse)- })-}--func ApproveComment(ctx context.Context, c *cmd.ApproveComment) error {- return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {- _, err := trx.Execute(`- UPDATE comments SET is_approved = true- WHERE id = $1 AND tenant_id = $2`, c.CommentID, tenant.ID)- if err != nil {- return errors.Wrap(err, "failed to approve comment")- }- return nil- })-}--func DeclineComment(ctx context.Context, c *cmd.DeclineComment) error {- return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {- // Use existing delete command- deleteComment := &cmd.DeleteComment{CommentID: c.CommentID}- return bus.Dispatch(ctx, deleteComment)- })-}--func BulkApproveItems(ctx context.Context, c *cmd.BulkApproveItems) error {- return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {- if len(c.PostIDs) > 0 {- postIDsStr := ""- for i, id := range c.PostIDs {- if i > 0 {- postIDsStr += ","- }- postIDsStr += fmt.Sprintf("%d", id)- }- _, err := trx.Execute(fmt.Sprintf(`- UPDATE posts SET is_approved = true- WHERE id IN (%s) AND tenant_id = $1`, postIDsStr), tenant.ID)- if err != nil {- return errors.Wrap(err, "failed to bulk approve posts")- }- }-- if len(c.CommentIDs) > 0 {- commentIDsStr := ""- for i, id := range c.CommentIDs {- if i > 0 {- commentIDsStr += ","- }- commentIDsStr += fmt.Sprintf("%d", id)- }- _, err := trx.Execute(fmt.Sprintf(`- UPDATE comments SET is_approved = true- WHERE id IN (%s) AND tenant_id = $1`, commentIDsStr), tenant.ID)- if err != nil {- return errors.Wrap(err, "failed to bulk approve comments")- }- }-- return nil- })-}--func BulkDeclineItems(ctx context.Context, c *cmd.BulkDeclineItems) error {- return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {- if len(c.PostIDs) > 0 {- // Use existing commands to properly delete each post- for _, postID := range c.PostIDs {- // Use existing query to get the post- getPost := &query.GetPostByID{PostID: postID}- if err := bus.Dispatch(ctx, getPost); err != nil {- return errors.Wrap(err, "failed to get post for bulk decline")- }-- // Use SetPostResponse to properly delete the post- setResponse := &cmd.SetPostResponse{- Post: getPost.Result,- Text: "Post declined during bulk moderation",- Status: enum.PostDeleted,- }-- if err := bus.Dispatch(ctx, setResponse); err != nil {- return errors.Wrap(err, "failed to bulk decline post")- }- }- }-- if len(c.CommentIDs) > 0 {- // Use existing delete command for each comment- for _, commentID := range c.CommentIDs {- deleteComment := &cmd.DeleteComment{CommentID: commentID}- if err := bus.Dispatch(ctx, deleteComment); err != nil {- return errors.Wrap(err, "failed to bulk decline comment")- }- }- }-- return nil- })-}--type dbModerationPost struct {- ID int `db:"id"`- Number int `db:"number"`- Title string `db:"title"`- Slug string `db:"slug"`- Description string `db:"description"`- CreatedAt time.Time `db:"created_at"`- User *dbEntities.User `db:"user"`-}--type dbModerationComment struct {- ID int `db:"id"`- PostID int `db:"post_id"`- PostNumber int `db:"post_number"`- PostSlug string `db:"post_slug"`- Content string `db:"content"`- CreatedAt time.Time `db:"created_at"`- User *dbEntities.User `db:"user"`- PostTitle string `db:"post_title"`-}--func GetModerationItems(ctx context.Context, q *query.GetModerationItems) error {- return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {- q.Result = make([]*query.ModerationItem, 0)-- // Get unmoderated posts- var posts []*dbModerationPost-- err := trx.Select(&posts, `- SELECT p.id, p.number, p.title, p.slug, p.description, p.created_at,- u.id AS user_id,- u.name AS user_name,- u.email AS user_email,- u.role AS user_role,- u.status AS user_status,- u.avatar_type AS user_avatar_type,- u.avatar_bkey AS user_avatar_bkey- FROM posts p- INNER JOIN users u ON u.id = p.user_id AND u.tenant_id = p.tenant_id- WHERE p.tenant_id = $1 AND p.is_approved = false and p.status <> $2- ORDER BY p.created_at DESC`, tenant.ID, enum.PostDeleted)- if err != nil {- return errors.Wrap(err, "failed to get unmoderated posts")- }-- for _, post := range posts {- userWithEmail := &entity.UserWithEmail{- User: post.User.ToModel(ctx),- }-- q.Result = append(q.Result, &query.ModerationItem{- Type: "post",- ID: post.ID,- PostNumber: post.Number,- PostSlug: post.Slug,- Title: post.Title,- Content: post.Description,- CreatedAt: post.CreatedAt,- User: userWithEmail,- })- }-- // Get unmoderated comments- var comments []*dbModerationComment-- err = trx.Select(&comments, `- SELECT c.id, c.post_id, p.number as post_number, p.slug as post_slug, c.content, c.created_at,- u.id AS user_id,- u.name AS user_name,- u.email AS user_email,- u.role AS user_role,- u.status AS user_status,- u.avatar_type AS user_avatar_type,- u.avatar_bkey AS user_avatar_bkey,- p.title as post_title- FROM comments c- INNER JOIN users u ON u.id = c.user_id AND u.tenant_id = c.tenant_id- INNER JOIN posts p ON p.id = c.post_id AND p.tenant_id = c.tenant_id- WHERE c.tenant_id = $1 AND c.is_approved = false and p.status <> $2- AND c.deleted_at IS NULL- ORDER BY c.created_at DESC`, tenant.ID, enum.PostDeleted)- if err != nil {- return errors.Wrap(err, "failed to get unmoderated comments")- }-- for _, comment := range comments {-- userWithEmail := &entity.UserWithEmail{- User: comment.User.ToModel(ctx),- }-- q.Result = append(q.Result, &query.ModerationItem{- Type: "comment",- ID: comment.ID,- PostID: comment.PostID,- PostNumber: comment.PostNumber,- PostSlug: comment.PostSlug,- Content: comment.Content,- CreatedAt: comment.CreatedAt,- PostTitle: comment.PostTitle,- User: userWithEmail,- })- }-- return nil- })-}--func GetModerationCount(ctx context.Context, q *query.GetModerationCount) error {- return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {- var count int-- err := trx.Get(&count, `- SELECT- (SELECT COUNT(*) FROM posts WHERE tenant_id = $1 AND is_approved = false and status <> $2) +- (SELECT COUNT(*) FROM comments c JOIN posts p on c.post_id = p.id WHERE p.tenant_id = $1 AND c.is_approved = false AND p.status <> $2 AND c.deleted_at IS NULL)- `, tenant.ID, enum.PostDeleted)-- if err != nil {- return errors.Wrap(err, "failed to get moderation count")- }-- q.Result = count- return nil- })-}--func TrustUser(ctx context.Context, c *cmd.TrustUser) error {- return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {- // Trust and unblock the user (can't be both blocked and trusted)- _, err := trx.Execute(`- UPDATE users SET is_trusted = true, status = $1- WHERE id = $2 AND tenant_id = $3`, enum.UserActive, c.UserID, tenant.ID)- if err != nil {- return errors.Wrap(err, "failed to trust user")- }-- return nil- })-}--func using(ctx context.Context, handler func(*dbx.Trx, *entity.Tenant, *entity.User) error) error {- trx, _ := ctx.Value(app.TransactionCtxKey).(*dbx.Trx)- tenant, _ := ctx.Value(app.TenantCtxKey).(*entity.Tenant)- user, _ := ctx.Value(app.UserCtxKey).(*entity.User)- return handler(trx, tenant, user)-}diff --git a/commercial/services/sqlstore/postgres/postgres.go b/commercial/services/sqlstore/postgres/postgres.godeleted file mode 100644index 3b88cae41..000000000--- a/commercial/services/sqlstore/postgres/postgres.go+++ /dev/null@@ -1,37 +0,0 @@-package postgres--import (- "github.com/getfider/fider/app/pkg/bus"-)--func init() {- bus.Register(CommercialService{})-}--type CommercialService struct{}--func (s CommercialService) Name() string {- return "Commercial PostgreSQL"-}--func (s CommercialService) Category() string {- return "commercial-sqlstore"-}--func (s CommercialService) Enabled() bool {- return true-}--func (s CommercialService) Init() {- // Register commercial moderation handlers- // These should override the open source stub handlers- bus.AddHandler(ApprovePost)- bus.AddHandler(DeclinePost)- bus.AddHandler(ApproveComment)- bus.AddHandler(DeclineComment)- bus.AddHandler(BulkApproveItems)- bus.AddHandler(BulkDeclineItems)- bus.AddHandler(GetModerationItems)- bus.AddHandler(GetModerationCount)- bus.AddHandler(TrustUser)-}diff --git a/docs/INTERNAL_LICENSE_SETUP.md b/docs/INTERNAL_LICENSE_SETUP.mddeleted file mode 100644index 7ed391cae..000000000--- a/docs/INTERNAL_LICENSE_SETUP.md+++ /dev/null@@ -1,216 +0,0 @@-# Internal: License System Setup--**This document is for internal use only** - setting up the Fider hosted instance to generate commercial licenses.--## Initial Setup (One-Time)--### 1. Generate License Key Pair--Run the key generation script:--```bash-go run scripts/generate_license_keys.go-```--This outputs:-```-=== Ed25519 License Key Pair Generated ===--PUBLIC KEY (for self-hosted instances):-lPHzCZhOBBihIusKWs5lzXCgGxZEKBpCiplkmZSjGpU=--PRIVATE KEY (for hosted server only - KEEP SECRET!):-B0Srq+DtsBI6MwY4sljCywXNLWAizfCdiJ6emGx+xIqU8fMJmE4EGKEi6wpazmXNcKAbFkQoGkKKmWSZlKMalQ==-```--### 2. Configure Production Environment--Add **only the private key** to the hosted instance's `.env`:--```env-LICENSE_PRIVATE_KEY=B0Srq+DtsBI6MwY4sljCywXNLWAizfCdiJ6emGx+xIqU8fMJmE4EGKEi6wpazmXNcKAbFkQoGkKKmWSZlKMalQ==-```--**Security:**-- Never commit this to git-- Store in secure secrets management (AWS Secrets Manager, Vault, etc.)-- Restrict access to production environment--### 3. Embed Public Key in Code--The **public key** is embedded in `app/services/license/validator.go` as `DefaultPublicKey`.--**When you generate a new key pair:**--1. Update the constant in `validator.go`:- ```go- const DefaultPublicKey = "your-new-public-key-here"- ```--2. Self-hosted customers get the new key automatically when they upgrade Fider--3. No manual configuration needed by customers - it "just works"--Current embedded public key:-```-lPHzCZhOBBihIusKWs5lzXCgGxZEKBpCiplkmZSjGpU=-```--## How License Generation Works--### Automatic Generation via Stripe--When a customer purchases Pro via Stripe webhook (`app/handlers/webhooks/stripe.go`):--1. **Checkout completed** (`handleCheckoutSessionCompleted`):- - Calls `license.GenerateKey(tenantID)`- - Stores key in database via `ActivateStripeSubscription`- - Key is displayed to customer in billing page--2. **Subscription cancelled** (`handleSubscriptionDeleted`):- - Calls `CancelStripeSubscription`- - Sets tenant back to free plan--### Manual License Generation (if needed)--If you need to manually generate a license for a customer:--```go-// In Go code or via admin endpoint-licenseKey := license.GenerateKey(tenantID)-// Returns: FIDER-COMMERCIAL-{tenantID}-{timestamp}-{signature}-```--The tenant ID should match the customer's tenant in your database.--## Code Reference--### Key Files--- **Generation**: `app/services/license/validator.go` - `GenerateKey()` function-- **Webhook**: `app/handlers/webhooks/stripe.go` - Automatic generation on purchase-- **Storage**: `app/services/sqlstore/postgres/billing.go` - Database operations-- **Validation**: `app/services/license/validator.go` - `ValidateKey()` function (used by self-hosted)--### Database Tables--- `tenants.is_pro` - Boolean flag indicating Pro subscription-- `tenants_billing` - Stores Stripe subscription ID and license key--## Testing--### Test Environment--The `.test.env` file contains test keys for development:--```env-LICENSE_PUBLIC_KEY=9o3OnNs9tnnD780fZcTYas8uhcA90MWtin1rWGhXVPE=-LICENSE_PRIVATE_KEY=fwRNcFEiusrH0Hx1aBlOobE+6hm2/CPXUkUTWXj3cQn2jc6c2z22ecPvzR9lxNhqzy6FwD3Qxa2KfWtYaFdU8Q==-```--These are safe for testing and are different from production keys.--### Running Tests--```bash-make test-server-# or specifically:-godotenv -f .test.env go test -v ./app/services/license/...-```--All tests should pass:-- `TestGenerateAndValidateKey_Ed25519`-- `TestValidateKey_Ed25519_InvalidSignature`-- `TestValidateKey_Ed25519_WrongPublicKey`-- `TestValidateKey_EmptyKey`-- `TestValidateKey_InvalidFormat`-- `TestValidateKey_NoPublicKeyConfigured`--## Key Rotation (Emergency Procedure)--If the private key is ever compromised:--1. **Generate new key pair**:- ```bash- go run scripts/generate_license_keys.go- ```--2. **Update production environment** with new `LICENSE_PRIVATE_KEY`--3. **Update embedded public key** in `app/services/license/validator.go`:- ```go- const DefaultPublicKey = "new-public-key-here"- ```--4. **Release new Fider version**--5. **Communicate to customers**:- - "Please update to Fider vX.X.X for important security improvements"- - They update Fider → automatically get new public key → existing licenses keep working- - No manual configuration needed--**Important**: Old licenses signed with the old private key won't validate with the new public key. You'll need to:-- Regenerate licenses for all active Pro customers (using their tenant IDs)-- Send new license keys to customers-- Or: Implement multi-key support to validate both old and new licenses during transition--## Monitoring--### What to Monitor--- License generation failures (check Stripe webhook logs)-- Invalid license validation attempts on hosted instance-- Customer support tickets about license issues--### Logs to Watch--```bash-# License generation-grep "GenerateKey" /var/log/fider/app.log--# Stripe webhook events-grep "stripe" /var/log/fider/app.log | grep "checkout\|subscription"-```--## Support Scenarios--### Customer Reports License Not Working--1. Verify they have correct `LICENSE_PUBLIC_KEY` in their `.env`-2. Check their license key format is correct-3. Test their license key validation locally:- ```bash- # Set up test environment with their key- LICENSE_PUBLIC_KEY=<current_public_key> \- go run scripts/validate_license.go "FIDER-COMMERCIAL-xxx-xxx-xxx"- ```-4. Check if license was successfully generated in database-5. If needed, manually regenerate license for their tenant ID--### Customer Wants to Transfer License--Licenses are tied to tenant ID. To transfer:-- Generate new license for new tenant ID-- Cancel old subscription/license-- Update billing records--## Security Best Practices--1. **Never** share or commit the private key-2. **Always** use environment variables for production-3. **Rotate** keys if any compromise is suspected-4. **Audit** license generation logs periodically-5. **Monitor** for unusual patterns (same license on multiple IPs)-6. **Backup** production environment configuration securely--## Production Checklist--Before deploying to production:--- [ ] Production `LICENSE_PRIVATE_KEY` is set and secured-- [ ] Public key is distributed in documentation-- [ ] Stripe webhook is configured and tested-- [ ] All tests pass-- [ ] Monitoring/logging is in place-- [ ] Support team knows how to help customers with license issues-- [ ] Emergency key rotation procedure is documenteddiff --git a/docs/LICENSE_SYSTEM.md b/docs/LICENSE_SYSTEM.mddeleted file mode 100644index c8f950451..000000000--- a/docs/LICENSE_SYSTEM.md+++ /dev/null@@ -1,92 +0,0 @@-# Commercial License System--This document explains how to enable commercial features on your self-hosted Fider instance using a license key.--## Overview--Fider's commercial features (like content moderation) require a valid license key. When you purchase a Pro subscription from the hosted Fider platform, you'll receive a license key that you can use to unlock these features on your self-hosted instance.--## Enabling Commercial Features--### Step 1: Purchase a Pro Subscription--Visit the hosted Fider platform and subscribe to the Pro plan. After your payment is processed, you'll receive a commercial license key.--### Step 2: Configure Your Self-Hosted Instance--Add your license key to your `.env` file:--```env-# Your commercial license key (received after purchase)-COMMERCIAL_KEY=FIDER-COMMERCIAL-xxx-xxx-xxx-```--**That's it!** The public key for validation is already embedded in Fider - no additional configuration needed.--### Step 3: Restart Fider--Restart your Fider instance. Commercial features (like content moderation) will now be enabled.--## How It Works--Your license key is validated locally when Fider starts:--1. Reads `COMMERCIAL_KEY` from your environment-2. Verifies the cryptographic signature using the embedded public key-3. If valid, enables commercial features--**No internet connection required** - validation happens entirely on your server.--### Advanced: Overriding the Public Key--The public key is embedded in Fider's code, so it updates automatically when you upgrade Fider. However, you can override it if needed:--```env-LICENSE_PUBLIC_KEY=your-custom-public-key-here-```--You typically **don't need** to set this unless:-- You're testing with a custom license system-- Fider support specifically instructs you to update it--## Security & Privacy--Fider uses **Ed25519 cryptographic signatures** to validate license keys:--- ✅ **Secure**: Modern elliptic curve cryptography-- ✅ **Private**: No phone-home or tracking-- ✅ **Offline**: Works without internet connection-- ✅ **Trustworthy**: Public key cryptography prevents forgery--## Troubleshooting--### Commercial features are not enabled--**Check the following:**--1. `COMMERCIAL_KEY` is set in your `.env` file-2. Your license key is in the correct format: `FIDER-COMMERCIAL-{numbers}-{numbers}-{hex}`-3. You restarted Fider after adding the configuration-4. You're running a recent version of Fider (with the embedded public key)-5. Check your logs for validation errors--### "invalid signature: license key verification failed"--**Problem:** Your license key cannot be verified.--**Possible causes:**-- License key was incorrectly copied (check for typos or missing characters)-- You're running an outdated version of Fider (update to get the latest public key)-- License key is not valid--**Solution:**-1. Verify your license key is copied correctly-2. Update to the latest Fider version-3. If issues persist, contact support--## Support--If you have issues with your commercial license, please contact Fider support with:-- Your license key-- Fider version-- Any error messages from logsdiff --git a/esbuild.config.js b/esbuild.config.jsindex 1fca15936..9d73ae975 100644--- a/esbuild.config.js+++ b/esbuild.config.js@@ -74,7 +74,6 @@ esbuildoutfile: "ssr.js",alias: {"@fider": "./public",- "@commercial": "./commercial","@locale": "./locale",},plugins: [emptyCSS, emptySVG, babelPlugin()],diff --git a/lingui.config.js b/lingui.config.jsindex d4bd3eeb6..a10bf10b0 100644--- a/lingui.config.js+++ b/lingui.config.js@@ -7,7 +7,7 @@ export default {catalogs: [{path: "<rootDir>/locale/{locale}/client",- include: ["<rootDir>/public/**/*.{ts,tsx}", "<rootDir>/commercial/**/*.{ts,tsx}"],+ include: ["<rootDir>/public/**/*.{ts,tsx}"],},],orderBy: "messageId",diff --git a/main.go b/main.goindex e76ca8dd0..63e000006 100644--- a/main.go+++ b/main.go@@ -4,8 +4,6 @@ import ("os""github.com/getfider/fider/app/cmd"- _ "github.com/getfider/fider/commercial"- _ "github.com/getfider/fider/commercial/services/sqlstore/postgres" // Import AFTER cmd to override open source handlers_ "github.com/lib/pq")diff --git a/package.json b/package.jsonindex 1517bb647..468f8fcad 100644--- a/package.json+++ b/package.json@@ -98,7 +98,6 @@"moduleNameMapper": {".*\\.(png|scss|svg)$": "<rootDir>/public/jest.assets.ts","@fider/(.*)": "<rootDir>/public/$1",- "@commercial/(.*)": "<rootDir>/commercial/$1","@locale/(.*)": "<rootDir>/locale/$1"}},diff --git a/commercial/components/ModerationIndicator.tsx b/public/components/ModerationIndicator.tsxsimilarity index 84%rename from commercial/components/ModerationIndicator.tsxrename to public/components/ModerationIndicator.tsxindex 000d574ad..cc0b23d79 100644--- a/commercial/components/ModerationIndicator.tsx+++ b/public/components/ModerationIndicator.tsx@@ -10,9 +10,6 @@ export const ModerationIndicator = () => {const [count, setCount] = useState(0)const [loading, setLoading] = useState(true)- // Check if commercial license is available- const hasCommercialLicense = fider.session.tenant.hasCommercialFeatures-useEffect(() => {const fetchCount = async () => {try {@@ -36,12 +33,7 @@ export const ModerationIndicator = () => {}}, [fider.session.user, fider.session.tenant.isModerationEnabled])- // Don't show the indicator if commercial license is not available- if (!hasCommercialLicense) {- return null- }-- // Don't show the indicator if user is not admin/collaborator or moderation is disabled+ // Don't show if user is not admin/collaborator or moderation is disabledif (!fider.session.user.isAdministrator && !fider.session.user.isCollaborator) {return null}diff --git a/public/components/index.tsx b/public/components/index.tsxindex 74fb08b10..fcb849400 100644--- a/public/components/index.tsx+++ b/public/components/index.tsx@@ -8,7 +8,7 @@ export * from "./SignInModal"export * from "./RSSModal"export * from "./VoteCounter"export * from "./NotificationIndicator"-export * from "@commercial/components/ModerationIndicator"+export * from "./ModerationIndicator"export * from "./UserMenu"export * from "./Reactions"export * from "./ReadOnlyNotice"diff --git a/public/models/identity.ts b/public/models/identity.tsindex 582e1895e..2281a76bd 100644--- a/public/models/identity.ts+++ b/public/models/identity.ts@@ -14,7 +14,7 @@ export interface Tenant {isEmailAuthAllowed: booleanisFeedEnabled: booleanisModerationEnabled: boolean- hasCommercialFeatures: boolean+ isPro: boolean}export enum TenantStatus {diff --git a/public/pages/Administration/pages/AdvancedSettings.page.tsx b/public/pages/Administration/pages/AdvancedSettings.page.tsxindex b0050502a..c7c893ec6 100644--- a/public/pages/Administration/pages/AdvancedSettings.page.tsx+++ b/public/pages/Administration/pages/AdvancedSettings.page.tsx@@ -7,15 +7,12 @@ import { AdminBasePage } from "../components/AdminBasePage"interface AdvancedSettingsPageProps {customCSS: stringallowedSchemes: string- licenseKey: string- hasCommercialFeatures: boolean}interface AdvancedSettingsPageState {customCSS: stringallowedSchemes: stringerror?: Failure- copied: boolean}export default class AdvancedSettingsPage extends AdminBasePage<AdvancedSettingsPageProps, AdvancedSettingsPageState> {@@ -30,7 +27,6 @@ export default class AdvancedSettingsPage extends AdminBasePage<AdvancedSettingsthis.state = {customCSS: this.props.customCSS,allowedSchemes: this.props.allowedSchemes,- copied: false,}}@@ -51,37 +47,9 @@ export default class AdvancedSettingsPage extends AdminBasePage<AdvancedSettings}}- private copyLicenseKey = (): void => {- navigator.clipboard.writeText(this.props.licenseKey)- this.setState({ copied: true })- setTimeout(() => this.setState({ copied: false }), 2000)- }-public content() {return (<Form error={this.state.error}>- {this.props.hasCommercialFeatures && this.props.licenseKey && (- <div className="field">- <label>Commercial License Key</label>- <p className="text-muted">Use this key to run Fider self-hosted with commercial features (content moderation).</p>- <div className="mt-2 mb-4">- <div className="flex gap-2">- <input- type="text"- id="licenseKey"- readOnly- value={this.props.licenseKey}- className="w-full font-mono text-sm bg-gray-50 border border-gray-300 rounded px-3 py-2"- style={{ fontFamily: "monospace" }}- />- <Button size="small" onClick={this.copyLicenseKey} className="whitespace-nowrap">- {this.state.copied ? "Copied!" : "Copy"}- </Button>- </div>- </div>- </div>- )}-<TextAreafield="customCSS"label="Custom CSS"diff --git a/commercial/pages/Administration/ContentModeration.page.scss b/public/pages/Administration/pages/ContentModeration.page.scsssimilarity index 100%rename from commercial/pages/Administration/ContentModeration.page.scssrename to public/pages/Administration/pages/ContentModeration.page.scssdiff --git a/public/pages/Administration/pages/ContentModeration.page.tsx b/public/pages/Administration/pages/ContentModeration.page.tsxindex 197412052..92de3cfd2 100644--- a/public/pages/Administration/pages/ContentModeration.page.tsx+++ b/public/pages/Administration/pages/ContentModeration.page.tsx@@ -1,39 +1,293 @@-import React from "react"+import "./ContentModeration.page.scss"++import React, { useState, useEffect } from "react"+import { Button, Avatar, Loader, Icon, Markdown } from "@fider/components/common"import { Header } from "@fider/components"-import { Button } from "@fider/components/common"+import { HStack, VStack } from "@fider/components/layout"+import { actions, chopString, http, notify } from "@fider/services"+import { User, UserStatus } from "@fider/models"+import { useFider } from "@fider/hooks"+import { Trans } from "@lingui/react/macro"+import IconCheck from "@fider/assets/images/heroicons-check.svg"+import IconX from "@fider/assets/images/heroicons-x.svg"+import IconShieldCheck from "@fider/assets/images/heroicons-shieldcheck.svg"+import IconBan from "@fider/assets/images/heroicons-x-circle.svg"+import { Moment } from "@fider/components/common"-// Dynamically import the commercial component-const CommercialContentModerationPage = React.lazy(() => import("@commercial/pages/Administration/ContentModeration.page"))+interface ModerationItem {+ type: "post" | "comment"+ id: number+ postId?: number+ postNumber?: number+ postSlug?: string+ title?: string+ content: string+ user: User+ createdAt: string+ postTitle?: string+}++interface ContentModerationPageState {+ items: ModerationItem[]+ loading: boolean+}const ContentModerationPage = () => {- // Check if commercial license is available- // TODO: This will be replaced with proper license validation in Phase 4- const hasCommercialLicense = true // Placeholder for development+ const [state, setState] = useState<ContentModerationPageState>({+ items: [],+ loading: true,+ })+ const fider = useFider()++ const fetchItems = async () => {+ setState((prev) => ({ ...prev, loading: true }))+ const result = await http.get<{ items: ModerationItem[] }>("/_api/admin/moderation/items")+ if (result.ok) {+ setState({ items: result.data.items, loading: false })+ } else {+ setState((prev) => ({ ...prev, loading: false }))+ notify.error(<Trans id="moderation.fetch.error">Failed to fetch moderation items</Trans>)+ }+ }++ useEffect(() => {+ fetchItems()+ }, [])++ const handleApprovePost = async (postId: number) => {+ const result = await actions.approvePost(postId)+ if (result.ok) {+ notify.success(<Trans id="moderation.post.published">Post published successfully</Trans>)+ setState((prev) => ({+ ...prev,+ items: prev.items.filter((item) => !(item.type === "post" && item.id === postId)),+ }))+ } else {+ notify.error(<Trans id="moderation.post.publish.error">Failed to publish post</Trans>)+ }+ }++ const handleDeclinePost = async (postId: number) => {+ const result = await actions.declinePost(postId)+ if (result.ok) {+ notify.success(<Trans id="moderation.post.deleted">Post deleted successfully</Trans>)+ setState((prev) => ({+ ...prev,+ items: prev.items.filter((item) => !(item.type === "post" && item.id === postId)),+ }))+ } else {+ notify.error(<Trans id="moderation.post.delete.error">Failed to delete post</Trans>)+ }+ }++ const handleApproveComment = async (commentId: number) => {+ const result = await actions.approveComment(commentId)+ if (result.ok) {+ notify.success(<Trans id="moderation.comment.published">Comment published successfully</Trans>)+ setState((prev) => ({+ ...prev,+ items: prev.items.filter((item) => !(item.type === "comment" && item.id === commentId)),+ }))+ } else {+ notify.error(<Trans id="moderation.comment.publish.error">Failed to publish comment</Trans>)+ }+ }++ const handleDeclineComment = async (commentId: number) => {+ const result = await actions.declineComment(commentId)+ if (result.ok) {+ notify.success(<Trans id="moderation.comment.deleted">Comment deleted successfully</Trans>)+ setState((prev) => ({+ ...prev,+ items: prev.items.filter((item) => !(item.type === "comment" && item.id === commentId)),+ }))+ } else {+ notify.error(<Trans id="moderation.comment.delete.error">Failed to delete comment</Trans>)+ }+ }++ const handleApprovePostAndVerify = async (postId: number) => {+ const result = await actions.approvePostAndVerify(postId)+ if (result.ok) {+ notify.success(<Trans id="moderation.post.published.verified">Post published and user verified</Trans>)+ setState((prev) => ({+ ...prev,+ items: prev.items.filter((item) => !(item.type === "post" && item.id === postId)),+ }))+ } else {+ notify.error(<Trans id="moderation.post.publish.verify.error">Failed to publish post and verify user</Trans>)+ }+ }++ const handleDeclinePostAndBlock = async (postId: number) => {+ const result = await actions.declinePostAndBlock(postId)+ if (result.ok) {+ notify.success(<Trans id="moderation.post.deleted.blocked">Post deleted and user blocked</Trans>)+ setState((prev) => ({+ ...prev,+ items: prev.items.filter((item) => !(item.type === "post" && item.id === postId)),+ }))+ } else {+ notify.error(<Trans id="moderation.post.delete.block.error">Failed to delete post and block user</Trans>)+ }+ }++ const handleApproveCommentAndVerify = async (commentId: number) => {+ const result = await actions.approveCommentAndVerify(commentId)+ if (result.ok) {+ notify.success(<Trans id="moderation.comment.published.verified">Comment published and user verified</Trans>)+ setState((prev) => ({+ ...prev,+ items: prev.items.filter((item) => !(item.type === "comment" && item.id === commentId)),+ }))+ } else {+ notify.error(<Trans id="moderation.comment.publish.verify.error">Failed to publish comment and verify user</Trans>)+ }+ }++ const handleDeclineCommentAndBlock = async (commentId: number) => {+ const result = await actions.declineCommentAndBlock(commentId)+ if (result.ok) {+ notify.success(<Trans id="moderation.comment.deleted.blocked">Comment deleted and user blocked</Trans>)+ setState((prev) => ({+ ...prev,+ items: prev.items.filter((item) => !(item.type === "comment" && item.id === commentId)),+ }))+ } else {+ notify.error(<Trans id="moderation.comment.delete.block.error">Failed to delete comment and block user</Trans>)+ }+ }++ const renderDivider = (title: string, count: number) => {+ return (+ <div className="c-moderation-page__divider">+ <div className="c-moderation-page__divider-title">+ {title} ({count})+ </div>+ </div>+ )+ }++ const handlePostClick = (link: string) => {+ window.location.href = link+ }++ const renderModerationItem = (item: ModerationItem) => {+ const title = item.type == "post" ? item.title : item.postTitle+ const link = item.type == "post" ? `/posts/${item.postNumber}/${item.postSlug}` : `/posts/${item.postNumber}/${item.postSlug}#comment-${item.id}`+ const blocked = item.user.status === UserStatus.Blocked && <span className="text-red-700">blocked</span>- // If no commercial license, show upgrade message- if (!hasCommercialLicense) {return (- <>- <Header />- <div id="p-admin-moderation" className="page container">- <h1 className="text-large">Content Moderation</h1>- <div className="text-center p-8 border rounded mt-4">- <h2 className="text-medium mb-4">Commercial Feature</h2>- <p className="text-body mb-4">Content moderation is a commercial feature. Please upgrade to access the moderation queue.</p>- <Button size="small" variant="primary" href="/upgrade">- Upgrade to Commercial- </Button>+ <div key={`${item.type}-${item.id}`} className="c-moderation-item" onClick={() => handlePostClick(link)}>+ <div className="c-moderation-item__content">+ <div className="c-moderation-item__header">+ <HStack spacing={4} align="start">+ <Avatar user={item.user} size="large" />+ <VStack spacing={1} className="flex-grow c-moderation-item__user-info">+ <div className="text-semibold c-moderation-item__user-name">{item.user.name}</div>+ <div className="c-moderation-item__user-email"><{item.user.email}></div>+ {blocked && <span className="text-red-700">{blocked}</span>}+ </VStack>+ </HStack>+ <div className="c-moderation-item__timestamp">+ <Moment date={item.createdAt} locale={fider.currentLocale} />+ </div></div>++ <VStack spacing={2} className="c-moderation-item__body">+ {item.type === "post" && <h3 className="text-semibold m-0">{title}</h3>}+ <div className="text-body text-break">+ <Markdown text={chopString(item.content, 200)} style="plainText" />+ </div>+ {item.type === "comment" && <div className="text-muted text-break">{title}</div>}++ <div className="c-moderation-item__actions invisible" onClick={(e) => e.stopPropagation()}>+ <Button size="small" variant="secondary" onClick={() => (item.type === "post" ? handleApprovePost(item.id) : handleApproveComment(item.id))}>+ <Icon sprite={IconCheck} />+ <span>+ <Trans id="action.publish">Publish</Trans>+ </span>+ </Button>+ <Button size="small" variant="secondary" onClick={() => (item.type === "post" ? handleDeclinePost(item.id) : handleDeclineComment(item.id))}>+ <Icon sprite={IconX} />+ <span>+ <Trans id="action.delete">Delete</Trans>+ </span>+ </Button>+ <Button+ size="small"+ variant="secondary"+ onClick={() => (item.type === "post" ? handleApprovePostAndVerify(item.id) : handleApproveCommentAndVerify(item.id))}+ >+ <Icon sprite={IconShieldCheck} />+ <span>+ <Trans id="action.publish.verify">Publish & Trust</Trans>+ </span>+ </Button>+ <Button+ size="small"+ variant="secondary"+ onClick={() => (item.type === "post" ? handleDeclinePostAndBlock(item.id) : handleDeclineCommentAndBlock(item.id))}+ >+ <Icon sprite={IconBan} />+ <span>+ <Trans id="action.delete.block">Delete & Block</Trans>+ </span>+ </Button>+ </div>+ </VStack></div>- </>+ </div>)}- // If licensed, load the commercial component+ const posts = state.items.filter((item) => item.type === "post")+ const comments = state.items.filter((item) => item.type === "comment")+return (- <React.Suspense fallback={<div>Loading...</div>}>- <CommercialContentModerationPage />- </React.Suspense>+ <>+ <Header />+ <div id="p-admin-moderation" className="page container">+ <VStack spacing={2}>+ <h1 className="text-display">+ <Trans id="moderation.title">Moderation Queue</Trans>+ </h1>+ <p className="text-body">+ <Trans id="moderation.subtitle">+ These ideas and comments are from people outside of your trusted users list, you decide if they get published.+ </Trans>+ </p>+ </VStack>++ <div className="c-moderation-page">+ {state.loading ? (+ <Loader />+ ) : state.items.length === 0 ? (+ <div className="text-center p-8 rounded mt-4">+ <p>+ <Trans id="moderation.empty">All content has been moderated. You're all caught up!</Trans>+ </p>+ </div>+ ) : (+ <>+ {posts.length > 0 && (+ <>+ {renderDivider("New ideas", posts.length)}+ <div className="c-moderation-page__list">{posts.map(renderModerationItem)}</div>+ </>+ )}++ {comments.length > 0 && (+ <>+ {renderDivider("New comments", comments.length)}+ <div className="c-moderation-page__list">{comments.map(renderModerationItem)}</div>+ </>+ )}+ </>+ )}+ </div>+ </div>+ </>)}diff --git a/public/pages/Administration/pages/ManageBilling.page.tsx b/public/pages/Administration/pages/ManageBilling.page.tsxindex d3a5b53d4..e7de526ae 100644--- a/public/pages/Administration/pages/ManageBilling.page.tsx+++ b/public/pages/Administration/pages/ManageBilling.page.tsx@@ -12,9 +12,8 @@ import "./ManageBilling.page.scss"interface ManageBillingPageProps {stripeCustomerID: stringstripeSubscriptionID: string- licenseKey: stringpaddleSubscriptionID: string- hasCommercialFeatures: boolean+ isPro: boolean}interface PlanFeature {@@ -115,8 +114,8 @@ const ManageBillingPage = (props: ManageBillingPageProps) => {// Detect Paddle customers who need to migrateconst isPaddleCustomer = Boolean(props.paddleSubscriptionID && !props.stripeSubscriptionID)- // Display as commercial only if they're truly a Stripe customer- const displayAsCommercial = props.hasCommercialFeatures && !isPaddleCustomer+ // Display as Pro only if they're truly a Stripe customer+ const displayAsPro = props.isPro && !isPaddleCustomerconst openPortal = async () => {setIsLoading(true)@@ -161,18 +160,6 @@ const ManageBillingPage = (props: ManageBillingPageProps) => {{isPaddleCustomer && <PaddleMigrationBanner />}- {displayAsCommercial && props.licenseKey && (- <div className="bg-blue-50 p-4 rounded mb-4 border border-blue-200">- <p className="text-sm text-gray-700">- If you want to run Fider self-hosted with commercial features,{" "}- <a href="/admin/advanced" className="text-blue-600 hover:text-blue-800 underline">- see advanced- </a>- .- </p>- </div>- )}-<div className="c-billing-plans"><PlanCardname="Free"@@ -180,11 +167,11 @@ const ManageBillingPage = (props: ManageBillingPageProps) => {period="month"description="Perfect for getting started with feedback collection."features={freeFeatures}- isCurrent={!displayAsCommercial && !isPaddleCustomer}+ isCurrent={!displayAsPro && !isPaddleCustomer}buttonText="Downgrade"buttonVariant="secondary"- onButtonClick={displayAsCommercial ? openPortal : undefined}- isLoading={isLoading && displayAsCommercial}+ onButtonClick={displayAsPro ? openPortal : undefined}+ isLoading={isLoading && displayAsPro}/>{isPaddleCustomer && (@@ -205,11 +192,11 @@ const ManageBillingPage = (props: ManageBillingPageProps) => {period="month"description="For teams that need advanced features and support."features={proFeatures}- isCurrent={displayAsCommercial}+ isCurrent={displayAsPro}isHighlighted={true}- buttonText={displayAsCommercial ? "Manage Billing" : isPaddleCustomer ? "Switch to new Pro Plan" : "Upgrade to Pro"}+ buttonText={displayAsPro ? "Manage Billing" : isPaddleCustomer ? "Switch to new Pro Plan" : "Upgrade to Pro"}buttonVariant="primary"- onButtonClick={displayAsCommercial ? openPortal : startCheckout}+ onButtonClick={displayAsPro ? openPortal : startCheckout}isLoading={isLoading}/></div>diff --git a/public/pages/Administration/pages/PrivacySettings.page.tsx b/public/pages/Administration/pages/PrivacySettings.page.tsxindex 0dc561ffa..f2cce0c0d 100644--- a/public/pages/Administration/pages/PrivacySettings.page.tsx+++ b/public/pages/Administration/pages/PrivacySettings.page.tsx@@ -56,22 +56,21 @@ export default class PrivacySettingsPage extends AdminBasePage<any, PrivacySettipublic content() {return (<Form>- <Field label="Private Site">+ <Field label="Private Board"><Toggle disabled={!Fider.session.user.isAdministrator} active={this.state.isPrivate} onToggle={this.privacyToggle} /><p className="text-muted mt-1">- A private site prevents unauthenticated users from viewing or interacting with its content. <br /> When enabled, only already registered users,- invited users and users from trusted OAuth providers will have access to this site. Disables the feed feature.+ A private board prevents unauthenticated users from viewing or interacting with its content. <br /> When enabled, only already registered users,+ invited users and users from trusted OAuth providers will have access to this board. Disables the feed feature.</p></Field><Field label="ATOM Feed"><Toggle disabled={!Fider.session.user.isAdministrator || this.state.isPrivate} active={this.state.isFeedEnabled} onToggle={this.atomFeedToggle} /><p className="text-muted mt-1">- This feature lets users access this site via a feed reader. <br /> When enabled, the site makes its posts and comments available using the ATOM- format. Links to feeds and autodiscovery metadata are shown on the site.+ This feature lets users access this board via a feed reader. <br /> When enabled, the board makes its posts and comments available using the ATOM+ format. Links to feeds and autodiscovery metadata are shown on the board.</p></Field>- {/* Moderation requires commercial plan */}- {Fider.session.tenant.hasCommercialFeatures && (+ {Fider.session.tenant.isPro && (<Field label="Content Moderation"><Toggle disabled={!Fider.session.user.isAdministrator} active={this.state.isModerationEnabled} onToggle={this.moderationToggle} /><p className="text-muted mt-1">diff --git a/public/services/fider.ts b/public/services/fider.tsindex 6395361e0..2d4491150 100644--- a/public/services/fider.ts+++ b/public/services/fider.ts@@ -43,12 +43,12 @@ export class FiderSession {public get isModerationRequiredForNewPost(): boolean {return (- this.pTenant.hasCommercialFeatures && this.pTenant.isModerationEnabled && this.isAuthenticated && this.pUser!.role === "visitor" && !this.pUser!.isTrusted+ this.pTenant.isPro && this.pTenant.isModerationEnabled && this.isAuthenticated && this.pUser!.role === "visitor" && !this.pUser!.isTrusted)}public get showModerationControls(): boolean {- return this.pTenant.hasCommercialFeatures && this.pTenant.isModerationEnabled && this.isAuthenticated && (this.pUser?.isCollaborator ?? false)+ return this.pTenant.isPro && this.pTenant.isModerationEnabled && this.isAuthenticated && (this.pUser?.isCollaborator ?? false)}}diff --git a/scripts/generate_license_keys.go b/scripts/generate_license_keys.godeleted file mode 100644index 30c3e60ec..000000000--- a/scripts/generate_license_keys.go+++ /dev/null@@ -1,40 +0,0 @@-package main--import (- "crypto/ed25519"- "crypto/rand"- "encoding/base64"- "fmt"- "log"-)--// This script generates an Ed25519 key pair for the commercial license system.-// For setup instructions, see docs/INTERNAL_LICENSE_SETUP.md--func main() {- // Generate Ed25519 key pair- publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)- if err != nil {- log.Fatal(err)- }-- // Encode as base64 for easy storage in env files- publicKeyB64 := base64.StdEncoding.EncodeToString(publicKey)- privateKeyB64 := base64.StdEncoding.EncodeToString(privateKey)-- fmt.Println("=== Ed25519 License Key Pair Generated ===")- fmt.Println()- fmt.Println("PUBLIC KEY (for self-hosted instances):")- fmt.Println(publicKeyB64)- fmt.Println()- fmt.Println("PRIVATE KEY (for hosted server only - KEEP SECRET!):")- fmt.Println(privateKeyB64)- fmt.Println()- fmt.Println("Add to production .env:")- fmt.Println("LICENSE_PRIVATE_KEY=" + privateKeyB64)- fmt.Println()- fmt.Println("Distribute to self-hosted customers:")- fmt.Println("LICENSE_PUBLIC_KEY=" + publicKeyB64)- fmt.Println()- fmt.Println("For full setup instructions, see docs/INTERNAL_LICENSE_SETUP.md")-}diff --git a/tsconfig.json b/tsconfig.jsonindex e1021294b..73790fe48 100755--- a/tsconfig.json+++ b/tsconfig.json@@ -14,9 +14,8 @@"noUnusedLocals": true,"paths": {"@fider/*": ["./public/*"],- "@commercial/*": ["./commercial/*"],"@locale/*": ["./locale/*"]}},- "include": ["./public/**/*", "./commercial/**/*", "./locale/**/*", "index.d.ts", "./e2e/**/*"]+ "include": ["./public/**/*", "./locale/**/*", "index.d.ts", "./e2e/**/*"]}diff --git a/webpack.config.js b/webpack.config.jsindex 2e2c905df..76054f607 100755--- a/webpack.config.js+++ b/webpack.config.js@@ -8,7 +8,6 @@ const PurgecssPlugin = require("purgecss-webpack-plugin")const MiniCssExtractPlugin = require("mini-css-extract-plugin")const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPluginconst publicFolder = path.resolve(__dirname, "public")-const commercialFolder = path.resolve(__dirname, "commercial")const localeFolder = path.resolve(__dirname, "locale")const isProduction = process.env.NODE_ENV === "production"@@ -37,7 +36,7 @@ const plugins = [if (isProduction) {plugins.push(new PurgecssPlugin({- paths: [...glob.sync(`./public/**/*.{html,tsx}`, { nodir: true }), ...glob.sync(`./commercial/**/*.{html,tsx}`, { nodir: true })],+ paths: [...glob.sync(`./public/**/*.{html,tsx}`, { nodir: true })],defaultExtractor: (content) => content.match(/[^<>"'`\s]*[^<>"'`\s:]/g) || [],safelist: [/--/, /__/, /data-/, /tiptap/],})@@ -63,7 +62,6 @@ module.exports = {extensions: [".mjs", ".ts", ".tsx", ".js", ".svg"],alias: {"@fider": publicFolder,- "@commercial": commercialFolder,"@locale": localeFolder,},},@@ -80,7 +78,7 @@ module.exports = {},{test: /\.(ts|tsx)$/,- include: [publicFolder, commercialFolder, localeFolder],+ include: [publicFolder, localeFolder],loader: "babel-loader",},{@@ -91,7 +89,7 @@ module.exports = {},{test: /\.svg$/,- include: [publicFolder, commercialFolder],+ include: [publicFolder],use: ["svg-sprite-loader", "svgo-loader"],},],