Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

Determine if instance is commercial or "normal"

Matt Robertsd44c90249c7c
diff --git a/.example.env b/.example.env
index 737c02333..c8ed924cd 100644
--- a/.example.env
+++ b/.example.env
@@ -33,3 +33,13 @@ EMAIL_SMTP_HOST=localhost
EMAIL_SMTP_PORT=1025
EMAIL_SMTP_USERNAME=
EMAIL_SMTP_PASSWORD=
+
+# Commercial License (Optional for self-hosted, Required for hosted multi-tenant)
+# LICENSE_MASTER_SECRET: Only required for hosted Fider instances that sell Pro subscriptions
+# - Used to generate and validate license keys for Pro customers
+# - Not needed for self-hosted unless you want to validate a COMMERCIAL_KEY
+# COMMERCIAL_KEY: For self-hosted Fider, set this to enable commercial features (content moderation)
+# - Leave blank to run Fider without commercial features (free/open-source mode)
+# - If you have a commercial license, set it here
+# LICENSE_MASTER_SECRET=your-secret-key-here-change-in-production
+# COMMERCIAL_KEY=FIDER-COMMERCIAL-123-1638360000-abc123...
diff --git a/.test.env b/.test.env
index 96821ae4f..464916b20 100644
--- a/.test.env
+++ b/.test.env
@@ -41,4 +41,4 @@ EMAIL_MAILGUN_DOMAIN=mydomain.com
USER_LIST_ENABLED=true
USER_LIST_APIKEY=abcdefg
-COMMERCIAL_ENABLED=true
+LICENSE_MASTER_SECRET=test_master_secret_for_license_generation
diff --git a/app/handlers/admin.go b/app/handlers/admin.go
index 8735ccee6..a90d75b5b 100644
--- a/app/handlers/admin.go
+++ b/app/handlers/admin.go
@@ -27,12 +27,19 @@ func GeneralSettingsPage() web.HandlerFunc {
// AdvancedSettingsPage is the advanced settings page
func 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,
+ "isCommercial": c.Tenant().IsCommercial,
},
})
}
diff --git a/app/handlers/billing.go b/app/handlers/billing.go
index 12396db5c..a1a77002f 100644
--- a/app/handlers/billing.go
+++ b/app/handlers/billing.go
@@ -27,7 +27,8 @@ func ManageBilling() web.HandlerFunc {
Data: web.Map{
"stripeCustomerID": billingState.Result.CustomerID,
"stripeSubscriptionID": billingState.Result.SubscriptionID,
- "isPro": c.Tenant().IsPro,
+ "licenseKey": billingState.Result.LicenseKey,
+ "isCommercial": c.Tenant().IsCommercial,
},
})
}
diff --git a/app/handlers/webhooks/stripe.go b/app/handlers/webhooks/stripe.go
index 6e013c010..0d5a0c536 100644
--- a/app/handlers/webhooks/stripe.go
+++ b/app/handlers/webhooks/stripe.go
@@ -13,6 +13,7 @@ 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"
@@ -59,10 +60,14 @@ 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/models/cmd/billing.go b/app/models/cmd/billing.go
index 1ff09d32f..feb46c819 100644
--- a/app/models/cmd/billing.go
+++ b/app/models/cmd/billing.go
@@ -12,6 +12,7 @@ type ActivateStripeSubscription struct {
TenantID int
CustomerID string
SubscriptionID string
+ LicenseKey string
}
type CancelStripeSubscription struct {
diff --git a/app/models/entity/billing.go b/app/models/entity/billing.go
index 294eb84de..06d0841fa 100644
--- a/app/models/entity/billing.go
+++ b/app/models/entity/billing.go
@@ -24,4 +24,5 @@ type BillingPayment struct {
type StripeBillingState struct {
CustomerID string `json:"customerID"`
SubscriptionID string `json:"subscriptionID"`
+ LicenseKey string `json:"licenseKey"`
}
diff --git a/app/models/entity/tenant.go b/app/models/entity/tenant.go
index ae1dd009b..7787a0b5f 100644
--- a/app/models/entity/tenant.go
+++ b/app/models/entity/tenant.go
@@ -1,6 +1,8 @@
package entity
-import "github.com/getfider/fider/app/models/enum"
+import (
+ "github.com/getfider/fider/app/models/enum"
+)
// Tenant represents a tenant
type Tenant struct {
@@ -20,7 +22,7 @@ type Tenant struct {
IsFeedEnabled bool `json:"isFeedEnabled"`
PreventIndexing bool `json:"preventIndexing"`
IsModerationEnabled bool `json:"isModerationEnabled"`
- IsPro bool `json:"isPro"`
+ IsCommercial bool `json:"isCommercial"`
}
func (t *Tenant) IsDisabled() bool {
diff --git a/app/pkg/env/env.go b/app/pkg/env/env.go
index 211ccc7b8..406892180 100644
--- a/app/pkg/env/env.go
+++ b/app/pkg/env/env.go
@@ -143,8 +143,9 @@ 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"`
- Commercial struct {
- Enabled bool `env:"COMMERCIAL_ENABLED,default=true"`
+ License struct {
+ MasterSecret string `env:"LICENSE_MASTER_SECRET"`
+ Key string `env:"COMMERCIAL_KEY"`
}
}
@@ -246,9 +247,9 @@ func IsBillingEnabled() bool {
return Config.Stripe.SecretKey != ""
}
-// IsCommercialEnabled returns true if commercial features are enabled
-func IsCommercialEnabled() bool {
- return Config.Commercial.Enabled
+// IsMultiHostMode returns true if host mode is set to multi tenant
+func IsMultiHostMode() bool {
+ return Config.HostMode == "multi"
}
// IsProduction returns true on Fider production environment
diff --git a/app/pkg/web/renderer.go b/app/pkg/web/renderer.go
index 78bd253b5..4fa325bad 100644
--- a/app/pkg/web/renderer.go
+++ b/app/pkg/web/renderer.go
@@ -204,20 +204,19 @@ func (r *Renderer) Render(w io.Writer, statusCode int, props Props, ctx *Context
public["tenant"] = tenant
public["props"] = props.Data
public["settings"] = &Map{
- "mode": env.Config.HostMode,
- "locale": locale,
- "localeDirection": localeDirection,
- "environment": env.Config.Environment,
- "googleAnalytics": env.Config.GoogleAnalytics,
- "domain": env.MultiTenantDomain(),
- "hasLegal": env.HasLegal(),
- "isBillingEnabled": env.IsBillingEnabled(),
- "isCommercialEnabled": env.IsCommercialEnabled(),
- "baseURL": ctx.BaseURL(),
- "assetsURL": AssetsURL(ctx, ""),
- "oauth": oauthProviders.Result,
- "postWithTags": env.Config.PostCreationWithTagsEnabled,
- "allowAllowedSchemes": env.Config.AllowAllowedSchemes,
+ "mode": env.Config.HostMode,
+ "locale": locale,
+ "localeDirection": localeDirection,
+ "environment": env.Config.Environment,
+ "googleAnalytics": env.Config.GoogleAnalytics,
+ "domain": env.MultiTenantDomain(),
+ "hasLegal": env.HasLegal(),
+ "isBillingEnabled": env.IsBillingEnabled(),
+ "baseURL": ctx.BaseURL(),
+ "assetsURL": AssetsURL(ctx, ""),
+ "oauth": oauthProviders.Result,
+ "postWithTags": env.Config.PostCreationWithTagsEnabled,
+ "allowAllowedSchemes": env.Config.AllowAllowedSchemes,
}
if ctx.IsAuthenticated() {
diff --git a/app/pkg/web/testdata/basic.html b/app/pkg/web/testdata/basic.html
index 4aad10313..4f7cd1fd1 100755
--- a/app/pkg/web/testdata/basic.html
+++ b/app/pkg/web/testdata/basic.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,"isCommercialEnabled":true,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true},"tenant":null,"title":"Fider"}
+ {"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":null,"title":"Fider"}
</script>
diff --git a/app/pkg/web/testdata/canonical.html b/app/pkg/web/testdata/canonical.html
index efc0c62f9..f6334b1e2 100755
--- a/app/pkg/web/testdata/canonical.html
+++ b/app/pkg/web/testdata/canonical.html
@@ -47,7 +47,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,"isCommercialEnabled":true,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true},"tenant":null,"title":"Fider"}
+ {"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":null,"title":"Fider"}
</script>
diff --git a/app/pkg/web/testdata/chunk.html b/app/pkg/web/testdata/chunk.html
index a161c9131..dfdf17bc3 100644
--- a/app/pkg/web/testdata/chunk.html
+++ b/app/pkg/web/testdata/chunk.html
@@ -45,7 +45,7 @@
<script id="server-data" type="application/json">
- {"contextID":"CONTEXT_ID","page":"Test.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,"isCommercialEnabled":true,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true},"tenant":null,"title":"Fider"}
+ {"contextID":"CONTEXT_ID","page":"Test.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":null,"title":"Fider"}
</script>
diff --git a/app/pkg/web/testdata/home.html b/app/pkg/web/testdata/home.html
index dbea062ad..3297e64d6 100755
--- a/app/pkg/web/testdata/home.html
+++ b/app/pkg/web/testdata/home.html
@@ -45,7 +45,7 @@
<script id="server-data" type="application/json">
- {"contextID":"CONTEXT_ID","description":"My Page Description","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,"isCommercialEnabled":true,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true},"tenant":null,"title":"My Page Title · Fider"}
+ {"contextID":"CONTEXT_ID","description":"My Page Description","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":null,"title":"My Page Title · Fider"}
</script>
diff --git a/app/pkg/web/testdata/home_ssr.html b/app/pkg/web/testdata/home_ssr.html
index 8b5e72cdf..04444844f 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,"isCommercialEnabled":true,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true},"tenant":{"id":0,"name":"","subdomain":"","invitation":"","welcomeMessage":"","cname":"","status":0,"locale":"en","isPrivate":false,"logoBlobKey":"","allowedSchemes":"","isEmailAuthAllowed":false,"isFeedEnabled":false,"preventIndexing":false,"isModerationEnabled":false,"isPro":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":"","cname":"","status":0,"locale":"en","isPrivate":false,"logoBlobKey":"","allowedSchemes":"","isEmailAuthAllowed":false,"isFeedEnabled":false,"preventIndexing":false,"isModerationEnabled":false,"isCommercial":false},"title":"My Page Title · "}
</script>
diff --git a/app/pkg/web/testdata/oauth.html b/app/pkg/web/testdata/oauth.html
index 6291ac1fc..7019812c2 100755
--- a/app/pkg/web/testdata/oauth.html
+++ b/app/pkg/web/testdata/oauth.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,"isCommercialEnabled":true,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[{"provider":"google","displayName":"Google","clientID":"1234","url":"https://demo.test.fider.io:3000/oauth/google","callbackURL":"https://demo.test.fider.io:3000/oauth/google/callback","logoBlobKey":"google.png","isCustomProvider":false,"isEnabled":true}],"postWithTags":true},"tenant":null,"title":"Fider"}
+ {"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":[{"provider":"google","displayName":"Google","clientID":"1234","url":"https://demo.test.fider.io:3000/oauth/google","callbackURL":"https://demo.test.fider.io:3000/oauth/google/callback","logoBlobKey":"google.png","isCustomProvider":false,"isEnabled":true}],"postWithTags":true},"tenant":null,"title":"Fider"}
</script>
diff --git a/app/pkg/web/testdata/tenant.html b/app/pkg/web/testdata/tenant.html
index bbf00ca0a..627dd2ee6 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,"isCommercialEnabled":true,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true},"tenant":{"id":0,"name":"Game of Thrones","subdomain":"","invitation":"","welcomeMessage":"","cname":"","status":0,"locale":"","isPrivate":false,"logoBlobKey":"","allowedSchemes":"","isEmailAuthAllowed":false,"isFeedEnabled":false,"preventIndexing":false,"isModerationEnabled":false,"isPro":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":"","cname":"","status":0,"locale":"","isPrivate":false,"logoBlobKey":"","allowedSchemes":"","isEmailAuthAllowed":false,"isFeedEnabled":false,"preventIndexing":false,"isModerationEnabled":false,"isCommercial":false},"title":"Game of Thrones"}
</script>
diff --git a/app/pkg/web/testdata/user.html b/app/pkg/web/testdata/user.html
index 354f09fdc..168530a36 100755
--- a/app/pkg/web/testdata/user.html
+++ b/app/pkg/web/testdata/user.html
@@ -45,7 +45,7 @@
<script id="server-data" type="application/json">
- {"contextID":"CONTEXT_ID","description":"My Page Description","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,"isCommercialEnabled":true,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true},"tenant":null,"title":"My Page Title · Fider","user":{"avatarBlobKey":"","avatarType":"gravatar","avatarURL":"https://demo.test.fider.io:3000/static/avatars/gravatar/5/Jon%20Snow","email":"[email protected]","id":5,"isAdministrator":true,"isCollaborator":true,"isTrusted":false,"name":"Jon Snow","role":"administrator","status":"active"}}
+ {"contextID":"CONTEXT_ID","description":"My Page Description","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":null,"title":"My Page Title · Fider","user":{"avatarBlobKey":"","avatarType":"gravatar","avatarURL":"https://demo.test.fider.io:3000/static/avatars/gravatar/5/Jon%20Snow","email":"[email protected]","id":5,"isAdministrator":true,"isCollaborator":true,"isTrusted":false,"name":"Jon Snow","role":"administrator","status":"active"}}
</script>
diff --git a/app/services/license/validator.go b/app/services/license/validator.go
new file mode 100644
index 000000000..78ed3c4ea
--- /dev/null
+++ b/app/services/license/validator.go
@@ -0,0 +1,107 @@
+package license
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "crypto/subtle"
+ "encoding/hex"
+ "fmt"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/errors"
+)
+
+// GenerateKey generates a commercial license key for a tenant
+// Format: FIDER-COMMERCIAL-{tenantID}-{timestamp}-{hmacHex}
+// Panics if LICENSE_MASTER_SECRET is not set
+func GenerateKey(tenantID int) string {
+ if env.Config.License.MasterSecret == "" {
+ panic("LICENSE_MASTER_SECRET environment variable must be set to generate license keys. This is required for hosted Fider instances that sell Pro subscriptions.")
+ }
+ timestamp := time.Now().Unix()
+ data := fmt.Sprintf("%d-%d", tenantID, timestamp)
+ mac := hmac.New(sha256.New, []byte(env.Config.License.MasterSecret))
+ mac.Write([]byte(data))
+ hash := hex.EncodeToString(mac.Sum(nil))
+ return fmt.Sprintf("FIDER-COMMERCIAL-%d-%d-%s", tenantID, timestamp, hash)
+}
+
+// ValidationResult contains the result of license key validation
+type ValidationResult struct {
+ IsValid bool
+ TenantID int
+ Error error
+}
+
+// ValidateKey validates a commercial license key and returns the tenant ID
+// Requires LICENSE_MASTER_SECRET to be set for validation
+func ValidateKey(key string) *ValidationResult {
+ if key == "" {
+ return &ValidationResult{
+ IsValid: false,
+ TenantID: 0,
+ Error: errors.New("license key is empty"),
+ }
+ }
+
+ if env.Config.License.MasterSecret == "" {
+ return &ValidationResult{
+ IsValid: false,
+ TenantID: 0,
+ Error: errors.New("LICENSE_MASTER_SECRET environment variable must be set to validate license keys"),
+ }
+ }
+
+ 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}-{hmac}"),
+ }
+ }
+
+ 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"),
+ }
+ }
+
+ providedHash := parts[4]
+
+ // Recompute HMAC to verify signature
+ data := fmt.Sprintf("%d-%d", tenantID, timestamp)
+ mac := hmac.New(sha256.New, []byte(env.Config.License.MasterSecret))
+ mac.Write([]byte(data))
+ expectedHash := hex.EncodeToString(mac.Sum(nil))
+
+ // Constant-time comparison to prevent timing attacks
+ if subtle.ConstantTimeCompare([]byte(expectedHash), []byte(providedHash)) != 1 {
+ 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/sqlstore/dbEntities/billing.go b/app/services/sqlstore/dbEntities/billing.go
index 4e70f4878..1e3a2a92f 100644
--- a/app/services/sqlstore/dbEntities/billing.go
+++ b/app/services/sqlstore/dbEntities/billing.go
@@ -7,4 +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"`
}
diff --git a/app/services/sqlstore/dbEntities/tenant.go b/app/services/sqlstore/dbEntities/tenant.go
index 85f3a3811..71243284a 100644
--- a/app/services/sqlstore/dbEntities/tenant.go
+++ b/app/services/sqlstore/dbEntities/tenant.go
@@ -3,6 +3,8 @@ package dbEntities
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 {
@@ -30,6 +32,16 @@ func (t *Tenant) ToModel() *entity.Tenant {
return nil
}
+ // Compute isCommercial based on hosting mode
+ var isCommercial bool
+ if env.IsSingleHostMode() {
+ // Self-hosted: check if license service validated successfully
+ isCommercial = services.IsCommercialFeatureEnabled(services.FeatureContentModeration)
+ } else {
+ // Hosted multi-tenant: check if this tenant has Pro subscription
+ isCommercial = t.IsPro
+ }
+
tenant := &entity.Tenant{
ID: t.ID,
Name: t.Name,
@@ -47,7 +59,7 @@ func (t *Tenant) ToModel() *entity.Tenant {
IsFeedEnabled: t.IsFeedEnabled,
PreventIndexing: t.PreventIndexing,
IsModerationEnabled: t.IsModerationEnabled,
- IsPro: t.IsPro,
+ IsCommercial: isCommercial,
}
return tenant
diff --git a/app/services/sqlstore/postgres/billing.go b/app/services/sqlstore/postgres/billing.go
index d10d4c2d9..f441d3ffa 100644
--- a/app/services/sqlstore/postgres/billing.go
+++ b/app/services/sqlstore/postgres/billing.go
@@ -47,7 +47,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
+ `SELECT stripe_customer_id, stripe_subscription_id, license_key
FROM tenants_billing
WHERE tenant_id = $1`, tenant.ID)
@@ -63,6 +63,7 @@ func getStripeBillingState(ctx context.Context, q *query.GetStripeBillingState)
q.Result = &entity.StripeBillingState{
CustomerID: state.StripeCustomerID.String,
SubscriptionID: state.StripeSubscriptionID.String,
+ LicenseKey: state.LicenseKey.String,
}
return nil
})
@@ -71,11 +72,11 @@ func getStripeBillingState(ctx context.Context, q *query.GetStripeBillingState)
func activateStripeSubscription(ctx context.Context, c *cmd.ActivateStripeSubscription) error {
return using(ctx, func(trx *dbx.Trx, _ *entity.Tenant, _ *entity.User) error {
_, err := trx.Execute(`
- INSERT INTO tenants_billing (tenant_id, stripe_customer_id, stripe_subscription_id)
- VALUES ($1, $2, $3)
+ INSERT INTO tenants_billing (tenant_id, stripe_customer_id, stripe_subscription_id, license_key)
+ VALUES ($1, $2, $3, $4)
ON CONFLICT (tenant_id) DO UPDATE
- SET stripe_customer_id = $2, stripe_subscription_id = $3
- `, c.TenantID, c.CustomerID, c.SubscriptionID)
+ SET stripe_customer_id = $2, stripe_subscription_id = $3, license_key = $4
+ `, c.TenantID, c.CustomerID, c.SubscriptionID, c.LicenseKey)
if err != nil {
return errors.Wrap(err, "failed to activate stripe subscription")
}
diff --git a/app/tasks/userlist.go b/app/tasks/userlist.go
index 8d2f1ef8a..4709330b8 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.IsPro {
+ if tenant.IsCommercial {
plan = enum.PlanPro
}
diff --git a/commercial/components/ModerationIndicator.tsx b/commercial/components/ModerationIndicator.tsx
index eaba5a9f4..0d6275fee 100644
--- a/commercial/components/ModerationIndicator.tsx
+++ b/commercial/components/ModerationIndicator.tsx
@@ -11,7 +11,7 @@ export const ModerationIndicator = () => {
const [loading, setLoading] = useState(true)
// Check if commercial license is available
- const hasCommercialLicense = fider.settings.isCommercialEnabled
+ const hasCommercialLicense = fider.session.tenant.isCommercial
useEffect(() => {
const fetchCount = async () => {
diff --git a/commercial/init.go b/commercial/init.go
index 44ae65344..02e0affa0 100644
--- a/commercial/init.go
+++ b/commercial/init.go
@@ -1,57 +1,94 @@
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() {
- // Register commercial license service
- services.License = &commercialLicenseService{}
-
- // Only register commercial handlers if commercial features are enabled
- if env.IsCommercialEnabled() {
- // Register commercial HTTP handlers
- 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,
- )
+ ctx := context.Background()
+ var svc *commercialLicenseService
+
+ if env.IsSingleHostMode() && env.Config.License.Key != "" {
+ // 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()}
}
-}
-// Commercial license service implementation
-type commercialLicenseService struct{}
+ // 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 {
- // TODO: Implement actual license validation
- // For now, use environment variable to control feature availability
- // Set COMMERCIAL_ENABLED=false to test without commercial features
- if !env.IsCommercialEnabled() {
- return false
+ // In self-hosted mode, check license validity
+ if env.IsSingleHostMode() {
+ return s.isValid && feature == services.FeatureContentModeration
}
- return feature == services.FeatureContentModeration
+
+ // In multi-tenant mode, this is a global check
+ // Per-tenant checking happens via tenant.IsCommercial()
+ 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: true,
- Features: []string{services.FeatureContentModeration},
- LicenseHolder: "Commercial License Holder",
+ IsValid: false,
+ Features: []string{},
+ LicenseHolder: "Unlicensed",
}
}
diff --git a/migrations/202511282000_add_license_key_to_billing.sql b/migrations/202511282000_add_license_key_to_billing.sql
new file mode 100644
index 000000000..b51e64ff0
--- /dev/null
+++ b/migrations/202511282000_add_license_key_to_billing.sql
@@ -0,0 +1,2 @@
+-- Add license key storage to tenants_billing table
+ALTER TABLE tenants_billing ADD COLUMN license_key TEXT;
diff --git a/public/models/identity.ts b/public/models/identity.ts
index d05692e54..207e60f97 100644
--- a/public/models/identity.ts
+++ b/public/models/identity.ts
@@ -13,7 +13,7 @@ export interface Tenant {
isEmailAuthAllowed: boolean
isFeedEnabled: boolean
isModerationEnabled: boolean
- isPro: boolean
+ isCommercial: boolean
}
export enum TenantStatus {
diff --git a/public/models/settings.ts b/public/models/settings.ts
index a2ff962a7..98c129440 100644
--- a/public/models/settings.ts
+++ b/public/models/settings.ts
@@ -17,7 +17,6 @@ export interface SystemSettings {
domain: string
hasLegal: boolean
isBillingEnabled: boolean
- isCommercialEnabled: boolean
baseURL: string
assetsURL: string
oauth: OAuthProviderOption[]
diff --git a/public/pages/Administration/pages/AdvancedSettings.page.tsx b/public/pages/Administration/pages/AdvancedSettings.page.tsx
index c7c893ec6..f41b0cfa4 100644
--- a/public/pages/Administration/pages/AdvancedSettings.page.tsx
+++ b/public/pages/Administration/pages/AdvancedSettings.page.tsx
@@ -7,12 +7,15 @@ import { AdminBasePage } from "../components/AdminBasePage"
interface AdvancedSettingsPageProps {
customCSS: string
allowedSchemes: string
+ licenseKey: string
+ isCommercial: boolean
}
interface AdvancedSettingsPageState {
customCSS: string
allowedSchemes: string
error?: Failure
+ copied: boolean
}
export default class AdvancedSettingsPage extends AdminBasePage<AdvancedSettingsPageProps, AdvancedSettingsPageState> {
@@ -27,6 +30,7 @@ export default class AdvancedSettingsPage extends AdminBasePage<AdvancedSettings
this.state = {
customCSS: this.props.customCSS,
allowedSchemes: this.props.allowedSchemes,
+ copied: false,
}
}
@@ -47,9 +51,39 @@ 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.isCommercial && 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>
+ )}
+
<TextArea
field="customCSS"
label="Custom CSS"
diff --git a/public/pages/Administration/pages/ManageBilling.page.tsx b/public/pages/Administration/pages/ManageBilling.page.tsx
index fc31c4a25..503181739 100644
--- a/public/pages/Administration/pages/ManageBilling.page.tsx
+++ b/public/pages/Administration/pages/ManageBilling.page.tsx
@@ -10,7 +10,8 @@ import "./ManageBilling.page.scss"
interface ManageBillingPageProps {
stripeCustomerID: string
stripeSubscriptionID: string
- isPro: boolean
+ licenseKey: string
+ isCommercial: boolean
}
interface PlanCardProps {
@@ -74,7 +75,7 @@ const PlanCard = (props: PlanCardProps) => {
const ManageBillingPage = (props: ManageBillingPageProps) => {
const [isLoading, setIsLoading] = useState(false)
- const isPro = props.isPro
+ const isCommercial = props.isCommercial
const openPortal = async () => {
setIsLoading(true)
@@ -103,6 +104,15 @@ const ManageBillingPage = (props: ManageBillingPageProps) => {
return (
<AdminPageContainer id="p-admin-billing" name="billing" title="Billing" subtitle="Manage your subscription and billing">
<p>Fider is free forever. But if you need advanced features and support, consider upgrading to Pro.</p>
+
+ {isCommercial && 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">
<PlanCard
name="Free"
@@ -110,11 +120,11 @@ const ManageBillingPage = (props: ManageBillingPageProps) => {
period="month"
description="Perfect for getting started with feedback collection."
features={freeFeatures}
- isCurrent={!isPro}
+ isCurrent={!isCommercial}
buttonText="Downgrade"
buttonVariant="secondary"
- onButtonClick={isPro ? openPortal : undefined}
- isLoading={isLoading && isPro}
+ onButtonClick={isCommercial ? openPortal : undefined}
+ isLoading={isLoading && isCommercial}
/>
<PlanCard
@@ -123,11 +133,11 @@ const ManageBillingPage = (props: ManageBillingPageProps) => {
period="month"
description="For teams that need advanced features and support."
features={proFeatures}
- isCurrent={isPro}
+ isCurrent={isCommercial}
isHighlighted={true}
- buttonText={isPro ? "Manage Billing" : "Upgrade to Pro"}
+ buttonText={isCommercial ? "Manage Billing" : "Upgrade to Pro"}
buttonVariant="primary"
- onButtonClick={isPro ? openPortal : startCheckout}
+ onButtonClick={isCommercial ? openPortal : startCheckout}
isLoading={isLoading}
/>
</div>
diff --git a/public/pages/Administration/pages/PrivacySettings.page.tsx b/public/pages/Administration/pages/PrivacySettings.page.tsx
index b5d99cf25..6ccb46a6e 100644
--- a/public/pages/Administration/pages/PrivacySettings.page.tsx
+++ b/public/pages/Administration/pages/PrivacySettings.page.tsx
@@ -71,7 +71,7 @@ export default class PrivacySettingsPage extends AdminBasePage<any, PrivacySetti
</p>
</Field>
{/* Moderation requires commercial plan */}
- {Fider.session.isCommercialEnabled && (
+ {Fider.session.tenant.isCommercial && (
<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.ts
index a98a711cc..9c679569e 100644
--- a/public/services/fider.ts
+++ b/public/services/fider.ts
@@ -7,7 +7,6 @@ export class FiderSession {
private pTenant: Tenant
private pUser: CurrentUser | undefined
private pProps: { [key: string]: any } = {}
- private pSettings: SystemSettings
constructor(data: any) {
this.pPage = data.page
@@ -15,7 +14,6 @@ export class FiderSession {
this.pProps = data.props
this.pUser = data.user
this.pTenant = data.tenant
- this.pSettings = data.settings
}
public get page(): string {
@@ -44,15 +42,11 @@ export class FiderSession {
}
public get isModerationRequiredForNewPost(): boolean {
- return this.isCommercialEnabled && this.pTenant.isModerationEnabled && this.isAuthenticated && this.pUser!.role === "visitor" && !this.pUser!.isTrusted
+ return this.pTenant.isCommercial && this.pTenant.isModerationEnabled && this.isAuthenticated && this.pUser!.role === "visitor" && !this.pUser!.isTrusted
}
public get showModerationControls(): boolean {
- return this.isCommercialEnabled && this.pTenant.isModerationEnabled && this.isAuthenticated && (this.pUser?.isCollaborator ?? false)
- }
-
- public get isCommercialEnabled(): boolean {
- return this.pSettings.isCommercialEnabled
+ return this.pTenant.isCommercial && this.pTenant.isModerationEnabled && this.isAuthenticated && (this.pUser?.isCollaborator ?? false)
}
}