Constrain PostHog consent to one normal category per banner

Add a partial unique index ensuring only one category per banner can
have posthog_consent enabled. Default it to the analytics category on
banner creation, clear the previous mapping before setting a new one,
and restrict the toggle to NORMAL categories in both the service layer
and the console UI.

Signed-off-by: Émile Ré <emile@getprobo.com>
This commit is contained in:
Émile Ré
2026-04-24 16:35:39 +04:00
parent 7f1dffad80
commit 9fbb716b00
9 changed files with 190 additions and 27 deletions

View File

@@ -490,6 +490,7 @@ export function CategorySection({ categoryKey, onDelete }: CategorySectionProps)
name={category.name} name={category.name}
slug={category.slug} slug={category.slug}
description={category.description} description={category.description}
kind={category.kind}
gcmConsentTypes={[...category.gcmConsentTypes]} gcmConsentTypes={[...category.gcmConsentTypes]}
posthogConsent={category.posthogConsent} posthogConsent={category.posthogConsent}
isUpdating={isUpdating} isUpdating={isUpdating}

View File

@@ -30,6 +30,7 @@ interface EditCategoryFormProps {
name: string; name: string;
slug: string; slug: string;
description: string; description: string;
kind: string;
gcmConsentTypes: string[]; gcmConsentTypes: string[];
posthogConsent: boolean; posthogConsent: boolean;
isUpdating: boolean; isUpdating: boolean;
@@ -41,6 +42,7 @@ export function EditCategoryForm({
name, name,
slug, slug,
description, description,
kind,
gcmConsentTypes, gcmConsentTypes,
posthogConsent, posthogConsent,
isUpdating, isUpdating,
@@ -105,23 +107,25 @@ export function EditCategoryForm({
))} ))}
</div> </div>
</div> </div>
<div> {kind === "NORMAL" && (
<label className="text-sm font-medium"> <div>
{__("PostHog")} <label className="text-sm font-medium">
</label> {__("PostHog")}
<p className="text-xs text-muted-foreground mb-2"> </label>
{__("Control PostHog tracking consent based on this category.")} <p className="text-xs text-muted-foreground mb-2">
</p> {__("Control PostHog tracking consent based on this category.")}
<label className="flex items-center gap-1.5 text-xs cursor-pointer"> </p>
<input <label className="flex items-center gap-1.5 text-xs cursor-pointer">
type="checkbox" <input
checked={editPosthogConsent} type="checkbox"
onChange={() => setEditPosthogConsent(prev => !prev)} checked={editPosthogConsent}
className="rounded" onChange={() => setEditPosthogConsent(prev => !prev)}
/> className="rounded"
<span>{__("Opt in/out of PostHog tracking")}</span> />
</label> <span>{__("Opt in/out of PostHog tracking")}</span>
</div> </label>
</div>
)}
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Button <Button
onClick={() => { onClick={() => {

View File

@@ -25,12 +25,53 @@ var defaultCategories = []struct {
Kind coredata.CookieCategoryKind Kind coredata.CookieCategoryKind
Rank int Rank int
GCMConsentTypes []string GCMConsentTypes []string
PostHogConsent bool
}{ }{
{"Necessary", "necessary", "Essential cookies required for the website to function properly.", coredata.CookieCategoryKindNecessary, 0, []string{"security_storage"}}, {
{"Analytics", "analytics", "Cookies that help understand how visitors interact with the website.", coredata.CookieCategoryKindNormal, 1, []string{"analytics_storage"}}, Name: "Necessary",
{"Advertising", "advertising", "Cookies used to deliver relevant advertisements and track campaigns.", coredata.CookieCategoryKindNormal, 2, []string{"ad_storage", "ad_user_data", "ad_personalization"}}, Slug: "necessary",
{"Functional", "functional", "Cookies that enable enhanced functionality and personalization.", coredata.CookieCategoryKindNormal, 3, []string{"functionality_storage", "personalization_storage"}}, Description: "Essential cookies required for the website to function properly.",
{"Uncategorised", "uncategorised", "Cookies that have not been assigned to a category yet.", coredata.CookieCategoryKindUncategorised, 4, nil}, Kind: coredata.CookieCategoryKindNecessary,
Rank: 0,
GCMConsentTypes: []string{"security_storage"},
PostHogConsent: false,
},
{
Name: "Analytics",
Slug: "analytics",
Description: "Cookies that help understand how visitors interact with the website.",
Kind: coredata.CookieCategoryKindNormal,
Rank: 1,
GCMConsentTypes: []string{"analytics_storage"},
PostHogConsent: true,
},
{
Name: "Advertising",
Slug: "advertising",
Description: "Cookies used to deliver relevant advertisements and track campaigns.",
Kind: coredata.CookieCategoryKindNormal,
Rank: 2,
GCMConsentTypes: []string{"ad_storage", "ad_user_data", "ad_personalization"},
PostHogConsent: false,
},
{
Name: "Functional",
Slug: "functional",
Description: "Cookies that enable enhanced functionality and personalization.",
Kind: coredata.CookieCategoryKindNormal,
Rank: 3,
GCMConsentTypes: []string{"functionality_storage", "personalization_storage"},
PostHogConsent: false,
},
{
Name: "Uncategorised",
Slug: "uncategorised",
Description: "Cookies that have not been assigned to a category yet.",
Kind: coredata.CookieCategoryKindUncategorised,
Rank: 4,
GCMConsentTypes: nil,
PostHogConsent: false,
},
} }
var defaultCategoryTranslationsByLanguage = map[string]map[string]struct { var defaultCategoryTranslationsByLanguage = map[string]map[string]struct {

View File

@@ -33,4 +33,5 @@ var (
ErrCookieNameAlreadyExists = errors.New("a cookie with this name already exists in this banner") ErrCookieNameAlreadyExists = errors.New("a cookie with this name already exists in this banner")
ErrCategoriesBannerMismatch = errors.New("source and target categories belong to different banners") ErrCategoriesBannerMismatch = errors.New("source and target categories belong to different banners")
ErrSameCategoryMove = errors.New("source and target cookie categories must be different") ErrSameCategoryMove = errors.New("source and target cookie categories must be different")
ErrPostHogConsentKindInvalid = errors.New("PostHog consent can only be enabled on normal categories")
) )

View File

@@ -574,6 +574,7 @@ func (s *Service) CreateCookieBanner(
Kind: dc.Kind, Kind: dc.Kind,
Rank: dc.Rank, Rank: dc.Rank,
GCMConsentTypes: gcmConsentTypes, GCMConsentTypes: gcmConsentTypes,
PostHogConsent: dc.PostHogConsent,
CreatedAt: now, CreatedAt: now,
UpdatedAt: now, UpdatedAt: now,
} }
@@ -1350,6 +1351,15 @@ func (s *Service) UpdateCookieCategory(
category.GCMConsentTypes = *req.GCMConsentTypes category.GCMConsentTypes = *req.GCMConsentTypes
} }
if req.PostHogConsent != nil { if req.PostHogConsent != nil {
if *req.PostHogConsent && category.Kind != coredata.CookieCategoryKindNormal {
return ErrPostHogConsentKindInvalid
}
if *req.PostHogConsent {
var categories coredata.CookieCategories
if err := categories.ClearPostHogConsentByBannerID(ctx, tx, scope, category.CookieBannerID); err != nil {
return fmt.Errorf("cannot clear posthog consent: %w", err)
}
}
category.PostHogConsent = *req.PostHogConsent category.PostHogConsent = *req.PostHogConsent
} }
@@ -2091,13 +2101,13 @@ func (s *Service) ReportDetectedCookies(
UpdatedAt: now, UpdatedAt: now,
} }
if err := cookie.Insert(ctx, tx, scope); err != nil { ok, err := cookie.InsertIfNotExists(ctx, tx, scope)
if errors.Is(err, coredata.ErrResourceAlreadyExists) { if err != nil {
continue
}
return fmt.Errorf("cannot insert detected cookie: %w", err) return fmt.Errorf("cannot insert detected cookie: %w", err)
} }
inserted++ if ok {
inserted++
}
} }
if inserted > 0 { if inserted > 0 {

View File

@@ -297,6 +297,59 @@ INSERT INTO cookies (
return nil return nil
} }
func (c *Cookie) InsertIfNotExists(
ctx context.Context,
tx pg.Tx,
scope Scoper,
) (bool, error) {
q := `
INSERT INTO cookies (
id,
tenant_id,
organization_id,
cookie_banner_id,
cookie_category_id,
name,
duration,
description,
created_at,
updated_at
) VALUES (
@id,
@tenant_id,
@organization_id,
@cookie_banner_id,
@cookie_category_id,
@name,
@duration,
@description,
@created_at,
@updated_at
)
ON CONFLICT (cookie_banner_id, name) DO NOTHING
`
args := pgx.StrictNamedArgs{
"id": c.ID,
"tenant_id": scope.GetTenantID(),
"organization_id": c.OrganizationID,
"cookie_banner_id": c.CookieBannerID,
"cookie_category_id": c.CookieCategoryID,
"name": c.Name,
"duration": c.Duration,
"description": c.Description,
"created_at": c.CreatedAt,
"updated_at": c.UpdatedAt,
}
result, err := tx.Exec(ctx, q, args)
if err != nil {
return false, fmt.Errorf("cannot insert cookie: %w", err)
}
return result.RowsAffected() > 0, nil
}
func (c *Cookie) Update( func (c *Cookie) Update(
ctx context.Context, ctx context.Context,
tx pg.Tx, tx pg.Tx,

View File

@@ -469,6 +469,39 @@ WHERE
return nil return nil
} }
func (c *CookieCategories) ClearPostHogConsentByBannerID(
ctx context.Context,
tx pg.Tx,
scope Scoper,
cookieBannerID gid.GID,
) error {
q := `
UPDATE cookie_categories
SET
posthog_consent = false,
updated_at = @updated_at
WHERE
%s
AND cookie_banner_id = @cookie_banner_id
AND posthog_consent = true
`
q = fmt.Sprintf(q, scope.SQLFragment())
args := pgx.StrictNamedArgs{
"cookie_banner_id": cookieBannerID,
"updated_at": time.Now(),
}
maps.Copy(args, scope.SQLArguments())
_, err := tx.Exec(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot clear posthog consent: %w", err)
}
return nil
}
func (c *CookieCategory) LoadUncategorisedByCookieBannerID( func (c *CookieCategory) LoadUncategorisedByCookieBannerID(
ctx context.Context, ctx context.Context,
conn pg.Querier, conn pg.Querier,

View File

@@ -0,0 +1,17 @@
-- Copyright (c) 2026 Probo Inc <hello@getprobo.com>.
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
-- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-- PERFORMANCE OF THIS SOFTWARE.
CREATE UNIQUE INDEX idx_cookie_categories_unique_posthog_per_banner
ON cookie_categories (cookie_banner_id)
WHERE posthog_consent = true;

View File

@@ -482,6 +482,9 @@ func (r *mutationResolver) UpdateCookieCategory(ctx context.Context, input types
if errors.Is(err, cookiebanner.ErrCategorySlugAlreadyExists) { if errors.Is(err, cookiebanner.ErrCategorySlugAlreadyExists) {
return nil, gqlutils.Conflict(ctx, err) return nil, gqlutils.Conflict(ctx, err)
} }
if errors.Is(err, cookiebanner.ErrPostHogConsentKindInvalid) {
return nil, gqlutils.Invalid(ctx, err)
}
if validationErrors, ok := errors.AsType[validator.ValidationErrors](err); ok { if validationErrors, ok := errors.AsType[validator.ValidationErrors](err); ok {
return nil, gqlutils.InvalidValidationErrors(ctx, validationErrors) return nil, gqlutils.InvalidValidationErrors(ctx, validationErrors)
} }