Add slug to cookie categories for stable consent identifiers

The category slug provides a stable, URL-safe key used as the
data-cookie-consent attribute value and consent data key, replacing
the fragile category name. This prevents breakage when categories
are renamed.

- Add slug column with unique-per-banner constraint and backfill migration
- Add Slug validator (lowercase alphanumeric + hyphens)
- Propagate slug through GraphQL schema, service layer, and snapshot
- Update console UI with slug field in create/edit forms
- Switch cookie-banner widget to use slug as consent data keys

Signed-off-by: Émile Ré <emile@getprobo.com>
This commit is contained in:
Émile Ré
2026-04-23 19:07:11 +04:00
parent bb39daebc5
commit 165b9ad9d3
19 changed files with 218 additions and 22 deletions

View File

@@ -18,15 +18,16 @@ import "go.probo.inc/probo/pkg/coredata"
var defaultCategories = []struct {
Name string
Slug string
Description string
Kind coredata.CookieCategoryKind
Rank int
}{
{"Necessary", "Essential cookies required for the website to function properly.", coredata.CookieCategoryKindNecessary, 0},
{"Analytics", "Cookies that help understand how visitors interact with the website.", coredata.CookieCategoryKindNormal, 1},
{"Advertising", "Cookies used to deliver relevant advertisements and track campaigns.", coredata.CookieCategoryKindNormal, 2},
{"Functional", "Cookies that enable enhanced functionality and personalization.", coredata.CookieCategoryKindNormal, 3},
{"Uncategorised", "Cookies that have not been assigned to a category yet.", coredata.CookieCategoryKindUncategorised, 4},
{"Necessary", "necessary", "Essential cookies required for the website to function properly.", coredata.CookieCategoryKindNecessary, 0},
{"Analytics", "analytics", "Cookies that help understand how visitors interact with the website.", coredata.CookieCategoryKindNormal, 1},
{"Advertising", "advertising", "Cookies used to deliver relevant advertisements and track campaigns.", coredata.CookieCategoryKindNormal, 2},
{"Functional", "functional", "Cookies that enable enhanced functionality and personalization.", coredata.CookieCategoryKindNormal, 3},
{"Uncategorised", "uncategorised", "Cookies that have not been assigned to a category yet.", coredata.CookieCategoryKindUncategorised, 4},
}
var defaultUIStringsByLanguage = map[string]map[string]string{

View File

@@ -26,6 +26,7 @@ var (
ErrNoPublishedVersion = errors.New("no published cookie banner version")
ErrNoDraftVersion = errors.New("no draft cookie banner version to publish")
ErrCannotDeleteSystemCategory = errors.New("cannot delete system cookie category")
ErrCategorySlugAlreadyExists = errors.New("a category with this slug already exists in this banner")
ErrOriginAlreadyInUse = errors.New("origin is already used by another active cookie banner")
ErrConsentNotFound = errors.New("consent record not found")
ErrCookieNotFound = errors.New("cookie not found")

View File

@@ -53,6 +53,7 @@ type (
CreateCookieCategoryRequest struct {
CookieBannerID gid.GID
Name string
Slug string
Description string
Rank int
}
@@ -70,6 +71,7 @@ type (
UpdateCookieCategoryRequest struct {
CookieCategoryID gid.GID
Name *string
Slug *string
Description *string
}
@@ -189,6 +191,7 @@ func (r *CreateCookieCategoryRequest) Validate() error {
v.Check(r.CookieBannerID, "cookie_banner_id", validator.Required(), validator.GID(coredata.CookieBannerEntityType))
v.Check(r.Name, "name", validator.Required(), validator.SafeTextNoNewLine(255))
v.Check(r.Slug, "slug", validator.Required(), validator.Slug(100))
v.Check(r.Description, "description", validator.Required(), validator.SafeText(1000))
v.Check(r.Rank, "rank", validator.Min(0))
@@ -200,6 +203,7 @@ func (r *UpdateCookieCategoryRequest) Validate() error {
v.Check(r.CookieCategoryID, "cookie_category_id", validator.Required(), validator.GID(coredata.CookieCategoryEntityType))
v.Check(r.Name, "name", validator.SafeTextNoNewLine(255))
v.Check(r.Slug, "slug", validator.Slug(100))
v.Check(r.Description, "description", validator.SafeText(1000))
return v.Error()
@@ -327,6 +331,7 @@ func buildSnapshot(
}
snapshotCategories[i] = coredata.CookieBannerVersionSnapshotCategory{
Name: c.Name,
Slug: c.Slug,
Description: c.Description,
Kind: c.Kind,
Cookies: cookies,
@@ -532,6 +537,7 @@ func (s *Service) CreateCookieBanner(
OrganizationID: banner.OrganizationID,
CookieBannerID: banner.ID,
Name: dc.Name,
Slug: dc.Slug,
Description: dc.Description,
Kind: dc.Kind,
Rank: dc.Rank,
@@ -925,6 +931,7 @@ func (s *Service) CreateCookieCategory(
OrganizationID: banner.OrganizationID,
CookieBannerID: req.CookieBannerID,
Name: req.Name,
Slug: req.Slug,
Description: req.Description,
Kind: coredata.CookieCategoryKindNormal,
Rank: req.Rank,
@@ -933,6 +940,9 @@ func (s *Service) CreateCookieCategory(
}
if err := category.Insert(ctx, tx, scope); err != nil {
if errors.Is(err, coredata.ErrResourceAlreadyExists) {
return ErrCategorySlugAlreadyExists
}
return fmt.Errorf("cannot insert cookie category: %w", err)
}
@@ -1274,6 +1284,9 @@ func (s *Service) UpdateCookieCategory(
if req.Name != nil {
category.Name = *req.Name
}
if req.Slug != nil {
category.Slug = *req.Slug
}
if req.Description != nil {
category.Description = *req.Description
}
@@ -1281,6 +1294,9 @@ func (s *Service) UpdateCookieCategory(
category.UpdatedAt = time.Now()
if err := category.Update(ctx, tx, scope); err != nil {
if errors.Is(err, coredata.ErrResourceAlreadyExists) {
return ErrCategorySlugAlreadyExists
}
return fmt.Errorf("cannot update cookie category: %w", err)
}

View File

@@ -50,6 +50,7 @@ type (
CookieBannerVersionSnapshotCategory struct {
Name string `json:"name"`
Slug string `json:"slug"`
Description string `json:"description"`
Kind CookieCategoryKind `json:"kind"`
Cookies CookieItems `json:"cookies"`

View File

@@ -23,6 +23,7 @@ import (
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/page"
@@ -42,6 +43,7 @@ type (
OrganizationID gid.GID `db:"organization_id"`
CookieBannerID gid.GID `db:"cookie_banner_id"`
Name string `db:"name"`
Slug string `db:"slug"`
Description string `db:"description"`
Kind CookieCategoryKind `db:"kind"`
Rank int `db:"rank"`
@@ -103,6 +105,7 @@ SELECT
organization_id,
cookie_banner_id,
name,
slug,
description,
kind,
rank,
@@ -152,6 +155,7 @@ SELECT
organization_id,
cookie_banner_id,
name,
slug,
description,
kind,
rank,
@@ -229,6 +233,7 @@ SELECT
organization_id,
cookie_banner_id,
name,
slug,
description,
kind,
rank,
@@ -275,6 +280,7 @@ INSERT INTO cookie_categories (
organization_id,
cookie_banner_id,
name,
slug,
description,
kind,
rank,
@@ -286,6 +292,7 @@ INSERT INTO cookie_categories (
@organization_id,
@cookie_banner_id,
@name,
@slug,
@description,
@kind,
@rank,
@@ -300,6 +307,7 @@ INSERT INTO cookie_categories (
"organization_id": c.OrganizationID,
"cookie_banner_id": c.CookieBannerID,
"name": c.Name,
"slug": c.Slug,
"description": c.Description,
"kind": c.Kind,
"rank": c.Rank,
@@ -309,6 +317,11 @@ INSERT INTO cookie_categories (
_, err := tx.Exec(ctx, q, args)
if err != nil {
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok {
if pgErr.Code == "23505" && pgErr.ConstraintName == "idx_cookie_categories_unique_slug_per_banner" {
return ErrResourceAlreadyExists
}
}
return fmt.Errorf("cannot insert cookie category: %w", err)
}
@@ -324,6 +337,7 @@ func (c *CookieCategory) Update(
UPDATE cookie_categories
SET
name = @name,
slug = @slug,
description = @description,
updated_at = @updated_at
WHERE
@@ -336,6 +350,7 @@ WHERE
args := pgx.StrictNamedArgs{
"id": c.ID,
"name": c.Name,
"slug": c.Slug,
"description": c.Description,
"updated_at": c.UpdatedAt,
}
@@ -343,6 +358,11 @@ WHERE
result, err := tx.Exec(ctx, q, args)
if err != nil {
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok {
if pgErr.Code == "23505" && pgErr.ConstraintName == "idx_cookie_categories_unique_slug_per_banner" {
return ErrResourceAlreadyExists
}
}
return fmt.Errorf("cannot update cookie category: %w", err)
}
@@ -443,6 +463,7 @@ SELECT
organization_id,
cookie_banner_id,
name,
slug,
description,
kind,
rank,

View File

@@ -0,0 +1,24 @@
-- 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.
ALTER TABLE cookie_categories
ADD COLUMN slug TEXT NOT NULL DEFAULT '';
UPDATE cookie_categories
SET slug = LOWER(REGEXP_REPLACE(REGEXP_REPLACE(name, '[^a-zA-Z0-9]+', '-', 'g'), '^-|-$', '', 'g'));
ALTER TABLE cookie_categories ALTER COLUMN slug DROP DEFAULT;
CREATE UNIQUE INDEX idx_cookie_categories_unique_slug_per_banner
ON cookie_categories (cookie_banner_id, slug);

View File

@@ -419,6 +419,7 @@ func (r *mutationResolver) CreateCookieCategory(ctx context.Context, input types
cookiebanner.CreateCookieCategoryRequest{
CookieBannerID: input.CookieBannerID,
Name: input.Name,
Slug: input.Slug,
Description: input.Description,
Rank: input.Rank,
},
@@ -427,6 +428,9 @@ func (r *mutationResolver) CreateCookieCategory(ctx context.Context, input types
if errors.Is(err, cookiebanner.ErrBannerNotFound) {
return nil, gqlutils.NotFound(ctx, err)
}
if errors.Is(err, cookiebanner.ErrCategorySlugAlreadyExists) {
return nil, gqlutils.Conflict(ctx, err)
}
if validationErrors, ok := errors.AsType[validator.ValidationErrors](err); ok {
return nil, gqlutils.InvalidValidationErrors(ctx, validationErrors)
}
@@ -460,6 +464,7 @@ func (r *mutationResolver) UpdateCookieCategory(ctx context.Context, input types
cookiebanner.UpdateCookieCategoryRequest{
CookieCategoryID: input.CookieCategoryID,
Name: input.Name,
Slug: input.Slug,
Description: input.Description,
},
)
@@ -467,6 +472,9 @@ func (r *mutationResolver) UpdateCookieCategory(ctx context.Context, input types
if errors.Is(err, cookiebanner.ErrCategoryNotFound) {
return nil, gqlutils.NotFound(ctx, err)
}
if errors.Is(err, cookiebanner.ErrCategorySlugAlreadyExists) {
return nil, gqlutils.Conflict(ctx, err)
}
if validationErrors, ok := errors.AsType[validator.ValidationErrors](err); ok {
return nil, gqlutils.InvalidValidationErrors(ctx, validationErrors)
}

View File

@@ -119,6 +119,7 @@ type CookieCategory implements Node {
id: ID!
cookieBanner: CookieBanner @goField(forceResolver: true)
name: String!
slug: String!
description: String!
kind: CookieCategoryKind!
rank: Int!
@@ -300,6 +301,7 @@ input PublishCookieBannerVersionInput {
input CreateCookieCategoryInput {
cookieBannerId: ID!
name: String!
slug: String!
description: String!
rank: Int!
}
@@ -307,6 +309,7 @@ input CreateCookieCategoryInput {
input UpdateCookieCategoryInput {
cookieCategoryId: ID!
name: String
slug: String
description: String
}

View File

@@ -67,6 +67,7 @@ func NewCookieCategory(c *coredata.CookieCategory) *CookieCategory {
ID: c.CookieBannerID,
},
Name: c.Name,
Slug: c.Slug,
Description: c.Description,
Kind: c.Kind,
Rank: c.Rank,

View File

@@ -15,6 +15,7 @@
package validator
import (
"fmt"
"net/url"
"regexp"
"slices"
@@ -25,6 +26,7 @@ import (
var (
domainRegex = regexp.MustCompile(`^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$`)
slugRegex = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*$`)
)
// URL validates that a string is a valid URL with http or https scheme.
@@ -177,6 +179,36 @@ func Origin() ValidatorFunc {
}
}
// Slug validates that a string is a lowercase alphanumeric slug (with hyphens, no
// leading/trailing hyphens, no consecutive hyphens) and does not exceed maxLen.
func Slug(maxLen int) ValidatorFunc {
return func(value any) *ValidationError {
actualValue, isNil := dereferenceValue(value)
if isNil {
return nil
}
str, ok := actualValue.(string)
if !ok {
return newValidationError(ErrorCodeInvalidFormat, "value must be a string")
}
if str == "" {
return nil
}
if len(str) > maxLen {
return newValidationError(ErrorCodeTooLong, fmt.Sprintf("slug must be at most %d characters", maxLen))
}
if !slugRegex.MatchString(str) {
return newValidationError(ErrorCodeInvalidFormat, "slug must contain only lowercase letters, numbers, and hyphens")
}
return nil
}
}
// Domain validates that a string is a valid domain name.
func Domain() ValidatorFunc {
return func(value any) *ValidationError {

View File

@@ -164,6 +164,49 @@ func TestOrigin(t *testing.T) {
}
}
func TestSlug(t *testing.T) {
tests := []struct {
name string
value any
maxLen int
wantError bool
wantCode ErrorCode
}{
{"valid simple slug", "analytics", 100, false, ""},
{"valid with hyphens", "my-category", 100, false, ""},
{"valid multi-segment", "my-cool-category", 100, false, ""},
{"valid single char", "a", 100, false, ""},
{"valid digits only", "123", 100, false, ""},
{"valid mixed", "cat2", 100, false, ""},
{"valid digit-hyphen-alpha", "1-a", 100, false, ""},
{"invalid - uppercase", "Analytics", 100, true, ErrorCodeInvalidFormat},
{"invalid - leading hyphen", "-analytics", 100, true, ErrorCodeInvalidFormat},
{"invalid - trailing hyphen", "analytics-", 100, true, ErrorCodeInvalidFormat},
{"invalid - consecutive hyphens", "my--category", 100, true, ErrorCodeInvalidFormat},
{"invalid - underscore", "my_category", 100, true, ErrorCodeInvalidFormat},
{"invalid - spaces", "my category", 100, true, ErrorCodeInvalidFormat},
{"invalid - special chars", "my@category", 100, true, ErrorCodeInvalidFormat},
{"invalid - dot", "my.category", 100, true, ErrorCodeInvalidFormat},
{"too long", "abcdefghijk", 10, true, ErrorCodeTooLong},
{"exactly max length", "abcdefghij", 10, false, ""},
{"empty string", "", 100, false, ""},
{"nil pointer", (*string)(nil), 100, false, ""},
{"non-string", 123, 100, true, ErrorCodeInvalidFormat},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := Slug(tt.maxLen)(tt.value)
if (err != nil) != tt.wantError {
t.Errorf("Slug(%d) error = %v, wantError %v", tt.maxLen, err, tt.wantError)
}
if err != nil && tt.wantCode != "" && err.Code != tt.wantCode {
t.Errorf("Expected error code %s, got %s", tt.wantCode, err.Code)
}
})
}
}
func TestDomain(t *testing.T) {
t.Run("valid domain", func(t *testing.T) {
str := "example.com"