Open platform to collect and prioritize feedback
Ability to delete your fider board if you are in multi site mode.
Matt Roberts0b2b1df7afbf
diff --git a/app/cmd/routes.go b/app/cmd/routes.goindex 07941738b..c434a9ed7 100644--- a/app/cmd/routes.go+++ b/app/cmd/routes.go@@ -129,6 +129,12 @@ func routes(r *web.Engine) *web.Engine {r.Post("/_api/signin/verify", handlers.VerifySignInCode())r.Post("/_api/signin/resend", handlers.ResendSignInCode())+ // Cancel a scheduled site deletion. Authorised by the unguessable key in the emailed link+ // alone, so it must stay reachable without authentication (it only restores access).+ if !env.IsSingleHostMode() {+ r.Get("/admin/danger-zone/cancel", handlers.CancelTenantDeletion())+ }+// Block if it's private tenant with unauthenticated userr.Use(middlewares.CheckTenantPrivacy())@@ -180,6 +186,14 @@ func routes(r *web.Engine) *web.Engine {// From this step, only Administrators are allowedui.Use(middlewares.IsAuthorized(enum.RoleAdministrator))+ // Danger Zone — delete the entire site. Hosted multi-tenant only; owner-only is+ // enforced inside the handlers.+ if !env.IsSingleHostMode() {+ ui.Get("/admin/danger-zone", handlers.DangerZonePage())+ ui.Delete("/_api/admin/tenant", handlers.RequestTenantDeletion())+ ui.Post("/_api/admin/tenant/cancel-deletion", handlers.CancelTenantDeletionByOwner())+ }+ui.Get("/admin/export", handlers.Page("Export · Site Settings", "", "Administration/pages/Export.page"))ui.Get("/admin/export/posts.csv", handlers.ExportPostsToCSV())ui.Get("/admin/export/backup.zip", handlers.ExportBackupZip())diff --git a/app/cmd/server.go b/app/cmd/server.goindex b9c1ae12c..eaec193df 100644--- a/app/cmd/server.go+++ b/app/cmd/server.go@@ -58,6 +58,7 @@ func startJobs(ctx context.Context) {c := cron.New()_ = c.AddJob(jobs.NewJob(ctx, "PurgeExpiredNotificationsJob", jobs.PurgeExpiredNotificationsJobHandler{}))_ = c.AddJob(jobs.NewJob(ctx, "EmailSupressionJob", jobs.EmailSupressionJobHandler{}))+ _ = c.AddJob(jobs.NewJob(ctx, "DeleteScheduledTenantsJob", jobs.DeleteScheduledTenantsJobHandler{}))c.Start()}diff --git a/app/handlers/danger_zone.go b/app/handlers/danger_zone.gonew file mode 100644index 000000000..fc29e4cd7--- /dev/null+++ b/app/handlers/danger_zone.go@@ -0,0 +1,132 @@+package handlers++import (+ "net/http"+ "time"++ "github.com/getfider/fider/app/models/cmd"+ "github.com/getfider/fider/app/models/entity"+ "github.com/getfider/fider/app/models/query"+ "github.com/getfider/fider/app/pkg/bus"+ "github.com/getfider/fider/app/pkg/env"+ "github.com/getfider/fider/app/pkg/rand"+ "github.com/getfider/fider/app/pkg/web"+ "github.com/getfider/fider/app/tasks"+)++// gracePeriod is how long a site deletion is delayed so the owner can change their mind.+const gracePeriod = time.Hour++// tenantOwner returns the account owner (the lowest-id active administrator) of the current+// tenant. Callers compare the returned user's ID with c.User().ID to gate owner-only actions.+func tenantOwner(c *web.Context) (*entity.User, error) {+ q := &query.GetTenantOwner{TenantID: c.Tenant().ID}+ if err := bus.Dispatch(c, q); err != nil {+ return nil, err+ }+ return q.Result, nil+}++// DangerZonePage renders the admin Danger Zone (delete entire site).+func DangerZonePage() web.HandlerFunc {+ return func(c *web.Context) error {+ owner, err := tenantOwner(c)+ if err != nil {+ return c.Failure(err)+ }++ return c.Page(http.StatusOK, web.Props{+ Page: "Administration/pages/DangerZone.page",+ Title: "Danger Zone · Site Settings",+ Data: web.Map{+ "isOwner": c.User().ID == owner.ID,+ "scheduledDeletionAt": c.Tenant().ScheduledDeletionAt,+ },+ })+ }+}++// RequestTenantDeletion schedules deletion of the whole site after a grace period. Only the+// account owner may do this, and only on hosted multi-tenant instances.+func RequestTenantDeletion() web.HandlerFunc {+ return func(c *web.Context) error {+ if env.IsSingleHostMode() {+ return c.Forbidden()+ }++ owner, err := tenantOwner(c)+ if err != nil {+ return c.Failure(err)+ }+ if c.User().ID != owner.ID {+ return c.Forbidden()+ }++ input := new(struct {+ Subdomain string `json:"subdomain"`+ })+ if err := c.Bind(input); err != nil {+ return c.BadRequest(web.Map{})+ }+ if input.Subdomain != c.Tenant().Subdomain {+ return c.BadRequest(web.Map{"message": "The subdomain you entered does not match this site."})+ }++ cancelKey := rand.String(64)+ scheduledAt := time.Now().Add(gracePeriod)++ if err := bus.Dispatch(c, &cmd.ScheduleTenantDeletion{+ TenantID: c.Tenant().ID,+ RequestedByUserID: c.User().ID,+ CancelKey: cancelKey,+ ScheduledAt: scheduledAt,+ }); err != nil {+ return c.Failure(err)+ }++ c.Enqueue(tasks.SendDeleteAccountScheduledEmail(owner, c.Tenant().Name, scheduledAt, c.BaseURL(), cancelKey))++ return c.Ok(web.Map{"scheduledDeletionAt": scheduledAt})+ }+}++// CancelTenantDeletionByOwner cancels a scheduled deletion from the Danger Zone page. Unlike+// the emailed link, this is authorised by the logged-in owner rather than a key.+func CancelTenantDeletionByOwner() web.HandlerFunc {+ return func(c *web.Context) error {+ if env.IsSingleHostMode() {+ return c.Forbidden()+ }++ owner, err := tenantOwner(c)+ if err != nil {+ return c.Failure(err)+ }+ if c.User().ID != owner.ID {+ return c.Forbidden()+ }++ if err := bus.Dispatch(c, &cmd.CancelTenantDeletion{TenantID: c.Tenant().ID}); err != nil {+ return c.Failure(err)+ }+ return c.Ok(web.Map{})+ }+}++// CancelTenantDeletion cancels a scheduled deletion. The unguessable key in the query string+// is the sole authorisation, so the emailed cancel link works without the owner being logged+// in (it only ever restores access).+func CancelTenantDeletion() web.HandlerFunc {+ return func(c *web.Context) error {+ key := c.QueryParam("k")+ if key != "" {+ byKey := &query.GetTenantByCancelKey{Key: key}+ if err := bus.Dispatch(c, byKey); err == nil && byKey.Result != nil {+ if err := bus.Dispatch(c, &cmd.CancelTenantDeletion{TenantID: byKey.Result.ID}); err != nil {+ return c.Failure(err)+ }+ }+ }+ return c.Redirect(c.BaseURL() + "/admin/danger-zone")+ }+}diff --git a/app/handlers/danger_zone_test.go b/app/handlers/danger_zone_test.gonew file mode 100644index 000000000..a5c572d83--- /dev/null+++ b/app/handlers/danger_zone_test.go@@ -0,0 +1,128 @@+package handlers_test++import (+ "context"+ "net/http"+ "testing"+ "time"++ "github.com/getfider/fider/app/handlers"+ "github.com/getfider/fider/app/models/cmd"+ "github.com/getfider/fider/app/models/entity"+ "github.com/getfider/fider/app/models/query"+ . "github.com/getfider/fider/app/pkg/assert"+ "github.com/getfider/fider/app/pkg/bus"+ "github.com/getfider/fider/app/pkg/mock"+)++// ownerIs registers a GetTenantOwner handler that always returns the given user.+func ownerIs(owner *entity.User) {+ bus.AddHandler(func(ctx context.Context, q *query.GetTenantOwner) error {+ q.Result = owner+ return nil+ })+}++func TestRequestTenantDeletion_SingleHostBlocked(t *testing.T) {+ RegisterT(t)+ ownerIs(mock.JonSnow)++ server := mock.NewSingleTenantServer()+ code, _ := server.+ OnTenant(mock.DemoTenant).+ AsUser(mock.JonSnow).+ ExecutePost(handlers.RequestTenantDeletion(), `{"subdomain":"demo"}`)++ Expect(code).Equals(http.StatusForbidden)+}++func TestRequestTenantDeletion_NonOwnerForbidden(t *testing.T) {+ RegisterT(t)+ ownerIs(mock.JonSnow) // owner is Jon, but Arya is making the request++ server := mock.NewServer()+ code, _ := server.+ OnTenant(mock.DemoTenant).+ AsUser(mock.AryaStark).+ ExecutePost(handlers.RequestTenantDeletion(), `{"subdomain":"demo"}`)++ Expect(code).Equals(http.StatusForbidden)+}++func TestRequestTenantDeletion_WrongSubdomain(t *testing.T) {+ RegisterT(t)+ ownerIs(mock.JonSnow)++ scheduled := false+ bus.AddHandler(func(ctx context.Context, c *cmd.ScheduleTenantDeletion) error {+ scheduled = true+ return nil+ })++ server := mock.NewServer()+ code, _ := server.+ OnTenant(mock.DemoTenant).+ AsUser(mock.JonSnow).+ ExecutePost(handlers.RequestTenantDeletion(), `{"subdomain":"not-demo"}`)++ Expect(code).Equals(http.StatusBadRequest)+ Expect(scheduled).IsFalse()+}++func TestRequestTenantDeletion_OwnerSchedules(t *testing.T) {+ RegisterT(t)+ ownerIs(mock.JonSnow)++ var scheduled *cmd.ScheduleTenantDeletion+ bus.AddHandler(func(ctx context.Context, c *cmd.ScheduleTenantDeletion) error {+ scheduled = c+ return nil+ })++ server := mock.NewServer()+ code, _ := server.+ OnTenant(mock.DemoTenant).+ AsUser(mock.JonSnow).+ ExecutePost(handlers.RequestTenantDeletion(), `{"subdomain":"demo"}`)++ Expect(code).Equals(http.StatusOK)+ Expect(scheduled).IsNotNil()+ Expect(scheduled.TenantID).Equals(mock.DemoTenant.ID)+ Expect(scheduled.RequestedByUserID).Equals(mock.JonSnow.ID)+ Expect(len(scheduled.CancelKey)).Equals(64)+ Expect(scheduled.ScheduledAt.After(time.Now())).IsTrue()+}++func TestCancelTenantDeletionByOwner_NonOwnerForbidden(t *testing.T) {+ RegisterT(t)+ ownerIs(mock.JonSnow)++ server := mock.NewServer()+ code, _ := server.+ OnTenant(mock.DemoTenant).+ AsUser(mock.AryaStark).+ ExecutePost(handlers.CancelTenantDeletionByOwner(), `{}`)++ Expect(code).Equals(http.StatusForbidden)+}++func TestCancelTenantDeletionByOwner_OwnerCancels(t *testing.T) {+ RegisterT(t)+ ownerIs(mock.JonSnow)++ var cancelled *cmd.CancelTenantDeletion+ bus.AddHandler(func(ctx context.Context, c *cmd.CancelTenantDeletion) error {+ cancelled = c+ return nil+ })++ server := mock.NewServer()+ code, _ := server.+ OnTenant(mock.DemoTenant).+ AsUser(mock.JonSnow).+ ExecutePost(handlers.CancelTenantDeletionByOwner(), `{}`)++ Expect(code).Equals(http.StatusOK)+ Expect(cancelled).IsNotNil()+ Expect(cancelled.TenantID).Equals(mock.DemoTenant.ID)+}diff --git a/app/jobs/delete_scheduled_tenants_job.go b/app/jobs/delete_scheduled_tenants_job.gonew file mode 100644index 000000000..9c49cdaf0--- /dev/null+++ b/app/jobs/delete_scheduled_tenants_job.go@@ -0,0 +1,131 @@+package jobs++import (+ "context"++ "github.com/getfider/fider/app"+ "github.com/getfider/fider/app/models/cmd"+ "github.com/getfider/fider/app/models/dto"+ "github.com/getfider/fider/app/models/entity"+ "github.com/getfider/fider/app/models/query"+ "github.com/getfider/fider/app/pkg/bus"+ "github.com/getfider/fider/app/pkg/env"+ "github.com/getfider/fider/app/pkg/errors"+ "github.com/getfider/fider/app/pkg/log"+ "github.com/getfider/fider/app/pkg/web"++ stripe "github.com/stripe/stripe-go/v83"+ stripesub "github.com/stripe/stripe-go/v83/subscription"+)++// DeleteScheduledTenantsJobHandler permanently deletes tenants whose grace period has+// elapsed. It processes at most one tenant per run so each deletion commits independently+// and a failure on one tenant cannot corrupt another (deletes also trigger non-transactional+// side effects — Stripe cancellation and blob storage wipes).+type DeleteScheduledTenantsJobHandler struct {+}++func (j DeleteScheduledTenantsJobHandler) Schedule() string {+ return "0 */5 * * * *" // every 5 minutes+}++func (j DeleteScheduledTenantsJobHandler) Run(ctx Context) error {+ pending := &query.GetTenantsPendingDeletion{}+ if err := bus.Dispatch(ctx, pending); err != nil {+ return errors.Wrap(err, "failed to fetch tenants pending deletion")+ }++ if len(pending.Result) == 0 {+ return nil+ }++ tenant := pending.Result[0]+ tenantCtx := context.WithValue(ctx.Context, app.TenantCtxKey, tenant)++ log.Warnf(ctx, "Deleting tenant @{TenantID} (@{Subdomain}) — grace period elapsed", dto.Props{+ "TenantID": tenant.ID,+ "Subdomain": tenant.Subdomain,+ })++ // Capture the owner before deletion so we can send the completion email afterwards.+ owner := &query.GetTenantOwner{TenantID: tenant.ID}+ if err := bus.Dispatch(ctx, owner); err != nil {+ log.Warnf(ctx, "Could not resolve owner for tenant @{TenantID}; no completion email will be sent", dto.Props{+ "TenantID": tenant.ID,+ })+ owner.Result = nil+ }++ // Stripe cancellation is a non-transactional side effect: do it first and bail (retry next+ // run) on a real error, but treat an already-missing subscription as success.+ if err := cancelStripeSubscription(tenantCtx); err != nil {+ return errors.Wrap(err, "failed to cancel stripe subscription for tenant '%d'", tenant.ID)+ }++ // Wipe blob storage (S3/fs files live under a tenant prefix; sql-backed blobs also fall to+ // the DB delete below, but listing+deleting here is harmless and correct for all backends).+ if err := wipeTenantBlobs(tenantCtx); err != nil {+ return errors.Wrap(err, "failed to wipe blobs for tenant '%d'", tenant.ID)+ }++ if err := bus.Dispatch(ctx, &cmd.DeleteTenant{TenantID: tenant.ID}); err != nil {+ return errors.Wrap(err, "failed to delete tenant '%d'", tenant.ID)+ }++ sendCompletionEmail(ctx, tenant, owner.Result)+ return nil+}++func cancelStripeSubscription(tenantCtx context.Context) error {+ billing := &query.GetStripeBillingState{}+ if err := bus.Dispatch(tenantCtx, billing); err != nil {+ return errors.Wrap(err, "failed to read stripe billing state")+ }++ subID := billing.Result.SubscriptionID+ if subID == "" {+ return nil+ }++ stripe.Key = env.Config.Stripe.SecretKey+ if _, err := stripesub.Cancel(subID, nil); err != nil {+ if stripeErr, ok := err.(*stripe.Error); ok && stripeErr.Code == stripe.ErrorCodeResourceMissing {+ // Subscription already cancelled or never existed — nothing to do.+ return nil+ }+ return err+ }+ return nil+}++func wipeTenantBlobs(tenantCtx context.Context) error {+ list := &query.ListBlobs{}+ if err := bus.Dispatch(tenantCtx, list); err != nil {+ return errors.Wrap(err, "failed to list blobs")+ }++ for _, key := range list.Result {+ if err := bus.Dispatch(tenantCtx, &cmd.DeleteBlob{Key: key}); err != nil {+ return errors.Wrap(err, "failed to delete blob '%s'", key)+ }+ }+ return nil+}++func sendCompletionEmail(ctx Context, tenant *entity.Tenant, owner *entity.User) {+ if owner == nil || owner.Email == "" {+ return+ }++ to := dto.NewRecipient(owner.Name, owner.Email, dto.Props{})+ bus.Publish(ctx, &cmd.SendMail{+ From: dto.Recipient{Name: "Fider"},+ To: []dto.Recipient{to},+ TemplateName: "delete_account_completed",+ Props: dto.Props{+ "tenantName": tenant.Name,+ "subdomain": tenant.Subdomain,+ "logo": web.LogoURL(ctx),+ },+ })+}diff --git a/app/models/cmd/tenant.go b/app/models/cmd/tenant.goindex 0b18f211f..a0881f42f 100644--- a/app/models/cmd/tenant.go+++ b/app/models/cmd/tenant.go@@ -75,3 +75,23 @@ type InvalidateVerificationsByEmail struct {type InvalidatePreviousSignUpKeys struct {}++// ScheduleTenantDeletion records the account owner's request to delete the whole site.+// The tenant stays active during the grace window; a background job performs the hard+// delete once ScheduledAt passes. CancelKey authorises the email cancel link.+type ScheduleTenantDeletion struct {+ TenantID int+ RequestedByUserID int+ CancelKey string+ ScheduledAt time.Time+}++// CancelTenantDeletion clears a pending deletion schedule, leaving the tenant untouched.+type CancelTenantDeletion struct {+ TenantID int+}++// DeleteTenant permanently removes a tenant and all of its data. Irreversible.+type DeleteTenant struct {+ TenantID int+}diff --git a/app/models/entity/tenant.go b/app/models/entity/tenant.goindex e1d936b12..49a0eba53 100644--- a/app/models/entity/tenant.go+++ b/app/models/entity/tenant.go@@ -1,6 +1,8 @@package entityimport (+ "time"+"github.com/getfider/fider/app/models/enum")@@ -24,6 +26,10 @@ type Tenant struct {PreventIndexing bool `json:"preventIndexing"`IsModerationEnabled bool `json:"isModerationEnabled"`IsPro bool `json:"isPro"`+ // ScheduledDeletionAt is set when the account owner has requested deletion of the whole+ // site. The tenant stays active during the grace window; a background job performs the+ // hard delete once this time passes. Not exposed to clients.+ ScheduledDeletionAt *time.Time `json:"-"`}func (t *Tenant) IsDisabled() bool {diff --git a/app/models/query/tenant.go b/app/models/query/tenant.goindex f8e9daaf4..536dcb827 100644--- a/app/models/query/tenant.go+++ b/app/models/query/tenant.go@@ -61,3 +61,27 @@ type GetPendingSignUpVerification struct {// OutputResult *entity.EmailVerification}++// GetTenantsPendingDeletion returns tenants whose scheduled_deletion_at has passed,+// ordered oldest-first. Consumed by the deletion cron job.+type GetTenantsPendingDeletion struct {+ // Output+ Result []*entity.Tenant+}++// GetTenantByCancelKey looks up the tenant holding the given deletion cancel key.+type GetTenantByCancelKey struct {+ Key string++ // Output+ Result *entity.Tenant+}++// GetTenantOwner returns the account owner: the active Administrator with the lowest+// users.id (the user that created the tenant at signup).+type GetTenantOwner struct {+ TenantID int++ // Output+ Result *entity.User+}diff --git a/app/services/sqlstore/dbEntities/tenant.go b/app/services/sqlstore/dbEntities/tenant.goindex bdd710e90..37200b67c 100644--- a/app/services/sqlstore/dbEntities/tenant.go+++ b/app/services/sqlstore/dbEntities/tenant.go@@ -3,6 +3,7 @@ package dbEntitiesimport ("github.com/getfider/fider/app/models/entity""github.com/getfider/fider/app/models/enum"+ "github.com/getfider/fider/app/pkg/dbx""github.com/getfider/fider/app/pkg/env")@@ -24,8 +25,9 @@ type Tenant struct {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"`+ IsPro bool `db:"is_pro"`+ HasPaddleSubscription bool `db:"has_paddle_subscription"`+ ScheduledDeletionAt dbx.NullTime `db:"scheduled_deletion_at"`}func (t *Tenant) ToModel() *entity.Tenant {@@ -61,5 +63,9 @@ func (t *Tenant) ToModel() *entity.Tenant {IsPro: isPro,}+ if t.ScheduledDeletionAt.Valid {+ tenant.ScheduledDeletionAt = &t.ScheduledDeletionAt.Time+ }+return tenant}diff --git a/app/services/sqlstore/postgres/postgres.go b/app/services/sqlstore/postgres/postgres.goindex fc8026e39..580b14c7a 100644--- a/app/services/sqlstore/postgres/postgres.go+++ b/app/services/sqlstore/postgres/postgres.go@@ -115,6 +115,12 @@ func (s Service) Init() {bus.AddHandler(updateTenantPrivacySettings)bus.AddHandler(updateTenantEmailAuthAllowedSettings)bus.AddHandler(updateTenantAdvancedSettings)+ bus.AddHandler(scheduleTenantDeletion)+ bus.AddHandler(cancelTenantDeletion)+ bus.AddHandler(deleteTenant)+ bus.AddHandler(getTenantsPendingDeletion)+ bus.AddHandler(getTenantByCancelKey)+ bus.AddHandler(getTenantOwner)bus.AddHandler(getVerificationByKey)bus.AddHandler(getVerificationByEmailAndCode)diff --git a/app/services/sqlstore/postgres/tenant.go b/app/services/sqlstore/postgres/tenant.goindex 0051275b3..269950d91 100644--- a/app/services/sqlstore/postgres/tenant.go+++ b/app/services/sqlstore/postgres/tenant.go@@ -259,7 +259,7 @@ func getFirstTenant(ctx context.Context, q *query.GetFirstTenant) error {tenant := dbEntities.Tenant{}err := trx.Get(&tenant, `- SELECT t.id, t.name, t.subdomain, t.cname, t.invitation, t.locale, t.welcome_message, t.welcome_header, t.status, t.is_private, t.logo_bkey, t.custom_css, t.allowed_schemes, t.is_email_auth_allowed, t.is_feed_enabled, t.is_moderation_enabled, t.prevent_indexing, t.is_pro,+ SELECT t.id, t.name, t.subdomain, t.cname, t.invitation, t.locale, t.welcome_message, t.welcome_header, t.status, t.is_private, t.logo_bkey, t.custom_css, t.allowed_schemes, t.is_email_auth_allowed, t.is_feed_enabled, t.is_moderation_enabled, t.prevent_indexing, t.is_pro, t.scheduled_deletion_at,(b.paddle_subscription_id IS NOT NULL AND b.stripe_subscription_id IS NULL) AS has_paddle_subscriptionFROM tenants tLEFT JOIN tenants_billing b ON b.tenant_id = t.id@@ -279,7 +279,7 @@ func getTenantByDomain(ctx context.Context, q *query.GetTenantByDomain) error {tenant := dbEntities.Tenant{}err := trx.Get(&tenant, `- SELECT t.id, t.name, t.subdomain, t.cname, t.invitation, t.locale, t.welcome_message, t.welcome_header, t.status, t.is_private, t.logo_bkey, t.custom_css, t.allowed_schemes, t.is_email_auth_allowed, t.is_feed_enabled, t.is_moderation_enabled, t.prevent_indexing, t.is_pro,+ SELECT t.id, t.name, t.subdomain, t.cname, t.invitation, t.locale, t.welcome_message, t.welcome_header, t.status, t.is_private, t.logo_bkey, t.custom_css, t.allowed_schemes, t.is_email_auth_allowed, t.is_feed_enabled, t.is_moderation_enabled, t.prevent_indexing, t.is_pro, t.scheduled_deletion_at,(b.paddle_subscription_id IS NOT NULL AND b.stripe_subscription_id IS NULL) AS has_paddle_subscriptionFROM tenants tLEFT JOIN tenants_billing b ON b.tenant_id = t.iddiff --git a/app/services/sqlstore/postgres/tenant_deletion.go b/app/services/sqlstore/postgres/tenant_deletion.gonew file mode 100644index 000000000..1b9457bfe--- /dev/null+++ b/app/services/sqlstore/postgres/tenant_deletion.go@@ -0,0 +1,141 @@+package postgres++import (+ "context"+ "fmt"++ "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/dbx"+ "github.com/getfider/fider/app/pkg/errors"+ "github.com/getfider/fider/app/services/sqlstore/dbEntities"+)++func scheduleTenantDeletion(ctx context.Context, c *cmd.ScheduleTenantDeletion) error {+ return using(ctx, func(trx *dbx.Trx, _ *entity.Tenant, _ *entity.User) error {+ _, err := trx.Execute(`+ UPDATE tenants+ SET scheduled_deletion_at = $2, deletion_requested_by = $3, deletion_cancel_key = $4+ WHERE id = $1+ `, c.TenantID, c.ScheduledAt, c.RequestedByUserID, c.CancelKey)+ if err != nil {+ return errors.Wrap(err, "failed to schedule tenant deletion")+ }+ return nil+ })+}++func cancelTenantDeletion(ctx context.Context, c *cmd.CancelTenantDeletion) error {+ return using(ctx, func(trx *dbx.Trx, _ *entity.Tenant, _ *entity.User) error {+ _, err := trx.Execute(`+ UPDATE tenants+ SET scheduled_deletion_at = NULL, deletion_requested_by = NULL, deletion_cancel_key = NULL+ WHERE id = $1+ `, c.TenantID)+ if err != nil {+ return errors.Wrap(err, "failed to cancel tenant deletion")+ }+ return nil+ })+}++func getTenantsPendingDeletion(ctx context.Context, q *query.GetTenantsPendingDeletion) error {+ return using(ctx, func(trx *dbx.Trx, _ *entity.Tenant, _ *entity.User) error {+ q.Result = []*entity.Tenant{}+ var tenants []*dbEntities.Tenant+ err := trx.Select(&tenants, `+ SELECT id, name, subdomain, scheduled_deletion_at+ FROM tenants+ WHERE scheduled_deletion_at IS NOT NULL AND scheduled_deletion_at <= now()+ ORDER BY scheduled_deletion_at ASC+ `)+ if err != nil {+ return errors.Wrap(err, "failed to get tenants pending deletion")+ }+ for _, t := range tenants {+ q.Result = append(q.Result, t.ToModel())+ }+ return nil+ })+}++func getTenantByCancelKey(ctx context.Context, q *query.GetTenantByCancelKey) error {+ return using(ctx, func(trx *dbx.Trx, _ *entity.Tenant, _ *entity.User) error {+ tenant := dbEntities.Tenant{}+ err := trx.Get(&tenant, `+ SELECT id, name, subdomain, scheduled_deletion_at+ FROM tenants+ WHERE deletion_cancel_key = $1+ `, q.Key)+ if err != nil {+ return errors.Wrap(err, "failed to get tenant by cancel key")+ }+ q.Result = tenant.ToModel()+ return nil+ })+}++func getTenantOwner(ctx context.Context, q *query.GetTenantOwner) error {+ return using(ctx, func(trx *dbx.Trx, _ *entity.Tenant, _ *entity.User) error {+ owner, err := queryUser(ctx, trx, "tenant_id = $1 AND role = $2 AND status = $3 ORDER BY id ASC LIMIT 1",+ q.TenantID, enum.RoleAdministrator, enum.UserActive)+ if err != nil {+ return errors.Wrap(err, "failed to get owner of tenant '%d'", q.TenantID)+ }+ q.Result = owner+ return nil+ })+}++// tenantScopedTables lists every table holding tenant-owned rows, ordered children → parents+// so deletes respect the composite (id, tenant_id) foreign keys (all NO ACTION, no CASCADE).+// `reactions` is handled separately first because it has no tenant_id column.+var tenantScopedTables = []string{+ "attachments",+ "mention_notifications",+ "notifications",+ "post_subscribers",+ "post_votes",+ "post_tags",+ "comments",+ "posts",+ "tags",+ "email_verifications",+ "user_providers",+ "user_settings",+ "webhooks",+ "events",+ "blobs",+ "oauth_providers",+ "tenant_providers",+ "users",+ "tenants_billing",+}++func deleteTenant(ctx context.Context, c *cmd.DeleteTenant) error {+ return using(ctx, func(trx *dbx.Trx, _ *entity.Tenant, _ *entity.User) error {+ // reactions has no tenant_id; scope via the tenant's comments before comments/users go.+ if _, err := trx.Execute(+ "DELETE FROM reactions WHERE comment_id IN (SELECT id FROM comments WHERE tenant_id = $1)",+ c.TenantID,+ ); err != nil {+ return errors.Wrap(err, "failed to delete reactions for tenant '%d'", c.TenantID)+ }++ for _, table := range tenantScopedTables {+ if _, err := trx.Execute(+ fmt.Sprintf("DELETE FROM %s WHERE tenant_id = $1", table),+ c.TenantID,+ ); err != nil {+ return errors.Wrap(err, "failed to delete %s for tenant '%d'", table, c.TenantID)+ }+ }++ if _, err := trx.Execute("DELETE FROM tenants WHERE id = $1", c.TenantID); err != nil {+ return errors.Wrap(err, "failed to delete tenant '%d'", c.TenantID)+ }+ return nil+ })+}diff --git a/app/services/sqlstore/postgres/tenant_deletion_test.go b/app/services/sqlstore/postgres/tenant_deletion_test.gonew file mode 100644index 000000000..c1f9251d6--- /dev/null+++ b/app/services/sqlstore/postgres/tenant_deletion_test.go@@ -0,0 +1,146 @@+package postgres_test++import (+ "context"+ "testing"+ "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/errors"++ . "github.com/getfider/fider/app/pkg/assert"+)++func countTenantRows(table string, tenantID int) int {+ var count int+ err := trx.Scalar(&count, "SELECT COUNT(*) FROM "+table+" WHERE tenant_id = $1", tenantID)+ Expect(err).IsNil()+ return count+}++// seedTenantContent creates a post, comment, reaction, vote and tag so deletion exercises+// the full FK-ordered teardown (including the tenant-less reactions table).+func seedTenantContent(tenantCtx, userCtx context.Context) {+ post := &cmd.AddNewPost{Title: "A feature request to delete", Description: "please"}+ Expect(bus.Dispatch(userCtx, post)).IsNil()++ comment := &cmd.AddNewComment{Post: post.Result, Content: "great idea"}+ Expect(bus.Dispatch(userCtx, comment)).IsNil()++ user, _ := userCtx.Value(app.UserCtxKey).(*entity.User)+ Expect(bus.Dispatch(userCtx, &cmd.ToggleCommentReaction{+ Comment: &entity.Comment{ID: comment.Result.ID}, Emoji: "👍", User: user,+ })).IsNil()+ Expect(bus.Dispatch(userCtx, &cmd.AddVote{Post: post.Result, User: user})).IsNil()++ tag := &cmd.AddNewTag{Name: "doomed", Color: "ffffff", IsPublic: true}+ Expect(bus.Dispatch(tenantCtx, tag)).IsNil()+ Expect(bus.Dispatch(userCtx, &cmd.AssignTag{Tag: tag.Result, Post: post.Result})).IsNil()+}++func TestTenantDeletion_DeletesEverythingForTenantOnly(t *testing.T) {+ ctx := SetupDatabaseTest(t)+ defer TeardownDatabaseTest()++ seedTenantContent(demoTenantCtx, jonSnowCtx)+ seedTenantContent(avengersTenantCtx, tonyStarkCtx)++ Expect(countTenantRows("users", demoTenant.ID) > 0).IsTrue()+ Expect(countTenantRows("posts", demoTenant.ID) > 0).IsTrue()+ Expect(countTenantRows("comments", demoTenant.ID) > 0).IsTrue()++ avengersUsersBefore := countTenantRows("users", avengersTenant.ID)+ avengersPostsBefore := countTenantRows("posts", avengersTenant.ID)+ avengersCommentsBefore := countTenantRows("comments", avengersTenant.ID)+ Expect(avengersPostsBefore > 0).IsTrue()++ err := bus.Dispatch(ctx, &cmd.DeleteTenant{TenantID: demoTenant.ID})+ Expect(err).IsNil()++ // Every tenant-scoped table is empty for the deleted tenant.+ for _, table := range []string{+ "users", "posts", "comments", "post_votes", "post_tags", "tags",+ "post_subscribers", "notifications", "attachments", "user_settings",+ "user_providers", "email_verifications", "events", "blobs", "webhooks",+ "oauth_providers", "tenant_providers", "tenants_billing",+ } {+ Expect(countTenantRows(table, demoTenant.ID)).Equals(0)+ }++ // The tenant row itself is gone.+ getDemo := &query.GetTenantByDomain{Domain: "demo"}+ err = bus.Dispatch(ctx, getDemo)+ Expect(errors.Cause(err)).IsNotNil()++ // Another tenant is left completely intact.+ Expect(countTenantRows("users", avengersTenant.ID)).Equals(avengersUsersBefore)+ Expect(countTenantRows("posts", avengersTenant.ID)).Equals(avengersPostsBefore)+ Expect(countTenantRows("comments", avengersTenant.ID)).Equals(avengersCommentsBefore)+}++func TestTenantDeletion_ScheduleAndCancel(t *testing.T) {+ ctx := SetupDatabaseTest(t)+ defer TeardownDatabaseTest()++ scheduledAt := time.Now().Add(time.Hour)+ err := bus.Dispatch(ctx, &cmd.ScheduleTenantDeletion{+ TenantID: demoTenant.ID,+ RequestedByUserID: jonSnow.ID,+ CancelKey: "test-cancel-key-123",+ ScheduledAt: scheduledAt,+ })+ Expect(err).IsNil()++ // Status is untouched during the grace window.+ getDemo := &query.GetTenantByDomain{Domain: "demo"}+ Expect(bus.Dispatch(ctx, getDemo)).IsNil()+ Expect(getDemo.Result.Status).Equals(enum.TenantActive)+ Expect(getDemo.Result.ScheduledDeletionAt).IsNotNil()++ // The cancel key resolves back to the tenant.+ byKey := &query.GetTenantByCancelKey{Key: "test-cancel-key-123"}+ Expect(bus.Dispatch(ctx, byKey)).IsNil()+ Expect(byKey.Result.ID).Equals(demoTenant.ID)++ // Cancelling clears the schedule.+ Expect(bus.Dispatch(ctx, &cmd.CancelTenantDeletion{TenantID: demoTenant.ID})).IsNil()+ getDemo = &query.GetTenantByDomain{Domain: "demo"}+ Expect(bus.Dispatch(ctx, getDemo)).IsNil()+ Expect(getDemo.Result.ScheduledDeletionAt).IsNil()+}++func TestTenantDeletion_PendingDeletionAndOwner(t *testing.T) {+ ctx := SetupDatabaseTest(t)+ defer TeardownDatabaseTest()++ // Owner is the lowest-id active administrator (the seed creator, Jon Snow).+ owner := &query.GetTenantOwner{TenantID: demoTenant.ID}+ Expect(bus.Dispatch(ctx, owner)).IsNil()+ Expect(owner.Result.ID).Equals(jonSnow.ID)+ Expect(owner.Result.Role).Equals(enum.RoleAdministrator)++ // A schedule in the past is returned; one in the future is not.+ Expect(bus.Dispatch(ctx, &cmd.ScheduleTenantDeletion{+ TenantID: demoTenant.ID, RequestedByUserID: jonSnow.ID,+ CancelKey: "past-key", ScheduledAt: time.Now().Add(-time.Minute),+ })).IsNil()+ Expect(bus.Dispatch(ctx, &cmd.ScheduleTenantDeletion{+ TenantID: avengersTenant.ID, RequestedByUserID: tonyStark.ID,+ CancelKey: "future-key", ScheduledAt: time.Now().Add(time.Hour),+ })).IsNil()++ pending := &query.GetTenantsPendingDeletion{}+ Expect(bus.Dispatch(ctx, pending)).IsNil()++ ids := map[int]bool{}+ for _, tn := range pending.Result {+ ids[tn.ID] = true+ }+ Expect(ids[demoTenant.ID]).IsTrue()+ Expect(ids[avengersTenant.ID]).IsFalse()+}diff --git a/app/tasks/delete_account.go b/app/tasks/delete_account.gonew file mode 100644index 000000000..7c7c70d02--- /dev/null+++ b/app/tasks/delete_account.go@@ -0,0 +1,35 @@+package tasks++import (+ "time"++ "github.com/getfider/fider/app/models/cmd"+ "github.com/getfider/fider/app/models/dto"+ "github.com/getfider/fider/app/models/entity"+ "github.com/getfider/fider/app/pkg/bus"+ "github.com/getfider/fider/app/pkg/web"+ "github.com/getfider/fider/app/pkg/worker"+)++// SendDeleteAccountScheduledEmail notifies the account owner that the whole site is scheduled+// for deletion and gives them a link to cancel during the grace window.+func SendDeleteAccountScheduledEmail(owner *entity.User, tenantName string, scheduledAt time.Time, baseURL, cancelKey string) worker.Task {+ return describe("Send delete account scheduled email", func(c *worker.Context) error {+ to := dto.NewRecipient(owner.Name, owner.Email, dto.Props{+ "tenantName": tenantName,+ "scheduledAt": scheduledAt.UTC().Format("2 Jan 2006 15:04 MST"),+ "cancelLink": linkWithText("Cancel the scheduled deletion", baseURL, "/admin/danger-zone/cancel?k=%s", cancelKey),+ })++ bus.Publish(c, &cmd.SendMail{+ From: dto.Recipient{Name: "Fider"},+ To: []dto.Recipient{to},+ TemplateName: "delete_account_requested",+ Props: dto.Props{+ "logo": web.LogoURL(c),+ },+ })++ return nil+ })+}diff --git a/migrations/202606101200_add_tenant_deletion_schedule.sql b/migrations/202606101200_add_tenant_deletion_schedule.sqlnew file mode 100644index 000000000..ae3405132--- /dev/null+++ b/migrations/202606101200_add_tenant_deletion_schedule.sql@@ -0,0 +1,3 @@+ALTER TABLE tenants ADD COLUMN scheduled_deletion_at TIMESTAMPTZ NULL;+ALTER TABLE tenants ADD COLUMN deletion_requested_by INT NULL;+ALTER TABLE tenants ADD COLUMN deletion_cancel_key VARCHAR(64) NULL;diff --git a/public/pages/Administration/components/SideMenu.tsx b/public/pages/Administration/components/SideMenu.tsxindex acde6b97c..e83e994e2 100644--- a/public/pages/Administration/components/SideMenu.tsx+++ b/public/pages/Administration/components/SideMenu.tsx@@ -52,6 +52,9 @@ export const SideMenu = (props: SiteMenuProps) => {{fider.settings.isBillingEnabled && <SideMenuItem name="billing" title="Billing" href="/admin/billing" isActive={activeItem === "billing"} />}<SideMenuItem name="webhooks" title="Webhooks" href="/admin/webhooks" isActive={activeItem === "webhooks"} /><SideMenuItem name="export" title="Export" href="/admin/export" isActive={activeItem === "export"} />+ {!fider.isSingleHostMode() && (+ <SideMenuItem name="danger-zone" title="Danger Zone" href="/admin/danger-zone" isActive={activeItem === "danger-zone"} />+ )}</>)}</VStack>diff --git a/public/pages/Administration/pages/DangerZone.page.tsx b/public/pages/Administration/pages/DangerZone.page.tsxnew file mode 100644index 000000000..0b93af792--- /dev/null+++ b/public/pages/Administration/pages/DangerZone.page.tsx@@ -0,0 +1,138 @@+import React from "react"++import { Button, Modal, Input, Message } from "@fider/components"+import { AdminBasePage } from "@fider/pages/Administration/components/AdminBasePage"+import { actions, notify, Fider } from "@fider/services"+import { Icon } from "@fider/components"+import IconExclamation from "@fider/assets/images/heroicons-exclamation.svg"++interface DangerZonePageProps {+ isOwner: boolean+ scheduledDeletionAt?: string | null+}++interface DangerZonePageState {+ showModal: boolean+ confirmation: string+ scheduledDeletionAt?: string | null+}++export default class DangerZonePage extends AdminBasePage<DangerZonePageProps, DangerZonePageState> {+ public id = "p-admin-danger"+ public name = "danger-zone"+ public title = "Danger Zone"+ public subtitle = "Permanently delete this site"++ constructor(props: DangerZonePageProps) {+ super(props)+ this.state = {+ showModal: false,+ confirmation: "",+ scheduledDeletionAt: props.scheduledDeletionAt,+ }+ }++ private openModal = () => this.setState({ showModal: true })+ private closeModal = () => this.setState({ showModal: false, confirmation: "" })++ private confirmDelete = async () => {+ const response = await actions.requestTenantDeletion(this.state.confirmation)+ if (response.ok) {+ this.setState({ showModal: false, confirmation: "", scheduledDeletionAt: response.data.scheduledDeletionAt })+ notify.success("Your site is scheduled for deletion. We've emailed you a link to cancel — you have 1 hour.")+ } else {+ notify.error("Failed to schedule deletion. Please try again later.")+ }+ }++ private cancelDeletion = async () => {+ const response = await actions.cancelTenantDeletion()+ if (response.ok) {+ this.setState({ scheduledDeletionAt: null })+ notify.success("The scheduled deletion has been cancelled.")+ } else {+ notify.error("Failed to cancel the scheduled deletion. Please try again later.")+ }+ }++ private renderScheduled() {+ const when = this.state.scheduledDeletionAt ? new Date(this.state.scheduledDeletionAt).toLocaleString() : ""+ return (+ <Message type="error">+ <h4 className="text-title mb-1">This site is scheduled for deletion</h4>+ <p className="mb-2">+ Everything for this site will be permanently deleted at <strong>{when}</strong>. This cannot be undone once it runs.+ </p>+ {this.props.isOwner ? (+ <Button variant="danger" size="small" onClick={this.cancelDeletion}>+ Cancel deletion+ </Button>+ ) : (+ <p className="text-muted">Only the account owner can cancel the deletion.</p>+ )}+ </Message>+ )+ }++ private renderDelete() {+ const subdomain = Fider.session.tenant.subdomain++ if (!this.props.isOwner) {+ return (+ <Message type="warning">+ <h4 className="text-title mb-1">Delete this fider board</h4>+ <p className="text-muted">+ Only the account owner (the person who created this fider board) can delete it. Please contact them if this site needs to be deleted.+ </p>+ </Message>+ )+ }++ return (+ <div>+ <Modal.Window isOpen={this.state.showModal} center={false} onClose={this.closeModal}>+ <Modal.Header>Are you sure you want to delete everything?</Modal.Header>+ <Modal.Content>+ <p>+ To confirm, This will <strong>permanently delete</strong> this fider board and everything in it — all users, posts, comments and votes — and+ cancel any active subscription.+ </p>+ <h4 className="text-title mb-2">How it works</h4>+ <p>+ We'll put the delete request in a queue and send an email to confirm what's happening. After an hour, the delete will be processed and everything+ will be deleted. No going back. No restore from backup. It's all gone.+ </p>+ <p className="mt-2">+ To confirm, type the subdomain of this site (<strong>{subdomain}</strong>) below:+ </p>+ <Input field="confirmation" value={this.state.confirmation} placeholder={subdomain} onChange={(confirmation) => this.setState({ confirmation })} />+ </Modal.Content>+ <Modal.Footer>+ <Button variant="danger" disabled={this.state.confirmation !== subdomain} onClick={this.confirmDelete}>+ Yes, delete this fider board.+ </Button>+ <Button variant="tertiary" onClick={this.closeModal}>+ Cancel+ </Button>+ </Modal.Footer>+ </Modal.Window>++ <h4 className="text-title mb-1 flex items-center gap-1 text-red-700">+ <Icon sprite={IconExclamation} height="24" />+ Delete this fider board+ </h4>+ <p className="text-muted text-red">+ Careful! This will permanently delete this fider board and <strong>everything</strong> in it — all users, posts, comments and votes — and cancels any+ active subscription to fider Pro.+ </p>+ <Button variant="danger" size="small" onClick={this.openModal}>+ I understand, delete this fider board+ </Button>+ </div>+ )+ }++ public content() {+ return this.state.scheduledDeletionAt ? this.renderScheduled() : this.renderDelete()+ }+}diff --git a/public/services/actions/tenant.ts b/public/services/actions/tenant.tsindex 2ea49da70..355c9c6c0 100644--- a/public/services/actions/tenant.ts+++ b/public/services/actions/tenant.ts@@ -135,3 +135,15 @@ export const setSystemProviderStatus = async (provider: string, isEnabled: booleexport const resendSignUpEmail = async (): Promise<Result> => {return await http.post("/_api/signup/resend", {})}++export interface RequestTenantDeletionResponse {+ scheduledDeletionAt: string+}++export const requestTenantDeletion = async (subdomain: string): Promise<Result<RequestTenantDeletionResponse>> => {+ return await http.delete<RequestTenantDeletionResponse>("/_api/admin/tenant", { subdomain })+}++export const cancelTenantDeletion = async (): Promise<Result> => {+ return await http.post("/_api/admin/tenant/cancel-deletion")+}diff --git a/views/email/delete_account_completed.html b/views/email/delete_account_completed.htmlnew file mode 100644index 000000000..908a00792--- /dev/null+++ b/views/email/delete_account_completed.html@@ -0,0 +1,10 @@+{{define "subject"}}{{ translate "email.delete_account_completed.subject" (dict "tenantName" .tenantName) }}{{end}}++{{define "body"}}+<tr>+ <td style="padding:20px 30px 30px 30px;">+ <h2 style="color:#1c262d;margin:0 0 15px 0;padding:0;">{{ "email.greetings" | translate }}</h2>+ <p style="color:#1c262d;margin:0 0 10px 0;">{{ translate "email.delete_account_completed.text" (dict "tenantName" (.tenantName | stripHtml) "subdomain" .subdomain) | html }}</p>+ </td>+</tr>+{{end}}diff --git a/views/email/delete_account_requested.html b/views/email/delete_account_requested.htmlnew file mode 100644index 000000000..560581a44--- /dev/null+++ b/views/email/delete_account_requested.html@@ -0,0 +1,13 @@+{{define "subject"}}{{ translate "email.delete_account_requested.subject" (dict "tenantName" .tenantName) }}{{end}}++{{define "body"}}+<tr>+ <td style="padding:20px 30px 30px 30px;">+ <h2 style="color:#1c262d;margin:0 0 15px 0;padding:0;">{{ "email.greetings" | translate }}</h2>+ <p style="color:#1c262d;margin:0 0 10px 0;">{{ translate "email.delete_account_requested.text" (dict "tenantName" (.tenantName | stripHtml)) | html }}</p>+ <p style="color:#1c262d;margin:0 0 20px 0;">{{ translate "email.delete_account_requested.scheduled" (dict "scheduledAt" .scheduledAt) | html }}</p>+ <p style="color:#1c262d;margin:0 0 10px 0;">{{ "email.delete_account_requested.cancel" | translate }}</p>+ <p style="color:#1c262d;margin:0 0 20px 0;">{{ .cancelLink | html }}</p>+ </td>+</tr>+{{end}}