Compare commits

..
Author SHA1 Message Date
Florian Sylvain daba3c04c0 fix: relation picker page size refused by entry list 2026-10-23 00:48:10 +02:00
Florian Sylvain f2cdbcd3cb docs: release notes for v3.5.0-beta 2026-10-23 00:38:22 +02:00
Florian Sylvain 37a77c9c22 feat: relation field and picker 2026-10-23 00:13:42 +02:00
Florian Sylvain b45c99be3b fix: reduced SPA build chunk sizes 2026-10-22 10:15:32 +02:00
Florian Sylvain fc51ab8c10 fix: editor's right side panel vertical overflow 2026-10-22 03:04:25 +02:00
Florian Sylvain 07f5c5d1ee docs: release notes for v3.4.2-beta 2026-10-22 00:50:33 +02:00
Florian Sylvain ea98c5ec05 fix: security & privacy (rate limiter fix, csrf session cookie, logout on server, drafts stale token passw, login timing, password over 72b, JWT_SECRET complexity, SMTP TLS, CSV export neutralised, fonts bundled, upload metadata, hourly cleanup job, privacy.md report) 2026-10-22 00:49:19 +02:00
Florian Sylvain e2812ee0b9 docs: release notes for v3.4.1-beta 2026-10-21 23:31:01 +02:00
Florian Sylvain aa5d3582f8 fix: updated go dependencies with latest security fixes 2026-10-21 23:28:41 +02:00
Florian Sylvain c68e9a7858 refac: removed 7 direct and 12 indirect go modules for custom code instead 2026-10-21 23:13:46 +02:00
Florian Sylvain cfcf108488 fix: web dependencies security updates 2026-10-21 22:55:37 +02:00
Florian Sylvain b43cc6861f docs: removed coding standards from version control 2026-10-21 22:48:31 +02:00
Florian Sylvain 074944c99a refac: atomic merge, lost-update race, RunPurge cost, duplicated walks 2026-10-21 22:47:46 +02:00
Florian Sylvain 0fc3511e2b feat(SPA): media library indications for custom medial field type usage 2026-10-21 16:17:09 +02:00
Florian Sylvain 3e7fc9a4a5 feat(SPA): media field type 2026-10-21 15:17:15 +02:00
Florian Sylvain a2d596f4ca feat(API): media field type 2026-10-21 05:07:36 +02:00
381 changed files with 26426 additions and 1466 deletions

No files matched your search

+1
View File
@@ -14,6 +14,7 @@ CORS_ALLOWED_ORIGINS=
AUTH_RATE_LIMIT_MAX_ATTEMPTS=5 AUTH_RATE_LIMIT_MAX_ATTEMPTS=5
AUTH_RATE_LIMIT_WINDOW_SECONDS=60 AUTH_RATE_LIMIT_WINDOW_SECONDS=60
TRUSTED_PROXIES= TRUSTED_PROXIES=
SMTP_ALLOW_INSECURE=false
UPDATE_FEED_URL=https://git.floriansylvain.fr UPDATE_FEED_URL=https://git.floriansylvain.fr
RENEWCMS_CONTAINER=false RENEWCMS_CONTAINER=false
IMAGE_VARIANT_MAX_SOURCE_BYTES=10485760 IMAGE_VARIANT_MAX_SOURCE_BYTES=10485760
+1
View File
@@ -28,3 +28,4 @@ CLAUDE.md
.agents/ .agents/
AGENTS.md AGENTS.md
codex-workflow.md codex-workflow.md
CODING_STANDARDS.md
-100
View File
@@ -1,100 +0,0 @@
# Coding Standards
These rules apply to every file in this repo , for humans and agents alike.
## General rules
1. Follow standard conventions.
2. Keep it simple stupid. Simpler is always better. Reduce complexity as much as possible.
3. Boy scout rule. Leave the campground cleaner than you found it.
4. Always find root cause. Always look for the root cause of a problem.
## Design rules
1. Keep configurable data at high levels.
2. Prefer polymorphism to if/else or switch/case.
3. Separate multi-threading code.
4. Prevent over-configurability.
5. Use dependency injection.
6. Follow Law of Demeter. A class should know only its direct dependencies.
## Understandability tips
1. Be consistent. If you do something a certain way, do all similar things in the same way.
2. Use explanatory variables.
3. Encapsulate boundary conditions. Boundary conditions are hard to keep track of. Put the processing for them in one place.
4. Prefer dedicated value objects to primitive types.
5. Avoid logical dependency. Don't write methods which work correctly only depending on something else in the same class.
6. Avoid negative conditionals.
## Names rules
1. Choose descriptive and unambiguous names.
2. Make meaningful distinctions.
3. Use pronounceable names.
4. Use searchable names.
5. Replace magic numbers with named constants.
6. Avoid encodings. Don't append prefixes or type information.
## Functions rules
1. Small.
2. Do one thing.
3. Use descriptive names.
4. Prefer fewer arguments.
5. Have no side effects.
6. Don't use flag arguments. Split the method into several independent methods that can be called from the client without the flag.
## Comments rules
1. No comments in the codebase. This covers Go, TypeScript/Vue, HTML templates and config files (YAML, TOML, `.env.example`, `.gitattributes`, …).
2. Explain yourself in code instead: descriptive names, small functions, named constants, explanatory variables.
3. The only exceptions are tool directives the code needs to work, such as `//go:build` and `//go:embed`.
4. Don't comment out code; just remove it.
5. Prose belongs in `docs/` and `README.md`, not in source files.
## Source code structure
1. Separate concepts vertically.
2. Related code should appear vertically dense.
3. Declare variables close to their usage.
4. Dependent functions should be close.
5. Similar functions should be close.
6. Place functions in the downward direction (caller above callee).
7. Keep lines short.
8. Don't use horizontal alignment.
9. Use white space to associate related things and disassociate weakly related ones.
10. Don't break indentation.
## Objects and data structures
1. Hide internal structure.
2. Prefer data structures when there's no behavior to attach.
3. Avoid hybrid structures (half object, half data).
4. Keep classes small.
5. Each class should do one thing.
6. Keep the number of instance variables small.
7. Base classes should know nothing about their derivatives.
8. Prefer many small functions over one function with a parameter that selects behavior.
9. Prefer non-static methods to static methods.
## Tests
1. One assert per test.
2. Readable.
3. Fast.
4. Independent.
5. Repeatable.
## Code smells to watch for
1. **Rigidity** — the software is difficult to change; a small change causes a cascade of subsequent changes.
2. **Fragility** — the software breaks in many places due to a single change.
3. **Immobility** — you cannot reuse parts of the code in other projects because of the risk and effort involved.
4. **Needless complexity**.
5. **Needless repetition**.
6. **Opacity** — the code is hard to understand.
## Credits
Thanks to [@wojtekluwojteklu/clean_code.md](https://gist.github.com/wojteklu/73c6914cc446146b8b533c0988cf8d29)
+1 -1
View File
@@ -5,7 +5,7 @@ RUN bun install --frozen-lockfile
COPY web/ ./ COPY web/ ./
RUN bun run build-only RUN bun run build-only
FROM golang:1.27.1-alpine AS server FROM golang:1.27.3-alpine AS server
ARG VERSION=dev ARG VERSION=dev
ENV CGO_ENABLED=0 ENV CGO_ENABLED=0
WORKDIR /src WORKDIR /src
+1
View File
@@ -47,6 +47,7 @@ task dev # API with hot reload + Vite HMR → http://localhost:51
| [docs/deployment.md](docs/deployment.md) | Building release binaries, running as a service, HTTPS, backups, upgrades | | [docs/deployment.md](docs/deployment.md) | Building release binaries, running as a service, HTTPS, backups, upgrades |
| [docs/docker.md](docs/docker.md) | Running RenewCMS in Docker: image, Compose, data volume, backups, reverse proxy, tags, upgrades, publishing | | [docs/docker.md](docs/docker.md) | Running RenewCMS in Docker: image, Compose, data volume, backups, reverse proxy, tags, upgrades, publishing |
| [docs/configuration.md](docs/configuration.md) | Every environment variable | | [docs/configuration.md](docs/configuration.md) | Every environment variable |
| [docs/privacy.md](docs/privacy.md) | Personal data stored, retention, cookies, outbound connections and GDPR requests |
| [docs/architecture.md](docs/architecture.md) | Backend layering and how the SPA is embedded | | [docs/architecture.md](docs/architecture.md) | Backend layering and how the SPA is embedded |
| [docs/performance.md](docs/performance.md) | Measured costs, such as the `?seo=` article filter | | [docs/performance.md](docs/performance.md) | Measured costs, such as the `?seo=` article filter |
| [docs/api.md](docs/api.md) | API reference: authentication, API keys, routes and the activity log | | [docs/api.md](docs/api.md) | API reference: authentication, API keys, routes and the activity log |
+1 -1
View File
@@ -231,7 +231,7 @@ tasks:
desc: Type-check and build the SPA into {{.DIST_DIR}} desc: Type-check and build the SPA into {{.DIST_DIR}}
dir: web dir: web
deps: [web:install] deps: [web:install]
sources: [src/**/*, public/**/*, index.html, vite.config.ts, tsconfig*.json, package.json, bun.lock] sources: [src/**/*, public/**/*, vite/**/*, index.html, vite.config.ts, tsconfig*.json, package.json, bun.lock]
generates: ['../{{.DIST_DIR}}/index.html'] generates: ['../{{.DIST_DIR}}/index.html']
cmds: cmds:
- bun run build - bun run build
+21 -14
View File
@@ -1,6 +1,7 @@
package api package api
import ( import (
"RenewCMS/api/pkg/authtoken"
domainAPIKey "RenewCMS/internal/domain/apikey" domainAPIKey "RenewCMS/internal/domain/apikey"
domainArticle "RenewCMS/internal/domain/article" domainArticle "RenewCMS/internal/domain/article"
domainAudit "RenewCMS/internal/domain/audit" domainAudit "RenewCMS/internal/domain/audit"
@@ -11,7 +12,9 @@ import (
domainInvite "RenewCMS/internal/domain/invite" domainInvite "RenewCMS/internal/domain/invite"
domainMail "RenewCMS/internal/domain/mail" domainMail "RenewCMS/internal/domain/mail"
domainPurge "RenewCMS/internal/domain/purge" domainPurge "RenewCMS/internal/domain/purge"
domainSession "RenewCMS/internal/domain/session"
domainSite "RenewCMS/internal/domain/site" domainSite "RenewCMS/internal/domain/site"
domainTransaction "RenewCMS/internal/domain/transaction"
domainUpdate "RenewCMS/internal/domain/update" domainUpdate "RenewCMS/internal/domain/update"
domainUser "RenewCMS/internal/domain/user" domainUser "RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/auditing" "RenewCMS/internal/infrastructure/auditing"
@@ -36,16 +39,15 @@ import (
"runtime" "runtime"
"sync" "sync"
"time" "time"
"github.com/go-chi/jwtauth/v5"
) )
type UseCases struct { type UseCases struct {
apiKeyAuthOnce sync.Once apiKeyAuthOnce sync.Once
apiKeyAuthMiddleware func(http.Handler) http.Handler apiKeyAuthMiddleware func(http.Handler) http.Handler
Token *jwtauth.JWTAuth Token *authtoken.Auth
PurgeScheduler *scheduler.Runner PurgeScheduler *scheduler.Runner
ActivityCleanupScheduler *scheduler.Runner ActivityCleanupScheduler *scheduler.Runner
RetentionScheduler *scheduler.Runner
CreateArticleUseCase *useCases.CreateArticleUseCase CreateArticleUseCase *useCases.CreateArticleUseCase
GetArticleUseCase *useCases.GetArticleUseCase GetArticleUseCase *useCases.GetArticleUseCase
ListArticlesUseCase *useCases.ListArticlesUseCase ListArticlesUseCase *useCases.ListArticlesUseCase
@@ -139,7 +141,7 @@ type UseCases struct {
func (c *UseCases) RunSchedulers(ctx context.Context) { func (c *UseCases) RunSchedulers(ctx context.Context) {
var running sync.WaitGroup var running sync.WaitGroup
for _, runner := range []*scheduler.Runner{c.PurgeScheduler, c.ActivityCleanupScheduler} { for _, runner := range []*scheduler.Runner{c.PurgeScheduler, c.ActivityCleanupScheduler, c.RetentionScheduler} {
if runner == nil { if runner == nil {
continue continue
} }
@@ -160,6 +162,7 @@ type Repositories struct {
AuthorRepo domainAuthor.Repository AuthorRepo domainAuthor.Repository
UserRepo domainUser.Repository UserRepo domainUser.Repository
ImageRepo domainImage.Repository ImageRepo domainImage.Repository
Transactor domainTransaction.Transactor
VariantRepo domainImage.VariantRepository VariantRepo domainImage.VariantRepository
VariantFileRepo domainImage.VariantFileRepository VariantFileRepo domainImage.VariantFileRepository
VariantCacheRepo domainImage.VariantCacheRepository VariantCacheRepo domainImage.VariantCacheRepository
@@ -167,6 +170,7 @@ type Repositories struct {
VariantRenderer domainImage.VariantRenderer VariantRenderer domainImage.VariantRenderer
InviteRepo domainInvite.Repository InviteRepo domainInvite.Repository
APIKeyRepo domainAPIKey.Repository APIKeyRepo domainAPIKey.Repository
SessionRepo domainSession.Repository
PurgeSettingsRepo domainPurge.Repository PurgeSettingsRepo domainPurge.Repository
AuditRepo domainAudit.Repository AuditRepo domainAudit.Repository
AuditSettingsRepo domainAudit.SettingsRepository AuditSettingsRepo domainAudit.SettingsRepository
@@ -302,6 +306,7 @@ func getRepositories(connection *database.Connection, settings config.Settings)
AuthorRepo: persistence.NewAuthorRepository(db), AuthorRepo: persistence.NewAuthorRepository(db),
UserRepo: persistence.NewUserRepository(db), UserRepo: persistence.NewUserRepository(db),
ImageRepo: persistence.NewImageRepository(db), ImageRepo: persistence.NewImageRepository(db),
Transactor: persistence.NewTransactor(db),
VariantRepo: persistence.NewVariantRepository(db), VariantRepo: persistence.NewVariantRepository(db),
VariantFileRepo: variantFiles, VariantFileRepo: variantFiles,
VariantCacheRepo: variantFiles, VariantCacheRepo: variantFiles,
@@ -309,6 +314,7 @@ func getRepositories(connection *database.Connection, settings config.Settings)
VariantRenderer: imaging.NewVariantRenderer(), VariantRenderer: imaging.NewVariantRenderer(),
InviteRepo: persistence.NewInviteRepository(db), InviteRepo: persistence.NewInviteRepository(db),
APIKeyRepo: persistence.NewAPIKeyRepository(db), APIKeyRepo: persistence.NewAPIKeyRepository(db),
SessionRepo: persistence.NewRevokedSessionRepository(db),
PurgeSettingsRepo: persistence.NewPurgeSettingsRepository(db), PurgeSettingsRepo: persistence.NewPurgeSettingsRepository(db),
AuditRepo: persistence.NewAuditEventRepository(db), AuditRepo: persistence.NewAuditEventRepository(db),
AuditSettingsRepo: persistence.NewAuditSettingsRepository(db), AuditSettingsRepo: persistence.NewAuditSettingsRepository(db),
@@ -332,7 +338,7 @@ func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings
renderer := markdown.NewConverter() renderer := markdown.NewConverter()
keyGenerator := hashing.NewSHA256KeyGenerator() keyGenerator := hashing.NewSHA256KeyGenerator()
recorder := auditing.NewRecorder(repos.AuditRepo, time.Now, log.Default()) recorder := auditing.NewRecorder(repos.AuditRepo, time.Now, log.Default())
mergeMedia := useCases.NewMergeMediaUseCase(repos.ImageRepo, repos.ArticleRepo, imageStorage, repos.VariantFileRepo, recorder, repos.SiteRepo, repos.AuthorRepo) mergeMedia := useCases.NewMergeMediaUseCase(repos.ImageRepo, repos.ArticleRepo, imageStorage, repos.VariantFileRepo, recorder, repos.ContentTypeRepo, repos.EntryRepo, repos.Transactor, log.Default())
runPurge := useCases.NewRunPurgeUseCase(repos.ImageRepo, repos.ArticleRepo, mergeMedia, repos.PurgeSettingsRepo, time.Now, log.Default(), recorder, repos.SiteRepo, repos.AuthorRepo) runPurge := useCases.NewRunPurgeUseCase(repos.ImageRepo, repos.ArticleRepo, mergeMedia, repos.PurgeSettingsRepo, time.Now, log.Default(), recorder, repos.SiteRepo, repos.AuthorRepo)
purgeScheduler := useCases.NewPurgeSchedulerUseCase(repos.PurgeSettingsRepo, runPurge, recorder) purgeScheduler := useCases.NewPurgeSchedulerUseCase(repos.PurgeSettingsRepo, runPurge, recorder)
@@ -344,7 +350,8 @@ func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings
return &UseCases{ return &UseCases{
PurgeScheduler: scheduler.NewSystemRunner(purgeScheduler, log.Default()), PurgeScheduler: scheduler.NewSystemRunner(purgeScheduler, log.Default()),
ActivityCleanupScheduler: scheduler.NewSystemCleanupRunner(activityCleanup, log.Default()), ActivityCleanupScheduler: scheduler.NewSystemCleanupRunner(activityCleanup, log.Default()),
Token: jwtauth.New("HS256", []byte(settings.JWTSecret), nil), RetentionScheduler: scheduler.NewSystemRetentionRunner(useCases.NewEnforceRetentionUseCase(repos.UserRepo, repos.InviteRepo, repos.SessionRepo), log.Default()),
Token: authtoken.New([]byte(settings.JWTSecret), authtoken.WithRevocationStore(useCases.NewSessionRevocationUseCase(repos.SessionRepo, time.Now))),
CreateArticleUseCase: useCases.NewCreateArticleUseCase(repos.ArticleRepo, renderer, recorder, repos.SiteRepo, repos.AuthorRepo), CreateArticleUseCase: useCases.NewCreateArticleUseCase(repos.ArticleRepo, renderer, recorder, repos.SiteRepo, repos.AuthorRepo),
GetArticleUseCase: useCases.NewGetArticleUseCase(repos.ArticleRepo, renderer), GetArticleUseCase: useCases.NewGetArticleUseCase(repos.ArticleRepo, renderer),
ListArticlesUseCase: useCases.NewListArticlesUseCase(repos.ArticleRepo, renderer, repos.SiteRepo), ListArticlesUseCase: useCases.NewListArticlesUseCase(repos.ArticleRepo, renderer, repos.SiteRepo),
@@ -372,10 +379,10 @@ func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings
ListBuiltinTypesUseCase: useCases.NewListBuiltinTypesUseCase(), ListBuiltinTypesUseCase: useCases.NewListBuiltinTypesUseCase(),
GetBuiltinTypeUseCase: useCases.NewGetBuiltinTypeUseCase(), GetBuiltinTypeUseCase: useCases.NewGetBuiltinTypeUseCase(),
LookupUserNamesUseCase: useCases.NewLookupUserNamesUseCase(repos.UserRepo), LookupUserNamesUseCase: useCases.NewLookupUserNamesUseCase(repos.UserRepo),
CreateEntryUseCase: useCases.NewCreateEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo, time.Now), CreateEntryUseCase: useCases.NewCreateEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo, repos.ImageRepo, time.Now),
GetEntryUseCase: useCases.NewGetEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo), GetEntryUseCase: useCases.NewGetEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo, repos.ImageRepo),
ListEntriesUseCase: useCases.NewListEntriesUseCase(repos.ContentTypeRepo, repos.EntryRepo), ListEntriesUseCase: useCases.NewListEntriesUseCase(repos.ContentTypeRepo, repos.EntryRepo, repos.ImageRepo),
UpdateEntryUseCase: useCases.NewUpdateEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo, time.Now), UpdateEntryUseCase: useCases.NewUpdateEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo, repos.ImageRepo, time.Now),
DeleteEntryUseCase: useCases.NewDeleteEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo), DeleteEntryUseCase: useCases.NewDeleteEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo),
GetUserUseCase: useCases.NewGetUserUseCase(repos.UserRepo), GetUserUseCase: useCases.NewGetUserUseCase(repos.UserRepo),
CreateUserUseCase: useCases.NewCreateUserUseCase(repos.UserRepo, hasher, repos.MailRepo, settings.PublicURL, recorder), CreateUserUseCase: useCases.NewCreateUserUseCase(repos.UserRepo, hasher, repos.MailRepo, settings.PublicURL, recorder),
@@ -393,16 +400,16 @@ func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings
GetInviteUseCase: useCases.NewGetInviteUseCase(repos.InviteRepo, hasher), GetInviteUseCase: useCases.NewGetInviteUseCase(repos.InviteRepo, hasher),
AcceptInviteUseCase: useCases.NewAcceptInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher, recorder), AcceptInviteUseCase: useCases.NewAcceptInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher, recorder),
SendMailUseCase: useCases.NewSendMailUseCase(repos.MailRepo), SendMailUseCase: useCases.NewSendMailUseCase(repos.MailRepo),
CreateImageUseCase: useCases.NewCreateImageUseCase(repos.ImageRepo, imageStorage, recorder), CreateImageUseCase: useCases.NewCreateImageUseCase(repos.ImageRepo, imageStorage, recorder, imaging.NewMetadataStripper()),
OpenMediaUseCase: useCases.NewOpenMediaUseCase(imageStorage), OpenMediaUseCase: useCases.NewOpenMediaUseCase(imageStorage),
ListMediaUseCase: useCases.NewListMediaUseCase(repos.ImageRepo, repos.ArticleRepo, repos.UserRepo, repos.VariantFileRepo, repos.SiteRepo, repos.AuthorRepo), ListMediaUseCase: useCases.NewListMediaUseCase(repos.ImageRepo, repos.ArticleRepo, repos.UserRepo, repos.VariantFileRepo, repos.SiteRepo, repos.AuthorRepo, repos.ContentTypeRepo, repos.EntryRepo),
RenameMediaUseCase: useCases.NewRenameMediaUseCase(repos.ImageRepo, recorder), RenameMediaUseCase: useCases.NewRenameMediaUseCase(repos.ImageRepo, recorder),
DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(repos.ImageRepo, imageStorage, repos.VariantFileRepo, recorder, repos.SiteRepo, repos.AuthorRepo, repos.ArticleRepo), DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(repos.ImageRepo, imageStorage, repos.VariantFileRepo, recorder, repos.SiteRepo, repos.AuthorRepo, repos.ArticleRepo),
MergeMediaUseCase: mergeMedia, MergeMediaUseCase: mergeMedia,
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(repos.ImageRepo, repos.ArticleRepo, repos.SiteRepo, repos.AuthorRepo), GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(repos.ImageRepo, repos.ArticleRepo, repos.SiteRepo, repos.AuthorRepo, repos.ContentTypeRepo, repos.EntryRepo),
GetPurgeSettingsUseCase: useCases.NewGetPurgeSettingsUseCase(repos.PurgeSettingsRepo), GetPurgeSettingsUseCase: useCases.NewGetPurgeSettingsUseCase(repos.PurgeSettingsRepo),
UpdatePurgeSettingsUseCase: useCases.NewUpdatePurgeSettingsUseCase(repos.PurgeSettingsRepo, time.Now), UpdatePurgeSettingsUseCase: useCases.NewUpdatePurgeSettingsUseCase(repos.PurgeSettingsRepo, time.Now),
PreviewPurgeUseCase: useCases.NewPreviewPurgeUseCase(repos.ImageRepo, repos.ArticleRepo, repos.SiteRepo, repos.AuthorRepo), PreviewPurgeUseCase: useCases.NewPreviewPurgeUseCase(repos.ImageRepo, repos.ArticleRepo, repos.SiteRepo, repos.AuthorRepo, repos.ContentTypeRepo, repos.EntryRepo),
RunPurgeUseCase: runPurge, RunPurgeUseCase: runPurge,
GetSettingsUseCase: useCases.NewGetSettingsUseCase(settings.Version), GetSettingsUseCase: useCases.NewGetSettingsUseCase(settings.Version),
GetUpdateStatusUseCase: useCases.NewGetUpdateStatusUseCase(repos.UpdateStore, repos.UpdateJobs, repos.UpdateHelper, repos.UpdateResults, repos.RestartRequests, settings.Version, settings.Container, time.Now), GetUpdateStatusUseCase: useCases.NewGetUpdateStatusUseCase(repos.UpdateStore, repos.UpdateJobs, repos.UpdateHelper, repos.UpdateResults, repos.RestartRequests, settings.Version, settings.Container, time.Now),
+5
View File
@@ -506,6 +506,11 @@ func isVerifiedCaller(r *http.Request, getUser *useCases.GetUserUseCase) bool {
return false return false
} }
tokenVersion, ok := claims.TokenVersion(r)
if !ok || tokenVersion != currentUser.TokenVersion {
return false
}
return currentUser.IsVerified return currentUser.IsVerified
} }
+5 -4
View File
@@ -2,6 +2,7 @@ package auth
import ( import (
"RenewCMS/api/pkg/apperr" "RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/authtoken"
validator "RenewCMS/api/pkg/validator" validator "RenewCMS/api/pkg/validator"
"RenewCMS/internal/domain/invite" "RenewCMS/internal/domain/invite"
"RenewCMS/internal/domain/user" "RenewCMS/internal/domain/user"
@@ -9,12 +10,10 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"net/http" "net/http"
"github.com/go-chi/jwtauth/v5"
) )
type AcceptInviteHandler struct { type AcceptInviteHandler struct {
Token *jwtauth.JWTAuth Token *authtoken.Auth
GetInviteUseCase *useCases.GetInviteUseCase GetInviteUseCase *useCases.GetInviteUseCase
AcceptInviteUseCase *useCases.AcceptInviteUseCase AcceptInviteUseCase *useCases.AcceptInviteUseCase
IsProduction bool IsProduction bool
@@ -30,7 +29,7 @@ type inviteEmailResponse struct {
Email string `json:"email"` Email string `json:"email"`
} }
func NewAcceptInviteHandler(getInvite *useCases.GetInviteUseCase, acceptInvite *useCases.AcceptInviteUseCase, token *jwtauth.JWTAuth, isProduction bool) *AcceptInviteHandler { func NewAcceptInviteHandler(getInvite *useCases.GetInviteUseCase, acceptInvite *useCases.AcceptInviteUseCase, token *authtoken.Auth, isProduction bool) *AcceptInviteHandler {
return &AcceptInviteHandler{ return &AcceptInviteHandler{
Token: token, Token: token,
GetInviteUseCase: getInvite, GetInviteUseCase: getInvite,
@@ -96,6 +95,8 @@ func writeAcceptInviteError(w http.ResponseWriter, err error) {
http.Error(w, apperr.UsernameTakenErrorMessage, http.StatusConflict) http.Error(w, apperr.UsernameTakenErrorMessage, http.StatusConflict)
case errors.Is(err, invite.ErrEmailHasAccount): case errors.Is(err, invite.ErrEmailHasAccount):
http.Error(w, apperr.EmailHasAccountErrorMessage, http.StatusConflict) http.Error(w, apperr.EmailHasAccountErrorMessage, http.StatusConflict)
case errors.Is(err, user.ErrPasswordTooLong):
http.Error(w, apperr.PasswordTooLongErrorMessage, http.StatusBadRequest)
default: default:
http.Error(w, "Internal server error", http.StatusInternalServerError) http.Error(w, "Internal server error", http.StatusInternalServerError)
} }
+21 -10
View File
@@ -2,6 +2,7 @@ package auth
import ( import (
"RenewCMS/api/pkg/apperr" "RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/authtoken"
validator "RenewCMS/api/pkg/validator" validator "RenewCMS/api/pkg/validator"
"RenewCMS/internal/domain/user" "RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases" "RenewCMS/internal/infrastructure/useCases"
@@ -9,12 +10,10 @@ import (
"errors" "errors"
"net/http" "net/http"
"time" "time"
"github.com/go-chi/jwtauth/v5"
) )
type LoginHandler struct { type LoginHandler struct {
Token *jwtauth.JWTAuth Token *authtoken.Auth
CreateUseCase *useCases.CreateUserUseCase CreateUseCase *useCases.CreateUserUseCase
AuthenticateUseCase *useCases.AuthenticateUserUseCase AuthenticateUseCase *useCases.AuthenticateUserUseCase
IsProduction bool IsProduction bool
@@ -31,7 +30,7 @@ type LoginCredentials struct {
Password string `json:"password" validate:"required,min=8"` Password string `json:"password" validate:"required,min=8"`
} }
func NewLoginHandler(token *jwtauth.JWTAuth, create *useCases.CreateUserUseCase, authenticate *useCases.AuthenticateUserUseCase, isProduction bool) *LoginHandler { func NewLoginHandler(token *authtoken.Auth, create *useCases.CreateUserUseCase, authenticate *useCases.AuthenticateUserUseCase, isProduction bool) *LoginHandler {
return &LoginHandler{ return &LoginHandler{
Token: token, Token: token,
CreateUseCase: create, CreateUseCase: create,
@@ -42,27 +41,29 @@ func NewLoginHandler(token *jwtauth.JWTAuth, create *useCases.CreateUserUseCase,
func removeJwtCookie(w http.ResponseWriter, isProduction bool) { func removeJwtCookie(w http.ResponseWriter, isProduction bool) {
http.SetCookie(w, &http.Cookie{ http.SetCookie(w, &http.Cookie{
Name: "jwt", Name: authtoken.CookieName,
Value: "", Value: "",
Expires: time.Now(), Expires: time.Now(),
MaxAge: -1, MaxAge: -1,
Secure: isProduction, Secure: isProduction,
HttpOnly: true, HttpOnly: true,
SameSite: http.SameSiteLaxMode,
Path: "/", Path: "/",
}) })
} }
func setJwtCookie(w http.ResponseWriter, token *jwtauth.JWTAuth, isProduction bool, u user.User) error { func setJwtCookie(w http.ResponseWriter, token *authtoken.Auth, isProduction bool, u user.User) error {
_, tokenString, err := token.Encode(map[string]any{"user_id": u.ID, "token_version": u.TokenVersion}) tokenString, err := token.Encode(map[string]any{"user_id": u.ID, "token_version": u.TokenVersion})
if err != nil { if err != nil {
return err return err
} }
http.SetCookie(w, &http.Cookie{ http.SetCookie(w, &http.Cookie{
Name: "jwt", Name: authtoken.CookieName,
Value: tokenString, Value: tokenString,
Expires: time.Now().Add(24 * time.Hour), Expires: time.Now().Add(authtoken.SessionLifetime),
Secure: isProduction, Secure: isProduction,
HttpOnly: true, HttpOnly: true,
SameSite: http.SameSiteLaxMode,
Path: "/", Path: "/",
}) })
return nil return nil
@@ -123,6 +124,10 @@ func (h *LoginHandler) Register(w http.ResponseWriter, r *http.Request) {
http.Error(w, apperr.RegistrationClosedErrorMessage, http.StatusForbidden) http.Error(w, apperr.RegistrationClosedErrorMessage, http.StatusForbidden)
return return
} }
if errors.Is(err, user.ErrPasswordTooLong) {
http.Error(w, apperr.PasswordTooLongErrorMessage, http.StatusBadRequest)
return
}
http.Error(w, apperr.RegistrationFailedErrorMessage, http.StatusInternalServerError) http.Error(w, apperr.RegistrationFailedErrorMessage, http.StatusInternalServerError)
return return
} }
@@ -140,8 +145,14 @@ func (h *LoginHandler) RegistrationStatus(w http.ResponseWriter, _ *http.Request
} }
func (h *LoginHandler) Logout(w http.ResponseWriter, r *http.Request) { func (h *LoginHandler) Logout(w http.ResponseWriter, r *http.Request) {
h.AuthenticateUseCase.Logout(r.Context())
removeJwtCookie(w, h.IsProduction) removeJwtCookie(w, h.IsProduction)
if claims, err := authtoken.FromContext(r.Context()); err == nil {
if err := h.Token.Revoke(claims); err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
}
h.AuthenticateUseCase.Logout(r.Context())
message, _ := json.Marshal(map[string]any{"message": "User logged out! HTTPonly jwt cookie deleted"}) message, _ := json.Marshal(map[string]any{"message": "User logged out! HTTPonly jwt cookie deleted"})
_, _ = w.Write(message) _, _ = w.Write(message)
} }
@@ -72,6 +72,10 @@ func (h *PasswordResetHandler) ResetPassword(w http.ResponseWriter, r *http.Requ
http.Error(w, apperr.PasswordResetFailedErrorMessage, http.StatusForbidden) http.Error(w, apperr.PasswordResetFailedErrorMessage, http.StatusForbidden)
return return
} }
if errors.Is(err, user.ErrPasswordTooLong) {
http.Error(w, apperr.PasswordTooLongErrorMessage, http.StatusBadRequest)
return
}
http.Error(w, "Internal server error", http.StatusInternalServerError) http.Error(w, "Internal server error", http.StatusInternalServerError)
return return
} }
@@ -92,6 +92,8 @@ func writeContentTypeError(w http.ResponseWriter, err error) {
http.Error(w, apperr.ContentTypeKeyTakenErrorMessage, http.StatusConflict) http.Error(w, apperr.ContentTypeKeyTakenErrorMessage, http.StatusConflict)
case errors.Is(err, domain.ErrHasEntries): case errors.Is(err, domain.ErrHasEntries):
http.Error(w, apperr.ContentTypeHasEntriesErrorMessage, http.StatusConflict) http.Error(w, apperr.ContentTypeHasEntriesErrorMessage, http.StatusConflict)
case errors.Is(err, domain.ErrReferenced):
http.Error(w, apperr.ContentTypeReferencedErrorMessage, http.StatusConflict)
case errors.Is(err, domain.ErrSchemaIncompatible): case errors.Is(err, domain.ErrSchemaIncompatible):
http.Error(w, apperr.SchemaIncompatibleErrorMessage, http.StatusConflict) http.Error(w, apperr.SchemaIncompatibleErrorMessage, http.StatusConflict)
case errors.Is(err, domain.ErrInvalidName): case errors.Is(err, domain.ErrInvalidName):
+73 -1
View File
@@ -42,6 +42,76 @@ type entryResponse struct {
UpdatedBy uint32 `json:"updated_by"` UpdatedBy uint32 `json:"updated_by"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"` UpdatedAt time.Time `json:"updated_at"`
Media map[string]any `json:"media"`
Relations map[string]any `json:"relations"`
}
type firstFieldBody struct {
Key string `json:"key"`
Type contenttype.FieldType `json:"type"`
Value any `json:"value"`
}
type relationBody struct {
ID uint32 `json:"id"`
ContentType string `json:"content_type"`
FirstField firstFieldBody `json:"first_field"`
}
type missingRelationBody struct {
ID uint32 `json:"id"`
Missing bool `json:"missing"`
}
func toRelationItem(item useCases.EntryRelation) any {
if item.Missing {
return missingRelationBody{ID: item.ID, Missing: true}
}
return relationBody{ID: item.ID, ContentType: item.ContentType, FirstField: firstFieldBody{Key: item.FirstField.Key, Type: item.FirstField.Type, Value: item.FirstField.Value}}
}
func toRelationsResponse(relations map[string]useCases.EntryRelations) map[string]any {
body := make(map[string]any, len(relations))
for key, held := range relations {
if !held.Many {
if len(held.Items) > 0 {
body[key] = toRelationItem(held.Items[0])
}
continue
}
items := make([]any, 0, len(held.Items))
for _, item := range held.Items {
items = append(items, toRelationItem(item))
}
body[key] = items
}
return body
}
type mediaBody struct {
ID uint32 `json:"id"`
Filename string `json:"filename"`
Width *int `json:"width"`
Height *int `json:"height"`
Size int64 `json:"size"`
ThumbnailURL string `json:"thumbnail_url"`
}
type missingMediaBody struct {
ID uint32 `json:"id"`
Missing bool `json:"missing"`
}
func toMediaResponse(media map[string]useCases.EntryMedia) map[string]any {
body := make(map[string]any, len(media))
for key, item := range media {
if item.Missing {
body[key] = missingMediaBody{ID: item.ID, Missing: true}
continue
}
body[key] = mediaBody{ID: item.ID, Filename: item.Filename, Width: item.Width, Height: item.Height, Size: item.Size, ThumbnailURL: item.ThumbnailURL}
}
return body
} }
func toResponse(typed useCases.TypedEntry) entryResponse { func toResponse(typed useCases.TypedEntry) entryResponse {
@@ -53,6 +123,8 @@ func toResponse(typed useCases.TypedEntry) entryResponse {
UpdatedBy: typed.UpdatedBy, UpdatedBy: typed.UpdatedBy,
CreatedAt: typed.CreatedAt, CreatedAt: typed.CreatedAt,
UpdatedAt: typed.UpdatedAt, UpdatedAt: typed.UpdatedAt,
Media: toMediaResponse(typed.Media),
Relations: toRelationsResponse(typed.Relations),
} }
} }
@@ -153,7 +225,7 @@ func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest) http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return return
} }
page, err := h.ListUseCase.ListPage(useCases.ListEntriesCommand{ContentTypeKey: chi.URLParam(r, "key"), Page: query.Page, Size: query.Size, Sort: query.Sort}) page, err := h.ListUseCase.ListPage(useCases.ListEntriesCommand{ContentTypeKey: chi.URLParam(r, "key"), Page: query.Page, Size: query.Size, Sort: query.Sort, Query: r.URL.Query().Get("q")})
if err != nil { if err != nil {
writeEntryError(w, err) writeEntryError(w, err)
return return
+20 -2
View File
@@ -92,9 +92,27 @@ func intQueryParam(values url.Values, name string, fallback int) (int, error) {
type usageResponse struct { type usageResponse struct {
Type string `json:"type"` Type string `json:"type"`
ID uint32 `json:"id"` ID uint32 `json:"id"`
Title string `json:"title"` Title string `json:"title,omitempty"`
Published *bool `json:"published,omitempty"` Published *bool `json:"published,omitempty"`
Fields []string `json:"fields"` Fields []string `json:"fields"`
ContentTypeKey string `json:"content_type_key,omitempty"`
ContentTypeName string `json:"content_type_name,omitempty"`
FirstField *usageFirstFieldBody `json:"first_field,omitempty"`
}
type usageFirstFieldBody struct {
Key string `json:"key"`
Type string `json:"type"`
Value any `json:"value"`
}
func toUsageResponse(usage useCases.MediaUsage) usageResponse {
body := usageResponse{Type: usage.Type, ID: usage.ID, Title: usage.Title, Published: usage.Published, Fields: usage.Fields, ContentTypeKey: usage.ContentTypeKey, ContentTypeName: usage.ContentTypeName}
if usage.FirstField != nil {
body.FirstField = &usageFirstFieldBody{Key: usage.FirstField.Key, Type: string(usage.FirstField.Type), Value: usage.FirstField.Value}
}
return body
} }
type mergeResponse struct { type mergeResponse struct {
@@ -347,7 +365,7 @@ func (h *Handler) Usage(w http.ResponseWriter, r *http.Request) {
response := make([]usageResponse, 0, len(usages)) response := make([]usageResponse, 0, len(usages))
for _, usage := range usages { for _, usage := range usages {
response = append(response, usageResponse{Type: usage.Type, ID: usage.ID, Title: usage.Title, Published: usage.Published, Fields: usage.Fields}) response = append(response, toUsageResponse(usage))
} }
writeJSON(w, http.StatusOK, response) writeJSON(w, http.StatusOK, response)
} }
+6 -18
View File
@@ -2,6 +2,7 @@ package middleware
import ( import (
"RenewCMS/api/pkg/apperr" "RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/authtoken"
"RenewCMS/internal/domain/apikey" "RenewCMS/internal/domain/apikey"
"RenewCMS/internal/infrastructure/useCases" "RenewCMS/internal/infrastructure/useCases"
"context" "context"
@@ -10,9 +11,6 @@ import (
"strconv" "strconv"
"strings" "strings"
"time" "time"
"github.com/go-chi/jwtauth/v5"
"github.com/lestrrat-go/jwx/v3/jwt"
) )
const bearerScheme = "bearer " const bearerScheme = "bearer "
@@ -79,13 +77,7 @@ func APIKeyAuth(authenticate *useCases.AuthenticateAPIKeyUseCase, maxRequests in
return return
} }
token, err := sessionTokenFor(authenticated) ctx := authtoken.NewContext(r.Context(), sessionClaimsFor(authenticated), nil)
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
ctx := jwtauth.NewContext(r.Context(), token, nil)
ctx = context.WithValue(ctx, apiKeyIdContextKey{}, authenticated.Key.ID) ctx = context.WithValue(ctx, apiKeyIdContextKey{}, authenticated.Key.ID)
ctx = context.WithValue(ctx, apiKeyNameContextKey{}, authenticated.Key.Name) ctx = context.WithValue(ctx, apiKeyNameContextKey{}, authenticated.Key.Name)
limited.ServeHTTP(w, r.WithContext(ctx)) limited.ServeHTTP(w, r.WithContext(ctx))
@@ -101,15 +93,11 @@ func writeAPIKeyError(w http.ResponseWriter, err error) {
http.Error(w, "Internal server error", http.StatusInternalServerError) http.Error(w, "Internal server error", http.StatusInternalServerError)
} }
func sessionTokenFor(authenticated useCases.AuthenticatedAPIKey) (jwt.Token, error) { func sessionClaimsFor(authenticated useCases.AuthenticatedAPIKey) authtoken.Claims {
token := jwt.New() return authtoken.Claims{
if err := token.Set("user_id", float64(authenticated.User.ID)); err != nil { "user_id": float64(authenticated.User.ID),
return nil, err "token_version": float64(authenticated.User.TokenVersion),
} }
if err := token.Set("token_version", float64(authenticated.User.TokenVersion)); err != nil {
return nil, err
}
return token, nil
} }
func apiKeyRateLimitKey(r *http.Request) string { func apiKeyRateLimitKey(r *http.Request) string {
+138
View File
@@ -0,0 +1,138 @@
package middleware
import (
"net/http"
"strconv"
"strings"
)
const (
corsAllowAnyOrigin = "*"
corsWildcardMarker = "*"
corsPreflightMaxAge = 300
corsPreflightSuccess = http.StatusNoContent
)
var (
corsAllowedMethods = []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodOptions}
corsAllowedHeaders = []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"}
corsExposedHeaders = []string{"Link", "X-Total-Count"}
)
type originWildcard struct {
prefix string
suffix string
}
func (w originWildcard) matches(origin string) bool {
return len(origin) >= len(w.prefix)+len(w.suffix) && strings.HasPrefix(origin, w.prefix) && strings.HasSuffix(origin, w.suffix)
}
type originPolicy struct {
anyOrigin bool
exact map[string]struct{}
wildcards []originWildcard
}
func newOriginPolicy(origins []string) originPolicy {
policy := originPolicy{exact: map[string]struct{}{}}
for _, origin := range origins {
origin = strings.ToLower(strings.TrimSpace(origin))
prefix, suffix, hasWildcard := strings.Cut(origin, corsWildcardMarker)
switch {
case origin == "":
case origin == corsAllowAnyOrigin:
policy.anyOrigin = true
case hasWildcard:
policy.wildcards = append(policy.wildcards, originWildcard{prefix: prefix, suffix: suffix})
default:
policy.exact[origin] = struct{}{}
}
}
return policy
}
func (p originPolicy) allows(origin string) bool {
if p.anyOrigin {
return true
}
origin = strings.ToLower(origin)
if _, ok := p.exact[origin]; ok {
return true
}
for _, wildcard := range p.wildcards {
if wildcard.matches(origin) {
return true
}
}
return false
}
func isPreflight(r *http.Request) bool {
return r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != ""
}
func containsFold(allowed []string, value string) bool {
for _, candidate := range allowed {
if strings.EqualFold(candidate, value) {
return true
}
}
return false
}
func requestedHeadersAllowed(r *http.Request) bool {
requested := r.Header.Get("Access-Control-Request-Headers")
if requested == "" {
return true
}
for _, header := range strings.Split(requested, ",") {
if header = strings.TrimSpace(header); header != "" && !containsFold(corsAllowedHeaders, header) {
return false
}
}
return true
}
func CORS(allowedOrigins []string) func(http.Handler) http.Handler {
policy := newOriginPolicy(allowedOrigins)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin == "" {
next.ServeHTTP(w, r)
return
}
w.Header().Add("Vary", "Origin")
if isPreflight(r) {
answerPreflight(w, r, origin, policy)
return
}
if policy.allows(origin) {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Expose-Headers", strings.Join(corsExposedHeaders, ", "))
}
next.ServeHTTP(w, r)
})
}
}
func answerPreflight(w http.ResponseWriter, r *http.Request, origin string, policy originPolicy) {
w.Header().Add("Vary", "Access-Control-Request-Method")
w.Header().Add("Vary", "Access-Control-Request-Headers")
method := r.Header.Get("Access-Control-Request-Method")
if !policy.allows(origin) || !containsFold(corsAllowedMethods, method) || !requestedHeadersAllowed(r) {
w.WriteHeader(http.StatusOK)
return
}
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", strings.ToUpper(method))
w.Header().Set("Access-Control-Allow-Headers", strings.Join(corsAllowedHeaders, ", "))
w.Header().Set("Access-Control-Max-Age", strconv.Itoa(corsPreflightMaxAge))
w.WriteHeader(corsPreflightSuccess)
}
+36
View File
@@ -0,0 +1,36 @@
package middleware
import (
"RenewCMS/api/pkg/apperr"
"net/http"
"net/url"
)
func CrossOriginProtection(publicURL string) func(http.Handler) http.Handler {
protection := http.NewCrossOriginProtection()
if origin, ok := originOf(publicURL); ok {
_ = protection.AddTrustedOrigin(origin)
}
protection.SetDenyHandler(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, apperr.CrossOriginErrorMessage, http.StatusForbidden)
}))
return func(next http.Handler) http.Handler {
protected := protection.Handler(next)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "" {
next.ServeHTTP(w, r)
return
}
protected.ServeHTTP(w, r)
})
}
}
func originOf(rawURL string) (string, bool) {
parsed, err := url.Parse(rawURL)
if err != nil || parsed.Scheme == "" || parsed.Host == "" {
return "", false
}
return parsed.Scheme + "://" + parsed.Host, true
}
+34 -12
View File
@@ -14,8 +14,19 @@ type rateLimitWindow struct {
count int count int
} }
type rateLimitCounters struct {
mu sync.Mutex
window time.Duration
windows map[string]*rateLimitWindow
lastSweep time.Time
}
func NewRateLimiter(maxAttempts int, window time.Duration) func(http.Handler) http.Handler { func NewRateLimiter(maxAttempts int, window time.Duration) func(http.Handler) http.Handler {
return newKeyedRateLimiter(maxAttempts, window, func(r *http.Request) string { return r.RemoteAddr }) return newKeyedRateLimiter(maxAttempts, window, connectionHostKey)
}
func connectionHostKey(r *http.Request) string {
return hostOf(r.RemoteAddr)
} }
func NewUserRateLimiter(maxAttempts int, window time.Duration) func(http.Handler) http.Handler { func NewUserRateLimiter(maxAttempts int, window time.Duration) func(http.Handler) http.Handler {
@@ -28,12 +39,11 @@ func userRateLimitKey(r *http.Request) string {
} }
func newKeyedRateLimiter(maxAttempts int, window time.Duration, keyOf func(*http.Request) string) func(http.Handler) http.Handler { func newKeyedRateLimiter(maxAttempts int, window time.Duration, keyOf func(*http.Request) string) func(http.Handler) http.Handler {
var mu sync.Mutex counters := &rateLimitCounters{window: window, windows: make(map[string]*rateLimitWindow)}
windows := make(map[string]*rateLimitWindow)
return func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
retryAfter, allowed := recordAttempt(&mu, windows, keyOf(r), maxAttempts, window) retryAfter, allowed := counters.recordAttempt(keyOf(r), maxAttempts, time.Now())
if !allowed { if !allowed {
w.Header().Set("Retry-After", strconv.Itoa(retryAfter)) w.Header().Set("Retry-After", strconv.Itoa(retryAfter))
http.Error(w, apperr.TooManyRequestsErrorMessage, http.StatusTooManyRequests) http.Error(w, apperr.TooManyRequestsErrorMessage, http.StatusTooManyRequests)
@@ -44,24 +54,36 @@ func newKeyedRateLimiter(maxAttempts int, window time.Duration, keyOf func(*http
} }
} }
func recordAttempt(mu *sync.Mutex, windows map[string]*rateLimitWindow, key string, maxAttempts int, window time.Duration) (int, bool) { func (c *rateLimitCounters) recordAttempt(key string, maxAttempts int, now time.Time) (int, bool) {
mu.Lock() c.mu.Lock()
defer mu.Unlock() defer c.mu.Unlock()
now := time.Now() c.sweepExpired(now)
current, exists := windows[key] current, exists := c.windows[key]
if !exists || now.Sub(current.start) >= window { if !exists || now.Sub(current.start) >= c.window {
current = &rateLimitWindow{start: now} current = &rateLimitWindow{start: now}
windows[key] = current c.windows[key] = current
} }
current.count++ current.count++
if current.count > maxAttempts { if current.count > maxAttempts {
return retryAfterSeconds(window - now.Sub(current.start)), false return retryAfterSeconds(c.window - now.Sub(current.start)), false
} }
return 0, true return 0, true
} }
func (c *rateLimitCounters) sweepExpired(now time.Time) {
if now.Sub(c.lastSweep) < c.window {
return
}
c.lastSweep = now
for key, current := range c.windows {
if now.Sub(current.start) >= c.window {
delete(c.windows, key)
}
}
}
func retryAfterSeconds(remaining time.Duration) int { func retryAfterSeconds(remaining time.Duration) int {
seconds := int(remaining / time.Second) seconds := int(remaining / time.Second)
if remaining%time.Second > 0 { if remaining%time.Second > 0 {
+2 -5
View File
@@ -2,16 +2,13 @@ package middleware
import ( import (
"RenewCMS/api/pkg/apperr" "RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/authtoken"
"net/http" "net/http"
"github.com/go-chi/jwtauth/v5"
"github.com/lestrrat-go/jwx/v3/jwt"
) )
func RequireSignedIn(next http.Handler) http.Handler { func RequireSignedIn(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, _, err := jwtauth.FromContext(r.Context()) if _, err := authtoken.FromContext(r.Context()); err != nil {
if err != nil || token == nil || jwt.Validate(token) != nil {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized) http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return return
} }
+2 -2
View File
@@ -4,8 +4,8 @@ import "net/http"
const contentSecurityPolicy = "default-src 'self'; " + const contentSecurityPolicy = "default-src 'self'; " +
"script-src 'self' 'wasm-unsafe-eval'; " + "script-src 'self' 'wasm-unsafe-eval'; " +
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " + "style-src 'self' 'unsafe-inline'; " +
"font-src 'self' https://fonts.gstatic.com; " + "font-src 'self'; " +
"img-src 'self' data: blob: https:; " + "img-src 'self' data: blob: https:; " +
"connect-src 'self'; " + "connect-src 'self'; " +
"object-src 'none'; " + "object-src 'none'; " +
+3
View File
@@ -16,6 +16,7 @@ const VerificationRequiredErrorMessage = "You must verify your account to access
const PasswordResetRequestedMessage = "If an account exists for that email, a password reset link has been sent." const PasswordResetRequestedMessage = "If an account exists for that email, a password reset link has been sent."
const PasswordResetFailedErrorMessage = "The password reset code is invalid or has expired." const PasswordResetFailedErrorMessage = "The password reset code is invalid or has expired."
const TooManyRequestsErrorMessage = "Too many requests. Please try again later." const TooManyRequestsErrorMessage = "Too many requests. Please try again later."
const CrossOriginErrorMessage = "Cross-origin requests are not allowed."
const EmailHasAccountErrorMessage = "This address already has an account." const EmailHasAccountErrorMessage = "This address already has an account."
const PendingInviteErrorMessage = "There's already a pending invite for this address." const PendingInviteErrorMessage = "There's already a pending invite for this address."
const InviteNotSentErrorMessage = "Couldn't send the invite. Try again in a moment." const InviteNotSentErrorMessage = "Couldn't send the invite. Try again in a moment."
@@ -25,6 +26,7 @@ const InviteInvalidErrorMessage = "This invite link doesn't work."
const InviteExpiredErrorMessage = "This invite has expired." const InviteExpiredErrorMessage = "This invite has expired."
const OwnerRequiredErrorMessage = "Only the owner can do this." const OwnerRequiredErrorMessage = "Only the owner can do this."
const UsernameTakenErrorMessage = "That username is taken. Try another." const UsernameTakenErrorMessage = "That username is taken. Try another."
const PasswordTooLongErrorMessage = "The password must be 72 bytes or fewer."
const MediaQueryErrorMessage = "The media query is invalid." const MediaQueryErrorMessage = "The media query is invalid."
const MediaFilenameErrorMessage = "Enter a filename." const MediaFilenameErrorMessage = "Enter a filename."
const MediaMergeConflictErrorMessage = "Some of the images to merge changed. Refresh and try again." const MediaMergeConflictErrorMessage = "Some of the images to merge changed. Refresh and try again."
@@ -90,6 +92,7 @@ const SlugSuggestionHeader = "X-Slug-Suggestion"
const ContentTypeNotFoundErrorMessage = "content_type_not_found" const ContentTypeNotFoundErrorMessage = "content_type_not_found"
const ContentTypeKeyTakenErrorMessage = "content_type_key_taken" const ContentTypeKeyTakenErrorMessage = "content_type_key_taken"
const ContentTypeHasEntriesErrorMessage = "content_type_has_entries" const ContentTypeHasEntriesErrorMessage = "content_type_has_entries"
const ContentTypeReferencedErrorMessage = "content_type_referenced"
const InvalidContentTypeKeyErrorMessage = "invalid_content_type_key" const InvalidContentTypeKeyErrorMessage = "invalid_content_type_key"
const InvalidIconErrorMessage = "invalid_icon" const InvalidIconErrorMessage = "invalid_icon"
const BuiltinTypeNotFoundErrorMessage = "builtin_type_not_found" const BuiltinTypeNotFoundErrorMessage = "builtin_type_not_found"
+225
View File
@@ -0,0 +1,225 @@
package authtoken
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"maps"
"strings"
"time"
)
const (
SessionLifetime = 24 * time.Hour
algorithmHS256 = "HS256"
tokenType = "JWT"
maxTokenBytes = 4096
segmentCount = 3
segmentSep = "."
)
var (
ErrNoToken = errors.New("no token found")
ErrInvalid = errors.New("token is invalid")
ErrExpired = errors.New("token is expired")
ErrNotYetValid = errors.New("token is not yet valid")
ErrRevoked = errors.New("token is revoked")
)
type RevocationStore interface {
Revoke(id string, expiresAt time.Time) error
IsRevoked(id string) (bool, error)
}
type Claims map[string]any
type header struct {
Algorithm string `json:"alg"`
Type string `json:"typ,omitempty"`
}
type Auth struct {
secret []byte
clock func() time.Time
revocations RevocationStore
}
type Option func(*Auth)
func WithClock(clock func() time.Time) Option {
return func(a *Auth) { a.clock = clock }
}
func WithRevocationStore(store RevocationStore) Option {
return func(a *Auth) { a.revocations = store }
}
func New(secret []byte, options ...Option) *Auth {
auth := &Auth{secret: secret, clock: time.Now}
for _, option := range options {
option(auth)
}
return auth
}
func (a *Auth) Encode(claims map[string]any) (string, error) {
payload := maps.Clone(claims)
if payload == nil {
payload = map[string]any{}
}
now := a.clock()
if _, ok := payload["iat"]; !ok {
payload["iat"] = now.Unix()
}
if _, ok := payload["exp"]; !ok {
payload["exp"] = now.Add(SessionLifetime).Unix()
}
if _, ok := payload["jti"]; !ok {
payload["jti"] = rand.Text()
}
headerSegment, err := encodeSegment(header{Algorithm: algorithmHS256, Type: tokenType})
if err != nil {
return "", err
}
payloadSegment, err := encodeSegment(payload)
if err != nil {
return "", err
}
signingInput := headerSegment + segmentSep + payloadSegment
return signingInput + segmentSep + a.sign(signingInput), nil
}
func (a *Auth) Decode(token string) (Claims, error) {
if token == "" {
return nil, ErrNoToken
}
if len(token) > maxTokenBytes {
return nil, ErrInvalid
}
segments := strings.Split(token, segmentSep)
if len(segments) != segmentCount {
return nil, ErrInvalid
}
var tokenHeader header
if err := decodeSegment(segments[0], &tokenHeader); err != nil || tokenHeader.Algorithm != algorithmHS256 {
return nil, ErrInvalid
}
signingInput := segments[0] + segmentSep + segments[1]
if !hmac.Equal([]byte(a.sign(signingInput)), []byte(segments[2])) {
return nil, ErrInvalid
}
var claims Claims
if err := decodeSegment(segments[1], &claims); err != nil || claims == nil {
return nil, ErrInvalid
}
if err := a.validateTimes(claims); err != nil {
return nil, err
}
if err := a.checkRevocation(claims); err != nil {
return nil, err
}
return claims, nil
}
func (a *Auth) Revoke(claims Claims) error {
id, ok := claims["jti"].(string)
if !ok || a.revocations == nil {
return nil
}
expiry, present, err := numericDate(claims, "exp")
if err != nil || !present {
return ErrInvalid
}
return a.revocations.Revoke(id, expiry)
}
func (a *Auth) checkRevocation(claims Claims) error {
raw, present := claims["jti"]
if !present {
return nil
}
id, ok := raw.(string)
if !ok {
return ErrInvalid
}
if a.revocations == nil {
return nil
}
revoked, err := a.revocations.IsRevoked(id)
if err != nil {
return errors.Join(ErrInvalid, err)
}
if revoked {
return ErrRevoked
}
return nil
}
func (a *Auth) validateTimes(claims Claims) error {
now := a.clock()
expiry, present, err := numericDate(claims, "exp")
if err != nil {
return err
}
if !present {
return ErrInvalid
}
if !now.Before(expiry) {
return ErrExpired
}
notBefore, present, err := numericDate(claims, "nbf")
if err != nil {
return err
}
if present && now.Before(notBefore) {
return ErrNotYetValid
}
return nil
}
func numericDate(claims Claims, name string) (time.Time, bool, error) {
raw, present := claims[name]
if !present {
return time.Time{}, false, nil
}
seconds, ok := raw.(float64)
if !ok {
return time.Time{}, false, ErrInvalid
}
return time.Unix(int64(seconds), 0), true, nil
}
func (a *Auth) sign(signingInput string) string {
mac := hmac.New(sha256.New, a.secret)
mac.Write([]byte(signingInput))
return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
}
func encodeSegment(value any) (string, error) {
encoded, err := json.Marshal(value)
if err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(encoded), nil
}
func decodeSegment(segment string, into any) error {
decoded, err := base64.RawURLEncoding.DecodeString(segment)
if err != nil {
return err
}
return json.Unmarshal(decoded, into)
}
+79
View File
@@ -0,0 +1,79 @@
package authtoken
import (
"RenewCMS/api/pkg/apperr"
"context"
"net/http"
"strings"
)
const (
CookieName = "jwt"
bearerPrefix = "bearer "
)
type contextKey struct{}
type verdict struct {
claims Claims
err error
}
func Verifier(auth *Auth) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
claims, err := auth.Decode(tokenFromRequest(r))
next.ServeHTTP(w, r.WithContext(NewContext(r.Context(), claims, err)))
})
}
}
func Authenticator(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := FromContext(r.Context()); err != nil {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
func NewContext(ctx context.Context, claims Claims, err error) context.Context {
return context.WithValue(ctx, contextKey{}, verdict{claims: claims, err: err})
}
func FromContext(ctx context.Context) (Claims, error) {
stored, ok := ctx.Value(contextKey{}).(verdict)
switch {
case !ok:
return nil, ErrNoToken
case stored.err != nil:
return nil, stored.err
case stored.claims == nil:
return nil, ErrNoToken
}
return stored.claims, nil
}
func tokenFromRequest(r *http.Request) string {
if token := tokenFromHeader(r); token != "" {
return token
}
return tokenFromCookie(r)
}
func tokenFromHeader(r *http.Request) string {
header := r.Header.Get("Authorization")
if len(header) <= len(bearerPrefix) || !strings.EqualFold(header[:len(bearerPrefix)], bearerPrefix) {
return ""
}
return header[len(bearerPrefix):]
}
func tokenFromCookie(r *http.Request) string {
cookie, err := r.Cookie(CookieName)
if err != nil {
return ""
}
return cookie.Value
}
+3 -4
View File
@@ -1,14 +1,13 @@
package claims package claims
import ( import (
"RenewCMS/api/pkg/authtoken"
"math" "math"
"net/http" "net/http"
"github.com/go-chi/jwtauth/v5"
) )
func UserId(r *http.Request) (uint32, bool) { func UserId(r *http.Request) (uint32, bool) {
_, claims, err := jwtauth.FromContext(r.Context()) claims, err := authtoken.FromContext(r.Context())
if err != nil { if err != nil {
return 0, false return 0, false
} }
@@ -31,7 +30,7 @@ func UserId(r *http.Request) (uint32, bool) {
} }
func TokenVersion(r *http.Request) (uint32, bool) { func TokenVersion(r *http.Request) (uint32, bool) {
_, claims, err := jwtauth.FromContext(r.Context()) claims, err := authtoken.FromContext(r.Context())
if err != nil { if err != nil {
return 0, false return 0, false
} }
+43 -47
View File
@@ -18,21 +18,23 @@ import (
"RenewCMS/api/handlers/update" "RenewCMS/api/handlers/update"
"RenewCMS/api/handlers/user" "RenewCMS/api/handlers/user"
"RenewCMS/api/middleware" "RenewCMS/api/middleware"
"RenewCMS/api/pkg/authtoken"
"RenewCMS/internal/infrastructure/config" "RenewCMS/internal/infrastructure/config"
"encoding/json" "encoding/json"
"log"
"net/http" "net/http"
"os"
"time" "time"
"github.com/MadAppGang/httplog"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
chimiddleware "github.com/go-chi/chi/v5/middleware" chimiddleware "github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
"github.com/go-chi/jwtauth/v5"
) )
func enableLoggingIfDev(r *chi.Mux, routerName string, environment string) { func enableLoggingIfDev(r *chi.Mux, routerName string, environment string) {
if environment == "development" { if environment == "development" {
r.Use(httplog.LoggerWithName(routerName)) r.Use(chimiddleware.RequestLogger(&chimiddleware.DefaultLogFormatter{
Logger: log.New(os.Stdout, "["+routerName+"] ", log.LstdFlags),
}))
} }
} }
@@ -68,7 +70,7 @@ func NewArticleRouter(container *UseCases, trustedProxies []string) http.Handler
r.Get("/{id}/seo", seoHandler.Resolve) r.Get("/{id}/seo", seoHandler.Resolve)
}) })
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Post("/", articleHandler.PostArticle) r.Post("/", articleHandler.PostArticle)
@@ -83,7 +85,7 @@ func NewArticleRouter(container *UseCases, trustedProxies []string) http.Handler
func NewAuthRouter(container *UseCases, isProduction bool, rateLimit config.AuthRateLimitSettings, trustedProxies []string) http.Handler { func NewAuthRouter(container *UseCases, isProduction bool, rateLimit config.AuthRateLimitSettings, trustedProxies []string) http.Handler {
r := chi.NewRouter() r := chi.NewRouter()
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
loginHandler := auth.NewLoginHandler(container.Token, container.CreateUserUseCase, container.AuthenticateUserUseCase, isProduction) loginHandler := auth.NewLoginHandler(container.Token, container.CreateUserUseCase, container.AuthenticateUserUseCase, isProduction)
@@ -114,16 +116,16 @@ func NewAuthRouter(container *UseCases, isProduction bool, rateLimit config.Auth
}) })
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(middleware.RequireSession) r.Use(middleware.RequireSession)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Post("/verify", verificationHandler.Verify) r.Post("/verify", verificationHandler.Verify)
r.Delete("/register", verificationHandler.CancelRegistration) r.Delete("/register", verificationHandler.CancelRegistration)
}) })
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(container.apiKeyAuth()) r.Use(container.apiKeyAuth())
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Get("/me", meHandler.Me) r.Get("/me", meHandler.Me)
}) })
@@ -137,10 +139,10 @@ func NewUserRouter(container *UseCases, rateLimit config.AuthRateLimitSettings,
lookupHandler := user.NewLookupHandler(container.LookupUserNamesUseCase) lookupHandler := user.NewLookupHandler(container.LookupUserNamesUseCase)
inviteHandler := user.NewInviteHandler(container.CreateInviteUseCase, container.CancelInviteUseCase, container.RenewInviteUseCase, container.ListUsersAndInvitesUseCase) inviteHandler := user.NewInviteHandler(container.CreateInviteUseCase, container.CancelInviteUseCase, container.RenewInviteUseCase, container.ListUsersAndInvitesUseCase)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(container.apiKeyAuth()) r.Use(container.apiKeyAuth())
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Patch("/me", userHandler.UpdateMe) r.Patch("/me", userHandler.UpdateMe)
@@ -163,19 +165,19 @@ func NewSettingsRouter(container *UseCases, trustedProxies []string) http.Handle
settingsHandler := settings.NewHandler(container.GetSettingsUseCase, container.GetActivityRetentionUseCase, container.UpdateActivityRetentionUseCase) settingsHandler := settings.NewHandler(container.GetSettingsUseCase, container.GetActivityRetentionUseCase, container.UpdateActivityRetentionUseCase)
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(container.apiKeyAuth()) r.Use(container.apiKeyAuth())
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Get("/", settingsHandler.GetSettings) r.Get("/", settingsHandler.GetSettings)
}) })
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(middleware.RequireSession) r.Use(middleware.RequireSession)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn) r.Use(middleware.RequireSignedIn)
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Use(middleware.RequireOwner(container.GetUserUseCase)) r.Use(middleware.RequireOwner(container.GetUserUseCase))
@@ -193,19 +195,19 @@ func NewSiteRouter(container *UseCases, trustedProxies []string) http.Handler {
r.Get("/{key}/sitemap", sitemapHandler.Sitemap) r.Get("/{key}/sitemap", sitemapHandler.Sitemap)
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(container.apiKeyAuth()) r.Use(container.apiKeyAuth())
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Get("/", siteHandler.List) r.Get("/", siteHandler.List)
}) })
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(middleware.RequireSession) r.Use(middleware.RequireSession)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn) r.Use(middleware.RequireSignedIn)
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Use(middleware.RequireOwner(container.GetUserUseCase)) r.Use(middleware.RequireOwner(container.GetUserUseCase))
@@ -223,19 +225,19 @@ func NewAuthorRouter(container *UseCases, trustedProxies []string) http.Handler
authorHandler := author.NewHandler(container.ListAuthorsUseCase, container.CreateAuthorUseCase, container.CreateMyAuthorUseCase, container.UpdateAuthorUseCase, container.DeleteAuthorUseCase, container.GetUserUseCase) authorHandler := author.NewHandler(container.ListAuthorsUseCase, container.CreateAuthorUseCase, container.CreateMyAuthorUseCase, container.UpdateAuthorUseCase, container.DeleteAuthorUseCase, container.GetUserUseCase)
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(container.apiKeyAuth()) r.Use(container.apiKeyAuth())
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Get("/", authorHandler.List) r.Get("/", authorHandler.List)
}) })
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(middleware.RequireSession) r.Use(middleware.RequireSession)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn) r.Use(middleware.RequireSignedIn)
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Post("/me", authorHandler.CreateMine) r.Post("/me", authorHandler.CreateMine)
@@ -256,11 +258,11 @@ func NewContentTypeRouter(container *UseCases, trustedProxies []string) http.Han
entryHandler := entry.NewHandler(container.CreateEntryUseCase, container.GetEntryUseCase, container.ListEntriesUseCase, container.UpdateEntryUseCase, container.DeleteEntryUseCase) entryHandler := entry.NewHandler(container.CreateEntryUseCase, container.GetEntryUseCase, container.ListEntriesUseCase, container.UpdateEntryUseCase, container.DeleteEntryUseCase)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(container.apiKeyAuth()) r.Use(container.apiKeyAuth())
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn) r.Use(middleware.RequireSignedIn)
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Get("/", contentTypeHandler.List) r.Get("/", contentTypeHandler.List)
@@ -284,11 +286,11 @@ func NewBuiltinTypeRouter(container *UseCases, trustedProxies []string) http.Han
builtinTypeHandler := builtintype.NewHandler(container.ListBuiltinTypesUseCase, container.GetBuiltinTypeUseCase) builtinTypeHandler := builtintype.NewHandler(container.ListBuiltinTypesUseCase, container.GetBuiltinTypeUseCase)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(container.apiKeyAuth()) r.Use(container.apiKeyAuth())
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn) r.Use(middleware.RequireSignedIn)
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Use(middleware.RequireOwnerOrAdmin(container.GetUserUseCase)) r.Use(middleware.RequireOwnerOrAdmin(container.GetUserUseCase))
@@ -303,10 +305,10 @@ func NewActivityRouter(container *UseCases, trustedProxies []string) http.Handle
activityHandler := activity.NewHandler(container.ListActivityUseCase, container.GetActivitySummaryUseCase, container.ExportActivityUseCase) activityHandler := activity.NewHandler(container.ListActivityUseCase, container.GetActivitySummaryUseCase, container.ExportActivityUseCase)
r.Use(middleware.RequireSession) r.Use(middleware.RequireSession)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn) r.Use(middleware.RequireSignedIn)
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Get("/", activityHandler.List) r.Get("/", activityHandler.List)
@@ -331,9 +333,9 @@ func NewSystemRouter(container *UseCases, trustedProxies []string) http.Handler
updateHandler := update.NewHandler(container.GetUpdateStatusUseCase, container.CheckForUpdateUseCase, container.StartUpdateDownloadUseCase, container.RequestRestartUseCase, container.GetUserUseCase) updateHandler := update.NewHandler(container.GetUpdateStatusUseCase, container.CheckForUpdateUseCase, container.StartUpdateDownloadUseCase, container.RequestRestartUseCase, container.GetUserUseCase)
r.Use(middleware.RequireSession) r.Use(middleware.RequireSession)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Get("/update", updateHandler.GetStatus) r.Get("/update", updateHandler.GetStatus)
@@ -360,9 +362,9 @@ func NewAPIKeyRouter(container *UseCases, trustedProxies []string) http.Handler
apiKeyHandler := apikey.NewHandler(container.CreateAPIKeyUseCase, container.ListAPIKeysUseCase, container.RevokeAPIKeyUseCase) apiKeyHandler := apikey.NewHandler(container.CreateAPIKeyUseCase, container.ListAPIKeysUseCase, container.RevokeAPIKeyUseCase)
r.Use(middleware.RequireSession) r.Use(middleware.RequireSession)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Post("/", apiKeyHandler.Create) r.Post("/", apiKeyHandler.Create)
@@ -376,11 +378,11 @@ func NewMediaRouter(container *UseCases, trustedProxies []string) http.Handler {
mediaHandler := media.NewHandler(container.CreateImageUseCase, container.ListMediaUseCase, container.RenameMediaUseCase, container.DeleteMediaUseCase, container.MergeMediaUseCase, container.GetMediaUsageUseCase, container.GetPurgeSettingsUseCase, container.UpdatePurgeSettingsUseCase, container.PreviewPurgeUseCase, container.RunPurgeUseCase, container.ListImageVariantsUseCase, container.GenerateImageVariantUseCase, container.GenerateAllImageVariantsUseCase, container.PurgeImageVariantUseCase, container.GenerateVariantsOnUploadUseCase) mediaHandler := media.NewHandler(container.CreateImageUseCase, container.ListMediaUseCase, container.RenameMediaUseCase, container.DeleteMediaUseCase, container.MergeMediaUseCase, container.GetMediaUsageUseCase, container.GetPurgeSettingsUseCase, container.UpdatePurgeSettingsUseCase, container.PreviewPurgeUseCase, container.RunPurgeUseCase, container.ListImageVariantsUseCase, container.GenerateImageVariantUseCase, container.GenerateAllImageVariantsUseCase, container.PurgeImageVariantUseCase, container.GenerateVariantsOnUploadUseCase)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(container.apiKeyAuth()) r.Use(container.apiKeyAuth())
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn) r.Use(middleware.RequireSignedIn)
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
@@ -413,10 +415,10 @@ func NewImageVariantRouter(container *UseCases, trustedProxies []string) http.Ha
variantHandler := imagevariant.NewHandler(container.ListVariantsUseCase, container.CreateVariantUseCase, container.UpdateVariantUseCase, container.SetVariantEnabledUseCase, container.DeleteVariantUseCase, container.PurgeVariantUseCase, container.GetVariantCacheStatsUseCase, container.PurgeVariantCacheUseCase) variantHandler := imagevariant.NewHandler(container.ListVariantsUseCase, container.CreateVariantUseCase, container.UpdateVariantUseCase, container.SetVariantEnabledUseCase, container.DeleteVariantUseCase, container.PurgeVariantUseCase, container.GetVariantCacheStatsUseCase, container.PurgeVariantCacheUseCase)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn) r.Use(middleware.RequireSignedIn)
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Use(middleware.RequireOwnerOrAdmin(container.GetUserUseCase)) r.Use(middleware.RequireOwnerOrAdmin(container.GetUserUseCase))
@@ -440,7 +442,7 @@ func InitBackendRoutes(container *UseCases, settings config.Settings) *chi.Mux {
r.Use(middleware.JsonContentTypeMiddleware) r.Use(middleware.JsonContentTypeMiddleware)
r.Get("/", GetHelloWorld) r.Get("/", GetHelloWorld)
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Mount("/article", NewArticleRouter(container, settings.TrustedProxies)) r.Mount("/article", NewArticleRouter(container, settings.TrustedProxies))
}) })
r.Mount("/user", NewUserRouter(container, settings.AuthRateLimit, settings.TrustedProxies)) r.Mount("/user", NewUserRouter(container, settings.AuthRateLimit, settings.TrustedProxies))
@@ -478,14 +480,7 @@ func enableCorsIfConfigured(r *chi.Mux, origins []string) {
if len(origins) == 0 { if len(origins) == 0 {
return return
} }
r.Use(cors.Handler(cors.Options{ r.Use(middleware.CORS(origins))
AllowedOrigins: origins,
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link", "X-Total-Count"},
AllowCredentials: false,
MaxAge: 300,
}))
} }
func InitRoutes(container *UseCases, settings config.Settings) *chi.Mux { func InitRoutes(container *UseCases, settings config.Settings) *chi.Mux {
@@ -495,6 +490,7 @@ func InitRoutes(container *UseCases, settings config.Settings) *chi.Mux {
apiRouter := chi.NewRouter() apiRouter := chi.NewRouter()
apiRouter.Use(middleware.SecurityHeaders(settings.IsProduction())) apiRouter.Use(middleware.SecurityHeaders(settings.IsProduction()))
enableCorsIfConfigured(apiRouter, settings.CorsAllowedOrigins) enableCorsIfConfigured(apiRouter, settings.CorsAllowedOrigins)
apiRouter.Use(middleware.CrossOriginProtection(settings.PublicURL))
apiRouter.Use(chimiddleware.GetHead) apiRouter.Use(chimiddleware.GetHead)
apiRouter.Get("/healthz", GetHealth) apiRouter.Get("/healthz", GetHealth)
apiRouter.Mount("/v1", backend) apiRouter.Mount("/v1", backend)
+7 -3
View File
@@ -7,6 +7,7 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"io/fs"
"log" "log"
"net" "net"
"net/http" "net/http"
@@ -15,8 +16,6 @@ import (
"slices" "slices"
"syscall" "syscall"
"time" "time"
"github.com/joho/godotenv"
) )
var version = "dev" var version = "dev"
@@ -59,6 +58,7 @@ var envDefaults = map[string]string{
"AUTH_RATE_LIMIT_MAX_ATTEMPTS": "5", "AUTH_RATE_LIMIT_MAX_ATTEMPTS": "5",
"AUTH_RATE_LIMIT_WINDOW_SECONDS": "60", "AUTH_RATE_LIMIT_WINDOW_SECONDS": "60",
"TRUSTED_PROXIES": "", "TRUSTED_PROXIES": "",
config.EnvSmtpAllowInsecure: config.DefaultSmtpAllowInsecure,
"UPDATE_FEED_URL": "https://git.floriansylvain.fr", "UPDATE_FEED_URL": "https://git.floriansylvain.fr",
"RENEWCMS_CONTAINER": "false", "RENEWCMS_CONTAINER": "false",
config.EnvImageVariantMaxSourceBytes: config.DefaultImageVariantMaxSourceBytes, config.EnvImageVariantMaxSourceBytes: config.DefaultImageVariantMaxSourceBytes,
@@ -106,9 +106,13 @@ func initEnvVariables() {
func loadEnvFile() { func loadEnvFile() {
for _, envLocation := range possibleEnvFileLocations { for _, envLocation := range possibleEnvFileLocations {
if godotenv.Load(envLocation) == nil { err := config.LoadDotenv(envLocation)
if err == nil {
return return
} }
if !errors.Is(err, fs.ErrNotExist) {
log.Println("WARNING: Could not parse env file:", err)
}
} }
log.Println("WARNING: Could not load any .env file") log.Println("WARNING: Could not load any .env file")
} }
+6
View File
@@ -21,6 +21,12 @@ for example `https://cms.example/v1/article/`.
or revoked key answers 401, even on public routes. The site writes (`POST`, `PATCH` and `DELETE` or revoked key answers 401, even on public routes. The site writes (`POST`, `PATCH` and `DELETE`
under `/v1/site`) and the author writes (`POST`, `PATCH` and `DELETE` under `/v1/author`, `POST /v1/author/me` included) are session only too. under `/v1/site`) and the author writes (`POST`, `PATCH` and `DELETE` under `/v1/author`, `POST /v1/author/me` included) are session only too.
- Each key can make 120 requests per minute. Beyond that: 429 with a `Retry-After` header. - Each key can make 120 requests per minute. Beyond that: 429 with a `Retry-After` header.
- A session lasts 24 hours. `POST /v1/auth/logout` revokes it on the server, so a copied cookie
stops working at once; other sessions of the same user stay valid. A password reset ends every
session and revokes every key of that user.
- A browser `POST`, `PUT`, `PATCH` or `DELETE` sent from another origin without an
`Authorization` header answers 403 "Cross-origin requests are not allowed." This blocks
cross-site request forgery with the cookie; scripts on other origins must send their key.
## Routes a key can call (30) ## Routes a key can call (30)
| Group | Routes | | Group | Routes |
+9 -1
View File
@@ -55,6 +55,14 @@ The use cases `GetPurgeSettings`, `UpdatePurgeSettings`, `PreviewPurge` and `Run
| `GET /v1/media/purge-preview` | Groups, copies, distinct articles, the first 5 groups, `more` and the fingerprint. | | `GET /v1/media/purge-preview` | Groups, copies, distinct articles, the first 5 groups, `more` and the fingerprint. |
| `POST /v1/media/purge` | Runs the purge. Optional `fingerprint`; 409 when stale or when a run is in progress. | | `POST /v1/media/purge` | Runs the purge. Optional `fingerprint`; 409 when stale or when a run is in progress. |
### Sessions and personal data retention
A session is an HS256 token from `api/pkg/authtoken`. `Encode` adds a random `jti` and an `exp` 24 hours ahead; `Decode` refuses a token without `exp`. `authtoken.WithRevocationStore` plugs in `useCases.SessionRevocationUseCase`, which stores a `session.Revocation` (`jti`, `exp`) through the `internal/domain/session` `Repository` (`persistence.RevokedSessionRepository`, table `revoked_sessions`). `LoginHandler.Logout` revokes the presented token; from then on `Decode` answers `ErrRevoked` for it, and a store that cannot be read makes every token invalid rather than valid. Revoking every session of a user stays the job of `token_version`, bumped by a password reset.
`useCases.EnforceRetentionUseCase.Tick(now)` deletes revocations past their expiry, unverified accounts 7 days after their code expired (`user.UnverifiedRetention`) and invites 30 days after they expired or were accepted (`invite.Retention`), and returns a `retention.Result`. `scheduler.NewSystemRetentionRunner` calls it one minute after startup and then hourly, logs one line only when something was removed, and stops with the other runners on shutdown.
Uploads go through the `image.MetadataStripper` port before they are measured for size, hashed and stored. `imaging.MetadataStripper` walks the JPEG segments, PNG chunks and WebP RIFF chunks without re-encoding pixels, drops metadata, keeps colour profiles and re-adds an orientation-only EXIF block when the photo was rotated. A container it cannot walk fails the upload with `image.ErrImageUnreadable`.
### Activity log ### Activity log
`internal/domain/audit` holds the append-only `Event` (actor, target and failure-reason snapshots, outcome, security flag, source, ip, user agent, `params` and `changes`), the closed vocabularies (actor type, category, outcome, source, change kind), the `Filter`, `Summary` and `Settings` types, the `Repository` interface (`Append`, `List`, `Summary`, `DeleteOlderThan`: no way to edit or delete one event), the `SettingsRepository` (`Get`, `SaveRetention`, `SaveLastCleanup`; no row means 90 days) and the sentinels `ErrInvalidFilter`, `ErrInvalidRetention`, `ErrInvalidEvent` and `ErrActorNotAllowed`. The `Recorder` port is `Record(ctx, event)`; it returns nothing, so a caller can never fail on it. `internal/domain/audit` holds the append-only `Event` (actor, target and failure-reason snapshots, outcome, security flag, source, ip, user agent, `params` and `changes`), the closed vocabularies (actor type, category, outcome, source, change kind), the `Filter`, `Summary` and `Settings` types, the `Repository` interface (`Append`, `List`, `Summary`, `DeleteOlderThan`: no way to edit or delete one event), the `SettingsRepository` (`Get`, `SaveRetention`, `SaveLastCleanup`; no row means 90 days) and the sentinels `ErrInvalidFilter`, `ErrInvalidRetention`, `ErrInvalidEvent` and `ErrActorNotAllowed`. The `Recorder` port is `Record(ctx, event)`; it returns nothing, so a caller can never fail on it.
@@ -95,7 +103,7 @@ Media usage has more sources than article bodies: `Article.CoverImageID` and `So
`internal/domain/image` holds the `Variant` entity and its rules (`VariantSettings.Normalized`, the settings `Fingerprint`, `VariantETag`, `ETagMatches`, `IsAnimatedGIF`), the sentinels (`ErrVariantNotFound`, `ErrVariantExists`, `ErrVariantInvalid`, `ErrVariantFormatUnavailable`, `ErrUnknownVariant`, `ErrUnsupportedParameter`, `ErrSourceTooLarge`) and three ports: `VariantRepository` (definitions), `VariantFileRepository` (the index of generated files: variant name, source stored name, cached stored name, content type, size and the settings fingerprint, needed because `Storage.Put` chooses the stored name itself) and `VariantRenderer` (decode a source, encode a variant, report the formats it can encode). `internal/infrastructure/imaging` is the renderer adapter, free of GORM and HTTP; the persistence adapters are `VariantRepository` and `VariantFileRepository` over `models.ImageVariant` and `models.ImageVariantFile`. `internal/domain/image` holds the `Variant` entity and its rules (`VariantSettings.Normalized`, the settings `Fingerprint`, `VariantETag`, `ETagMatches`, `IsAnimatedGIF`), the sentinels (`ErrVariantNotFound`, `ErrVariantExists`, `ErrVariantInvalid`, `ErrVariantFormatUnavailable`, `ErrUnknownVariant`, `ErrUnsupportedParameter`, `ErrSourceTooLarge`) and three ports: `VariantRepository` (definitions), `VariantFileRepository` (the index of generated files: variant name, source stored name, cached stored name, content type, size and the settings fingerprint, needed because `Storage.Put` chooses the stored name itself) and `VariantRenderer` (decode a source, encode a variant, report the formats it can encode). `internal/infrastructure/imaging` is the renderer adapter, free of GORM and HTTP; the persistence adapters are `VariantRepository` and `VariantFileRepository` over `models.ImageVariant` and `models.ImageVariantFile`.
Generated bytes are stored only through `image.Storage`, so they follow `STORAGE_DRIVER`, and are never rows of `images`. `ServeVariantUseCase` checks, in order: unsupported parameters, the variant (it must exist and be enabled), the source blob, SVG and animated GIF (served as they are), the size cap, the `If-None-Match` ETag, then the cached file, and generates under a `singleflight` keyed by variant, settings and source. A row whose fingerprint no longer matches, or whose blob vanished, is replaced. `UpdateVariantUseCase` purges a variant's files when a rendering setting changes; `DeleteVariantUseCase` and `PurgeVariantUseCase` purge a blob and then its row, so a failed blob delete keeps the row and a retry can finish; `mediaRemover` purges the files of a source before it deletes the source (delete and merge). Generated bytes are stored only through `image.Storage`, so they follow `STORAGE_DRIVER`, and are never rows of `images`. `ServeVariantUseCase` checks, in order: unsupported parameters, the variant (it must exist and be enabled), the source blob, SVG and animated GIF (served as they are), the size cap, the `If-None-Match` ETag, then the cached file, and generates under an in-process single-flight group keyed by variant, settings and source. A row whose fingerprint no longer matches, or whose blob vanished, is replaced. `UpdateVariantUseCase` purges a variant's files when a rendering setting changes; `DeleteVariantUseCase` and `PurgeVariantUseCase` purge a blob and then its row, so a failed blob delete keeps the row and a retry can finish; `mediaRemover` purges the files of a source before it deletes the source (delete and merge).
The cache screen adds three ports in `internal/domain/image`: `VariantCacheRepository` (unused totals, top sources by bytes and cursor-paged row listing, implemented by the same persistence type as `VariantFileRepository`), `VariantUsageRepository` (one batched write of request times and per-day rejection counts, and the rejection total of a window) and `VariantUsageTracker` (in-memory hits and rejections). `internal/infrastructure/usage.Tracker` implements the tracker; `GetVariantCacheStatsUseCase` and `PurgeVariantCacheUseCase` use the ports only. See [image-variants.md](image-variants.md). The cache screen adds three ports in `internal/domain/image`: `VariantCacheRepository` (unused totals, top sources by bytes and cursor-paged row listing, implemented by the same persistence type as `VariantFileRepository`), `VariantUsageRepository` (one batched write of request times and per-day rejection counts, and the rejection total of a window) and `VariantUsageTracker` (in-memory hits and rejections). `internal/infrastructure/usage.Tracker` implements the tracker; `GetVariantCacheStatsUseCase` and `PurgeVariantCacheUseCase` use the ports only. See [image-variants.md](image-variants.md).
-108
View File
@@ -1,108 +0,0 @@
# Claude Design prompt: custom content types
Paste everything below the line into Claude Design, with the existing RenewCMS design system attached.
---
You are extending the RenewCMS back-office design. RenewCMS is a small self-hosted CMS (Go API plus a Vue 3 SPA built with Nuxt UI v4 and Tailwind 4). The existing screens, the AppFrame back-office shell, the AuthCard auth frames, the design tokens and the component inventory are already in this design system: reuse them, never invent new colors, spacing, radius or type values, and keep the same copy tone (short, plain, sentence case). Deliver the same artifacts the system already uses: one board per screen with every state, the exact copy per state, the routes with their auth requirement, the new components with their Nuxt UI mapping, and light and dark variants at desktop (1440x900) and mobile (390x844).
## The feature
Until now RenewCMS only managed fixed content: articles, authors, sites, media and users. We are adding custom content types: an owner or admin defines a content type (for example "Recipe" or "Event") made of ordered fields, and then any verified user creates entries of that type. Think of the clear part of Directus: a type is a collection, a field is a typed column. Do not copy Strapi's split between collections, components and fields into separate screens: everything about a type happens on one screen. Do not draw a table-builder feel with database jargon; speak in terms of content.
The backend for the first part already exists. Design the full experience including the parts that come later, and mark each screen or state as "available now" or "later" (see the scope table).
## What the backend does today (design against this, do not contradict it)
Routes, all behind the normal signed-in, verified-user back-office session (cookie or API key):
- GET /v1/content-type: list of types, ordered by name.
- POST /v1/content-type, PUT /v1/content-type/{key}, DELETE /v1/content-type/{key}: owner or admin only.
- GET /v1/content-type/{key}.
- GET and POST /v1/content-type/{key}/entry; GET, PUT and DELETE /v1/content-type/{key}/entry/{id}. Any verified user.
A content type: id, key, name, fields, created_at, updated_at.
- key: lowercase slug, 2 to 40 characters, unique, chosen at creation, never editable afterwards. It appears in URLs and the API.
- name: free text, up to 100 characters, editable.
- fields: ordered list, 1 to 50 fields.
A field: key, label, type, required, unique, default, min, max, options.
- key: lowercase letters, digits and underscores, starts with a letter, up to 40 characters, unique within the type. It becomes the JSON key in the API.
- label: the text shown in the editor.
- type: one of text, richtext (markdown), number, boolean, date (a calendar date, no time), select (a single choice from a list of 1 to 50 distinct options).
- required, unique (text, number, date and select only), default (applied only when an entry is created and the field is omitted), min and max.
- min and max mean: length in characters for text and richtext, value for number, earliest and latest date for date. They do not exist for boolean and select. min must not exceed max. A default must satisfy the field's own rules. A unique field cannot have a default.
- A field's type can never change after the type is saved, and the type key never changes.
An entry: id, content_type (the type's key), data (an object keyed by field key), created_by, updated_by, created_at, updated_at.
- Saving an entry replaces its whole data. Defaults apply only on create. An explicit empty value stays empty, and a required field cannot be empty.
- Unknown keys are rejected. Values of a removed field disappear.
Schema changes once entries exist:
- Removing a field is allowed; its stored values stop being returned.
- Every existing entry is re-validated against the new schema. If any entry would become invalid (a new required field without a default, a field made unique while duplicates exist, a tighter min or max below a stored value, a removed option still in use), the whole change is refused as incompatible and nothing changes.
- Adding a required field is fine if it has a default.
- A type that has entries cannot be deleted.
Entry lists are paginated: page size 5, 25, 50 or 100 (default 25), sort by id, created_at or updated_at in either direction (default most recently updated first). There is no filtering or search on custom fields yet.
Errors come back as plain text. Map each to friendly copy:
- content_type_not_found, entry_not_found
- content_type_key_taken
- content_type_has_entries
- invalid_content_type_key
- invalid_field
- schema_incompatible
- "invalid_entry: <field key>: <rule>", rule being one of required, type, min, max, options, unique, unknown_field. Unique violations arrive as HTTP 409, the other entry rules as 422.
- The usual 401, 403 (unverified account or insufficient role), 400 and 500 already covered in the system's HTTP-status-to-copy table.
## Screens to design
For each screen: every state (loading, empty, populated, error, forbidden, offline or failed save where relevant), the exact copy, the routes and their auth requirement, and a mobile layout.
### 1. Schema screen: list of types (available now)
Sits in the back-office navigation as "Schema", visible to owners and admins; other verified users do not see it. Shows the types as a list or table: name, key, number of fields, last updated. Shows the built-in types (Articles, Authors, Sites, Media, Users) in the same list with a "Built-in" badge and a lock icon. Built-ins are read-only entries here: they open a read-only view listing their fields, with no edit, no delete and no ability to add fields. Do not suggest that built-ins are custom collections; the badge and a one-line explanation make clear they are managed by RenewCMS. Primary action "New content type". States: loading, empty (no custom type yet: invite the user to create one, built-ins still listed), populated, error, forbidden (non-admin who types the URL).
### 2. Schema builder (available now, the main screen)
One screen with three regions, not three separate areas:
- Left: the ordered field list. Reorder (drag with a keyboard-accessible alternative), add field, remove field. Each row shows label, key, type icon and small badges for required and unique.
- Right: the field inspector for the selected field: label, key (generated from the label, editable until the type is first saved, then locked), type (a gallery of the six types with icon and one-line description), required, unique (disabled with an explanation where not allowed), default, min and max (with the right unit wording per type), and for select an options editor (add, remove, reorder, no duplicates, no blanks). Show the rules inline as the user types, not only after save.
- Top: type name, type key (editable only at creation; afterwards locked with a tooltip explaining why), Save and Discard.
- Live API preview: a collapsible panel showing the exact JSON an entry of this type looks like (a sample entry using each field's type and default) and the route it lives at, updating as fields change. Include a copy button.
States: new type, editing an existing type, unsaved changes, validation errors per field and at type level (inline, with the field highlighted in the list), saving, saved, save failed, key already taken, schema incompatible with existing entries.
### 3. Schema change review (available now for the review step, later for the diff)
Before saving changes to a type that already has entries, show a review step: "Add 2 fields, change 1, remove 1", listing each change, with destructive ones (removing a field, removing an option, tightening a limit, making a field unique or required) clearly flagged. Because the server decides compatibility, the review is informational plus an explicit Apply button; if the server answers schema incompatible, show a refusal state that says nothing was changed and which kind of change likely caused it (we cannot tell which entry, so write copy that does not pretend to). Also design the "delete type" confirmation: blocked when entries exist (explain that entries must be deleted first) and a plain confirmation when empty. Mark per-change entry counts and a full diff as "later" (the API does not return them yet).
### 4. Field-type gallery (available now)
A reference board for the six field types showing, for each: its icon, its inspector options, its list cell (how a value renders in the entries table, including the empty state), its form control in the entry editor (markdown editor for richtext with preview, number input with min and max hints, toggle for boolean using the system's single toggle component, date picker, select, text with a character counter when a limit exists), and its error states per rule (required, type, min, max, options, unique). Show the "filter" widget for each type as "later" since filtering on custom fields is not available yet.
### 5. Content navigation and entry list (available now)
The back-office sidebar gets a "Content" group generated from the custom types, one entry per type (name, with the type's icon if any; truncated gracefully with many types; collapsed on mobile). The list screen for a type shows a paginated table with a column per field (cap the visible columns and let the user choose which, defaulting to the first few), plus created and updated dates and the author of the last change. Sort control (id, created, updated), page size selector (5, 25, 50, 100), "New entry" button. Row click opens the editor. States: loading, empty for this type (with a hint pointing to "New entry"), populated, error, forbidden, type not found.
Use a sample "Events" type for all boards: title (text, required, unique, max 80), starts_on (date, required), ends_on (date), online (boolean, default false), capacity (number, min 1, max 5000), category (select: Talk, Workshop, Meetup), description (richtext).
### 6. Entry editor (available now)
Create and edit form generated from the schema, one control per field in schema order, with labels, required markers, helper text from min, max and options, a character counter where a limit exists, and inline errors per field. Show defaults pre-filled on create. Save, Cancel, Delete (with confirmation). Provenance footer: created by, updated by, dates. States: new, editing, unsaved changes, saving, saved, failed save, field errors for each rule, duplicate unique value (409), entry not found, concurrent schema change (a field disappeared or a new required field appeared since the form loaded: explain that the form must be reloaded).
### 7. Relation field and sentence-style relation picker (later, design now)
Relations are not built yet. Design the picker so that the model reads as sentences, not jargon: "Each Event has one Venue" and, beside it, "Each Venue has many Events", with a live preview of both sides. Offer the three relationship shapes in plain words. Show how a relation field renders in the inspector, the entry form (search and pick, with chips for many) and the list cell. Mark everything "later".
### 8. Permissions grid (later, design now)
A collection by action grid on the roles area: rows are types (custom and built-in), columns are read, create, update and delete, per role. Built-in rows are locked where the system dictates it. Make the grid usable on mobile (collapse to a per-role list). Mark "later". Today's rule is simple: owners and admins edit schema, any verified user reads and writes entries; show that as the default state of the grid.
### 9. Schema export and import (later, design now)
Export the whole schema or a single type to a file, import with a preview of what will be created or changed and the same compatibility review as screen 3, plus an explicit confirm. Aim at the dev-to-production flow. Mark "later".
## Scope table to include in your answer
For every screen and state, label it "available now" or "later" so engineering knows what is wired. Available now: screens 1 to 6 (except the diff counts), the live API preview, the type-level and field-level validation states. Later: relation picker, permissions grid, schema export and import, filters on custom fields, per-change entry counts, publish and draft state, public (anonymous) read access, activity log entries for types and entries.
## Constraints
- Nuxt UI v4 only, mapped to existing components in the inventory. List every new component you introduce with its Nuxt UI mapping and why an existing one does not fit.
- Tokens only. No raw hex values and no arbitrary Tailwind colors.
- Accessibility: keyboard reorder for fields, focus order, visible focus, labels on every control, error text tied to its input, sufficient contrast in light and dark.
- Copy: short and plain, no database jargon in primary labels (say "field", "choice list", "entry", "content type"; keep "key" for the API identifier and explain it once).
- Do not redesign existing screens. Only add what these screens need: new sidebar group, new routes, new components.
- Provide the routes table: /schema, /schema/new, /schema/:key, /content/:key, /content/:key/new, /content/:key/:id, each with its auth requirement (schema routes owner or admin, content routes any verified user).
- Anything the API cannot do today (see above) must not appear as if it works. If a design needs a backend capability that does not exist, flag it explicitly in a short "needs backend" list at the end.
+4 -3
View File
@@ -1,6 +1,6 @@
# Configuration # Configuration
RenewCMS reads its configuration from environment variables. On startup it also loads a `.env` file from the working directory (or its parent) if one exists. Real environment variables take precedence over `.env`. RenewCMS reads its configuration from environment variables. On startup it also loads a `.env` file from the working directory (or its parent) if one exists. Real environment variables take precedence over `.env`. The parser reads `NAME=value` lines, an optional `export ` prefix, `#` comments (inline ones need a space before the `#`), and single- or double-quoted values (`\n`, `\t`, `\"` and `\\` are unescaped in double quotes). It does not expand `$VARIABLES` and does not support multi-line values. A malformed line makes the whole file ignored, and the server logs the line number.
Copy [`.env.example`](../.env.example) to `.env` to get started. When a required variable is missing, the server refuses to start and names the variable. Copy [`.env.example`](../.env.example) to `.env` to get started. When a required variable is missing, the server refuses to start and names the variable.
@@ -11,7 +11,7 @@ Copy [`.env.example`](../.env.example) to `.env` to get started. When a required
| Name | Description | Example | | Name | Description | Example |
|-----------------|---------------------------------------------------------------------------------------------------------------------|----------------------------| |-----------------|---------------------------------------------------------------------------------------------------------------------|----------------------------|
| `PUBLIC_URL` | Public base URL of the site, including scheme and no trailing slash. Used for links in emails and in the startup log. It is also the CMS's own address: at the first migration, when the sites table is empty, it seeds the default site (name "Default", key "default") with its scheme and host (path dropped, non-loopback `http` upgraded to `https`); an unparseable value stops the migration. It is never read for sites afterwards. | `https://cms.example.com` | | `PUBLIC_URL` | Public base URL of the site, including scheme and no trailing slash. Used for links in emails and in the startup log. It is also the CMS's own address: at the first migration, when the sites table is empty, it seeds the default site (name "Default", key "default") with its scheme and host (path dropped, non-loopback `http` upgraded to `https`); an unparseable value stops the migration. It is never read for sites afterwards. | `https://cms.example.com` |
| `JWT_SECRET` | Secret used to sign the auth JWT. Use a long random value; changing it logs everyone out. | `openssl rand -hex 32` | | `JWT_SECRET` | Secret used to sign the auth JWT. It must be at least 32 bytes, and the example values from `.env.example` and `docker.env.example` are refused: the server stops at startup with `JWT_SECRET is too weak` and how to generate one. Changing it logs everyone out. | `openssl rand -hex 32` |
| `SMTP_LOGIN` | SMTP username used to authenticate with the server. Some providers (e.g. Brevo) issue a login distinct from the sender address. | `noreply@example.com` | | `SMTP_LOGIN` | SMTP username used to authenticate with the server. Some providers (e.g. Brevo) issue a login distinct from the sender address. | `noreply@example.com` |
| `SMTP_SENDER` | Sender address used in the `From` header. Must be an address/domain the SMTP provider allows that login to send as. | `noreply@example.com` | | `SMTP_SENDER` | Sender address used in the `From` header. Must be an address/domain the SMTP provider allows that login to send as. | `noreply@example.com` |
| `SMTP_PASSWORD` | SMTP password. | | | `SMTP_PASSWORD` | SMTP password. | |
@@ -29,9 +29,10 @@ Copy [`.env.example`](../.env.example) to `.env` to get started. When a required
| `DATA_DIR` | directory of `DB_FILE` | Directory for update state, staged updates and database backups (`backups/`). Set it with `DB_DRIVER=mysql` or `postgres`, where there is no database file to sit beside (the default still follows `DB_FILE`). With SQLite, leave it unset to keep everything beside the database. | | `DATA_DIR` | directory of `DB_FILE` | Directory for update state, staged updates and database backups (`backups/`). Set it with `DB_DRIVER=mysql` or `postgres`, where there is no database file to sit beside (the default still follows `DB_FILE`). With SQLite, leave it unset to keep everything beside the database. |
| `STORAGE_DRIVER` | `local` | `local` (files in `UPLOAD_DIR`) or `s3` (an S3-compatible bucket). Any other value stops the server with `unsupported storage driver "<value>"`. See [Image storage](#image-storage). | | `STORAGE_DRIVER` | `local` | `local` (files in `UPLOAD_DIR`) or `s3` (an S3-compatible bucket). Any other value stops the server with `unsupported storage driver "<value>"`. See [Image storage](#image-storage). |
| `UPLOAD_DIR` | `./data/uploads` | Directory where uploaded images are stored. Ignored, without error, when `STORAGE_DRIVER=s3`. | | `UPLOAD_DIR` | `./data/uploads` | Directory where uploaded images are stored. Ignored, without error, when `STORAGE_DRIVER=s3`. |
| `CORS_ALLOWED_ORIGINS` | *(empty)* | Semicolon-separated list of origins allowed to call the API. When empty, no CORS headers are sent. That is the right setting whenever the SPA is served by RenewCMS itself (production) or through the Vite proxy (development). | | `CORS_ALLOWED_ORIGINS` | *(empty)* | Semicolon-separated list of origins allowed to call the API. Matching is case-insensitive. An entry may contain one `*` (`https://*.preview.example.com`), and a lone `*` allows every origin. Credentials are never allowed cross-origin. When empty, no CORS headers are sent. That is the right setting whenever the SPA is served by RenewCMS itself (production) or through the Vite proxy (development). |
| `AUTH_RATE_LIMIT_MAX_ATTEMPTS` | `5` | Maximum number of requests a single client IP may send to `POST /v1/auth/login`, `POST /v1/auth/password-reset` or the invite-accept pair (`GET /v1/auth/invite` and `POST /v1/auth/invite/accept`, sharing one counter) within the window, tracked independently per route. | | `AUTH_RATE_LIMIT_MAX_ATTEMPTS` | `5` | Maximum number of requests a single client IP may send to `POST /v1/auth/login`, `POST /v1/auth/password-reset` or the invite-accept pair (`GET /v1/auth/invite` and `POST /v1/auth/invite/accept`, sharing one counter) within the window, tracked independently per route. |
| `AUTH_RATE_LIMIT_WINDOW_SECONDS` | `60` | Length, in seconds, of the fixed rate-limit window for the routes above. | | `AUTH_RATE_LIMIT_WINDOW_SECONDS` | `60` | Length, in seconds, of the fixed rate-limit window for the routes above. |
| `SMTP_ALLOW_INSECURE` | `false` | `true` lets RenewCMS deliver mail without encryption to a server on another host that does not offer STARTTLS (a relay on a private network, a local Mailpit container). By default such delivery fails with an error naming this variable; port `465` always uses implicit TLS and `localhost`, `127.0.0.1` and `::1` are always allowed in clear text. Credentials (`SMTP_LOGIN`/`SMTP_PASSWORD`) are never sent unencrypted to another host, whatever this says. Any value other than `true` or `false` (case-insensitive) stops the server at boot. |
| `TRUSTED_PROXIES` | *(empty)* | Semicolon-separated list of exact IP addresses (no CIDR) of reverse proxies allowed to supply the client IP via `X-Real-IP` for the rate limiting of the routes above. When a request's connection address is not in this list, any `X-Real-IP` or `X-Forwarded-For` header it sends is ignored and the connection address is used instead. See [deployment.md](deployment.md). | | `TRUSTED_PROXIES` | *(empty)* | Semicolon-separated list of exact IP addresses (no CIDR) of reverse proxies allowed to supply the client IP via `X-Real-IP` for the rate limiting of the routes above. When a request's connection address is not in this list, any `X-Real-IP` or `X-Forwarded-For` header it sends is ignored and the connection address is used instead. See [deployment.md](deployment.md). |
| `RENEWCMS_CONTAINER` | `false` | Set to `true` (case-insensitive; any other value means `false`) when the app runs in a container. Settings then tells the owner to update by pulling a new image instead of offering browser updates, and `can_apply` is always `false`. The Dockerfile and `docker-compose.yml` set it to `true`. Update checks still work. | | `RENEWCMS_CONTAINER` | `false` | Set to `true` (case-insensitive; any other value means `false`) when the app runs in a container. Settings then tells the owner to update by pulling a new image instead of offering browser updates, and `can_apply` is always `false`. The Dockerfile and `docker-compose.yml` set it to `true`. Update checks still work. |
| `IMAGE_VARIANT_MAX_SOURCE_BYTES` | `10485760` | Largest stored image, in bytes, that an [image variant](image-variants.md) may be generated from. A request for a bigger source answers 413 with a plain-text body. The original is never affected, and SVG and animated GIF are always served as they are. A value that is not a whole number greater than zero stops the server at boot with an error naming the variable. | | `IMAGE_VARIANT_MAX_SOURCE_BYTES` | `10485760` | Largest stored image, in bytes, that an [image variant](image-variants.md) may be generated from. A request for a bigger source answers 413 with a plain-text body. The original is never affected, and SVG and animated GIF are always served as they are. A value that is not a whole number greater than zero stops the server at boot with an error naming the variable. |
+1 -1
View File
@@ -274,7 +274,7 @@ Either way, set `TRUSTED_PROXIES` (see [configuration.md](configuration.md)) to
RenewCMS sends `Content-Security-Policy` (including `frame-ancestors 'none'`), `X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy` and `Cross-Origin-Opener-Policy` itself, so the proxy doesn't need to add them. With `ENVIRONMENT=production` it also sends `Strict-Transport-Security: max-age=31536000` (browsers ignore it over plain HTTP, so serve the site over HTTPS only). Don't add the same headers in the proxy, or they will be duplicated. RenewCMS sends `Content-Security-Policy` (including `frame-ancestors 'none'`), `X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy` and `Cross-Origin-Opener-Policy` itself, so the proxy doesn't need to add them. With `ENVIRONMENT=production` it also sends `Strict-Transport-Security: max-age=31536000` (browsers ignore it over plain HTTP, so serve the site over HTTPS only). Don't add the same headers in the proxy, or they will be duplicated.
The CSP allows Google Fonts (`fonts.googleapis.com`, `fonts.gstatic.com`) and `https:` images, because the SPA loads its fonts from Google and articles may embed remote images. `style-src` keeps `'unsafe-inline'` for the article editor; `script-src` is `'self'` only. The CSP serves fonts from `'self'` only (the SPA bundles its fonts, so no visitor IP address is sent to a font CDN) and allows `https:` images, because articles may embed remote images. `style-src` keeps `'unsafe-inline'` for the article editor; `script-src` is `'self'` only.
## Using MySQL or MariaDB ## Using MySQL or MariaDB
+1 -1
View File
@@ -21,7 +21,7 @@ Back-office board groups: Sites, Sites: form, Sites: delete, Authors, Authors: f
- Role-restricted variants drawn: read-only Authors list and detail, hidden Sites entry, Sites 403, own-author edit. - Role-restricted variants drawn: read-only Authors list and detail, hidden Sites entry, Sites 403, own-author edit.
## Pass 4: custom content types ## Pass 4: custom content types
Board `RenewCMS Screens Schema.dc.html` (frames: `SchemaFrame`, mounted in `AppFrame`): 9 groups, 65 states (56 available now, 9 later). 1 Schema list 6, 2 Schema builder 16, 3 Review and delete 7, 4 Field types 6, 5 Content and entry list 9, 6 Entry editor 13, 7 Relations 3, 8 Permissions 2, 9 Export and import 3. Plus tables: scope, routes, new components with their Nuxt UI mapping, errors to copy, needs backend (4 rows), decisions to confirm, accessibility. Specs: screens/schema.md, content.md, entry.md, schema-later.md. Board `RenewCMS Screens Schema.dc.html` (frames: `SchemaFrame`, mounted in `AppFrame`): 11 groups, 97 states. 1 Schema list 7, 2 Schema builder 19, 3 Review and delete 9, 4 Field types 7, 5 Content and entry list 12, 6 Entry editor 23, 7 Relations 3, 8 Permissions 2, 9 Export and import 3, 10 Media picker for a field 8, 11 Media library usage 4. The Media field type (pass 5) is specified in `media-field-changes.md`; the exact copy and measurements are there, and the boards are the visual reference. Plus tables: scope, routes, new components with their Nuxt UI mapping, errors to copy, needs backend (4 rows), decisions to confirm, accessibility. Specs: screens/schema.md, content.md, entry.md, schema-later.md, media.md, media-picker.md, and media-field-changes.md for the Media field type.
- AppFrame gains a Schema item (owner and admin) and a Content group (sidebar and mobile drawer). Nothing else in AppFrame changed. - AppFrame gains a Schema item (owner and admin) and a Content group (sidebar and mobile drawer). Nothing else in AppFrame changed.
- Backend gaps still open: built-in types and fields, display names for created_by and updated_by, a type icon, per-change entry counts. - Backend gaps still open: built-in types and fields, display names for created_by and updated_by, a type icon, per-change entry counts.
- Not done: Back-office and Prototype boards were not compared visually after the sidebar change (see Checks below). - Not done: Back-office and Prototype boards were not compared visually after the sidebar change (see Checks below).
+10
View File
@@ -121,3 +121,13 @@ Frames: `SchemaFrame.dc.html` (all schema, content and entry bodies; relation, p
| RelationField (later) | New | UInputMenu multiple | Chips and search | | RelationField (later) | New | UInputMenu multiple | Chips and search |
| PermissionsGrid (later) | New | UTable + UCheckbox; UCard list on mobile | | | PermissionsGrid (later) | New | UTable + UCheckbox; UCard list on mobile | |
| SchemaImportDialog (later) | New | UModal + UFileUpload | | | SchemaImportDialog (later) | New | UModal + UFileUpload | |
## Media field (pass 5)
Frames: `SchemaFrame.dc.html` (`MCtl`) and `MediaFrame.dc.html` (picker in field mode, usage). Full spec: `media-field-changes.md`.
| Component | Status | Nuxt UI | Notes |
|---|---|---|---|
| MediaFieldControl | New | UFormField, UButton outline and ghost, UModal (desktop) or bottom UDrawer (mobile) for the picker, UTooltip, UIcon (image, image-off, unlink, image-plus). The thumbnail is a plain button | Props label, required, modelValue (image id or null), image (filename, width, height, size, or missing), disabled, error. Emits update:modelValue. States: empty, filled, hover, focus, error, missing, saving, read-only |
| FieldCell (media) | Extended | Thumbnail 40 px square, dash when empty, dashed square with unlink when the image is gone | Row height 48 px, mobile card thumbnail 32 px |
| MediaPicker (field mode) | Extended | Existing picker | Title "Choose an image", "Use this image", no alt text, no variant select, "Current" badge, optional "No image" row |
+121
View File
@@ -0,0 +1,121 @@
# Media field type: change list for implementation
Board: `RenewCMS Screens Schema.dc.html`. Frames changed: `SchemaFrame.dc.html`, `MediaFrame.dc.html`. Spec data: `schema-spec.js` (states) and `media-field-tables.js` (tables, appended to the board). No new tokens, no new colors, radius 0.
## 1. Behaviour
- New field type `media`, name "Media", icon `lucide:image`, description "One image from your media library".
- Stored value: id of a library image, or null. The file is never copied. The field always shows the current library image.
- Options: label, key, required. No default, unique, min, max or choices. The inspector hides them.
- Required: the entry can't be saved while the field is empty (422 invalid_entry, rule required).
- A saved field's type never changes. Key and type are locked after the first save (existing rule).
- Adding a required media field to a type with entries is refused, because a media field can't have a default. The review step shows this before the server is asked.
- Image deleted while entries point at it: the entry keeps the id. The control shows the missing state. Saving is refused only if the field is required.
- Entries count as uses of an image in Media. Deleting a used image is allowed after a warning.
- Variants: the editor preview uses the original. No variant select in the field. Nothing about variants in the builder.
- Galleries (several images) are out of scope and not drawn.
## 2. New component: MediaFieldControl
Props: label, required, modelValue (image id or null), image (filename, width, height, size, or `missing: true`), disabled, error. Emits `update:modelValue`. Opens the picker.
Nuxt UI v4: `UFormField` (label, help, error, required), `UButton` outline ("Pick an image", "Change image", "Choose another image"), `UButton` ghost ("Remove", "Clear"), `UModal` on desktop and bottom `UDrawer` on mobile for the picker, `UTooltip` for the list placeholder and the badge, `UIcon` lucide:image, image-off, unlink, image-plus. The thumbnail is a plain `button`.
States and measurements (SchemaFrame `MCtl`):
| State | Drawing |
|---|---|
| Empty | Dashed box (1px dashed `--ui-border-accented`), padding 12, 40 px icon square (`--ui-bg-elevated`), "No image selected.", button "Pick an image" (icon image-plus). Mobile: stacked, 44 px button |
| Filled | Solid 1px `--ui-border-accented` box, padding 12. Thumbnail 160 × 120 (mobile: full width, 16:9). Filename weight 500, then "1600 × 900 · 240 KB" 12/18 muted. Buttons "Change image" (outline, icon image) and "Remove" (ghost, icon x). Help line "One image from your library." |
| Hover (desktop) | Border `--ui-text-muted`. Bottom bar 28 px, `--ui-bg-inverted` with `--ui-text-inverted`, icon image 14 and "Change image". No hover on mobile |
| Focus | 2 px `--ui-primary` outline, offset 2, on the thumbnail button |
| Error | Box border `--ui-error` plus inset 1px `--ui-error`, error line with circle-alert 14: "Pick an image for Thumbnail." Focus ring on the first button (Pick an image, or Choose another image) |
| Missing | Dashed 160 × 120 (mobile 16:9) placeholder with image-off 24. Text "This image is no longer in the library" (weight 500). Help: optional "You can still save. The entry keeps the link until you change it." / required "Thumbnail is required. Choose another image to save." Buttons "Choose another image" (outline) and "Clear" (ghost) |
| Saving | Thumbnail at 60%, buttons at 40%, all form fields disabled, Save reads "Saving…" |
| Read-only (fields changed) | Same as saving, plus warning alert "The fields of Events changed" and button "Reload form" |
Label is the field label, plus " *" when required (existing form rule; "(optional)" is not used).
## 3. Per screen
### 3.1 Schema list (group 1), state "Custom type: read-only view"
Fields table of a custom type (Label, Key, Type, Rules) in the built-in table style. Thumbnail row: image icon, key `thumbnail`, type "Media", rules "One image from the library". Header "Events" with badge "Read only" (lock). Alert: "You can read these fields here" / "Only an owner or admin can change a content type." The built-in Media type in Schema is unchanged. Decision needed: no route shows a custom type read-only today.
### 3.2 Schema builder (group 2), 3 states
- "Media field selected": saved Thumbnail row selected (index 7). Inspector: Label, Key (locked, "Used in the API, so it can't change."), Type tiles (seven, Media selected, others dimmed with "Can't change after saving"), Required switch ("Required" / "An entry can't be saved with this field empty."). Hidden for media: Unique values, Default value, limits, choices. Hint (info-soft block, info icon): "Holds one image from the media library. Entries link to the image instead of keeping a copy, so they always show its current version."
- "New media field, seven types": new row with "New" badge, key editable ("The name used in the API. Starts with a letter. Lowercase letters, digits and underscores."), type tiles all enabled. State chip "Unsaved changes".
- "Media field, required": row shows the existing Required marker.
- Field row: grip, 28 px icon square (image), label, key (mono), badges. Mobile: inspector in the existing 92% sheet (title "Field: Thumbnail", footer "Done").
- Type tile grid now has seven tiles (3 columns desktop inspector, 2 in sheets).
### 3.3 Review (group 3), 2 states
Dialog "Review changes to Events" / "Apply them to save the content type." Summary "Add 1 field" / "Events has 12 entries. Each one is checked against the new fields when you apply." The info bar in the builder behind reads "12 entries use this content type…".
- Refused: row "Add Thumbnail", warning flag "Can't be applied", text "Media, required. A media field can't have a default, so the 12 existing entries would have no image. Make Thumbnail optional to add it." Note "Back to editing keeps your other changes." Buttons "Back to editing", "Apply changes" (disabled). This departs from the existing review (Apply is never disabled): decision.
- Clean: row "Add Thumbnail", "Media, optional. 12 entries are unaffected." Apply enabled.
### 3.4 Field types (group 4), state "Media"
Per-type frame like the others: header icon image, "Media", "One image from your media library", `type: "media"`. Columns: inspector options, entry form control (filled with hover, then empty), list cell (Filled thumbnail, Empty "–", Image missing), errors by rule, filter (later).
Errors by rule: required 422 "Pick an image for Thumbnail."; type 422 "Thumbnail must be an image from the library."; min, max, options, unique: "Not used for media." Filter widget: "Thumbnail: has an image" with Any / Has an image / No image, tagged Later.
### 3.5 Entry list (group 5), 3 states
Columns shown: Title, Thumbnail, Starts on, Category (user choice). Header "Thumbnail", no sort icon, column 80 px. Cell: 40 px square thumbnail; "–" when empty; dashed 40 px square with unlink icon, accessible name "Image no longer in the library", when the image is gone. Row height stays 48 px (thumbnail fits with 4 px above and below). Mobile card: 32 px thumbnail leads the card (empty: "–", missing: dashed square), card min height 68 px. Columns menu lists Thumbnail with the image icon ("4 of 6", "Choose up to 6 fields to show. 4 selected." on mobile). Tooltip on the missing placeholder (desktop): "Image no longer in the library".
### 3.6 Entry editor (group 6), 10 states
Control sits after Description, at the end of the form (schema order; see conflicts). States: empty optional, empty required, filled, hover, focus, validation error (status chip "Not saved"), image no longer in the library, missing + required (error), saving, read-only. The board scrolls the form so the control is visible in the frame; the real form is not scrolled.
### 3.7 Picker (group 10), 8 states, MediaFrame field mode
Existing picker (Upload and Library tabs, single selection, search "Search by filename", "Newest first · 48 images", Load more, 4 columns desktop and 3 on mobile, square tiles). Differences:
- Title "Choose an image".
- Primary "Use this image" (disabled until a tile is chosen). When "No image" is chosen it reads "Remove image".
- No alt text field, no variant select. Selected strip shows thumbnail, filename, "dimensions · size".
- Current image tile badge "Current" (replaces "In this article").
- Optional fields only: row "No image" / "Leave this field empty." at the top of the Library tab. Selected: sand fill, primary border, check.
- Empty: "Your library is empty" / "Images you upload appear here, ready to use in any article or entry." / "Upload an image".
- Failed: "Couldn't load your library" / "Check your connection and try again." / "Try again".
- Loading: skeleton tiles after 150 ms.
- Upload tab: unchanged flow (crop, resize); the new image lands in the library and is selected.
- Desktop dialog 640 wide, mobile bottom sheet.
### 3.8 Media library (group 11), 4 states
- Badge "Used in N" = articles + entries. The tooltip (hover or focus) reads "Used in entries: 3" and, if articles also use it, "Used in articles: 2" on the first line. Example: bathroom-tiles.png, 3 entries, "Used in 3".
- List view: same badge in the list row and mobile card.
- Detail panel (lime-plaster.jpg, 2 articles, 5 entries): preview is shorter when the image has entries; existing "Used in 2 articles" list; new section "Used in entries" with up to 3 rows (type name muted, entry title as link, arrow-up-right) and "and 2 more". When there are entries the empty-articles line reads "No article shows it." (not "safe to delete").
- Delete: title "Delete an image that's in use?" (existing in-use dialog), body `"lime-plaster.jpg" is used in 5 entries and 2 articles. Those entry fields will show "This image is no longer in the library", and the articles will show a broken image. This can't be undone.` with the entries and articles lists; "Cancel" and destructive "Delete image".
## 4. Copy added (exact)
Media · One image from your media library · Holds one image from the media library. Entries link to the image instead of keeping a copy, so they always show its current version. · No image selected. · Pick an image · Change image · Remove · Choose another image · Clear · One image from your library. · This image is no longer in the library · You can still save. The entry keeps the link until you change it. · Thumbnail is required. Choose another image to save. · Pick an image for Thumbnail. · Thumbnail must be an image from the library. · Not used for media. · Image no longer in the library · Choose an image · Use this image · Remove image · Current · No image · Leave this field empty. · Used in entries · and 2 more · Used in entries: 3 · Can't be applied · Media, required. A media field can't have a default, so the 12 existing entries would have no image. Make Thumbnail optional to add it. · Media, optional. 12 entries are unaffected. · The Thumbnail field was changed after you opened this form. Reload the form to continue. What you typed here can't be saved against the old fields.
Sentence case, "image" never "asset", buttons are verbs.
## 5. API and backend
- Schema API accepts type `media` with label, key, required. Value: image id or null.
- 422 invalid_entry: required → "Pick an image for Thumbnail."; type (id not in the library on a changed value) → "Thumbnail must be an image from the library."
- Entry and list responses include, per media field, filename, width, height, size and a thumbnail URL, or `missing: true`.
- GET /v1/media/{id}/usage returns articles and entries (content type name, key, entry id, title), a total and the first few items. GET /v1/media/ list items carry the combined use count.
- DELETE /v1/media/{id} stays allowed for used images. Entries keep the id.
- A new required media field on a type with entries is refused (schema_incompatible). The client shows the refusal first.
HTTP to copy (picker and field), from states.md: 400 "That request wasn't valid. Check the fields and try again."; 401/403 global; 404 "That item no longer exists."; 409 "This changed somewhere else. Reload and try again."; 413 "That file is too large."; 429 "Too many requests. Try again in a few minutes."; 500/network "Something went wrong on our side. Nothing was changed. Try again in a moment."
## 6. Accessibility
- Control is `role="group"` labelled by the field label. Required: `aria-required` on the main button.
- Names: "Pick an image for Thumbnail"; thumbnail "Change image, lime-plaster-workshop.jpg, 1600 by 900, 240 KB"; "Remove image from Thumbnail"; "Clear Thumbnail"; missing placeholder `role="img"` "Image no longer in the library".
- Error: error text has an id. The main button gets `aria-invalid="true"` and `aria-describedby` (error id, then help id). Focus moves to the first invalid control on a refused save.
- Order: label, thumbnail, Change image, Remove, help or error. The thumbnail duplicates Change image; use `tabindex="-1"` on it if one stop is preferred.
- One polite live region: "Image selected: lime-plaster-workshop.jpg", "Image removed from Thumbnail.", "Thumbnail cleared."
- Focus: Use this image → Change image. Remove or Clear → Pick an image. Cancel or Esc → the opener.
- Picker: tiles are buttons with `aria-pressed`, names "stone-steps.jpg, 310 KB, Current". "No image" has `aria-pressed`. "Use this image" uses `aria-disabled`.
- Contrast: Current badge and selected rows use `--rc-on-sand`; hover bar 18.9 (inverted pair). 44 px targets on mobile. No hover on mobile.
## 7. Conflicts to decide
1. Row height: design is 48 px (56 px media rows, 68 px cards), not 32 px. Drawn at 48 and 68.
2. Thumbnail position: existing form has Description last. Drawn after Description (end of form).
3. "Used in N" counted articles. Now articles + entries.
4. Delete title: existing in-use title kept; "Delete this image?" stays for unused images.
5. "Clear" vs glossary "Remove".
6. "1600 × 900 · 240 KB" (design separator) instead of "1600 x 900 - 240 KB".
7. Review step disables Apply for the certain refusal; existing review never does.
8. Picker button "Use this image" vs article picker "Insert image"; "Remove image" when No image is chosen is my addition.
9. "Pick an image" also on optional empty fields.
10. No read-only route for custom types.
11. Two tab stops for the same picker (thumbnail and Change image).
12. Disabled opacity: form 60%, foundations 40%.
13. The picker frame shows a stand-in entry form, not the real editor.
## 8. Not done
README.md, states.md and the screens/*.md files are not updated with the new counts (group 2 +3, 3 +2, 4 +1, 5 +3, 6 +10, 1 +1, new groups 10 (8) and 11 (4): 32 states). Light/dark and mobile frames were checked by reading the DOM, not state by state on screen.
+3
View File
@@ -21,3 +21,6 @@ The sidebar gets a "Content" group, one item per custom type (a default icon: ty
| 7 | Error | 500 or network failure. | Couldn't load entries · GET /v1/content-type/events/entry failed. Check your connection and try again. · Try again | Available now | | 7 | Error | 500 or network failure. | Couldn't load entries · GET /v1/content-type/events/entry failed. Check your connection and try again. · Try again | Available now |
| 8 | Forbidden (403) | The API answers 403. Unverified accounts are redirected to /register/pending before this. | You don't have access to Events · Your account can't open this content right now. If you think this is a mistake, ask an owner or an admin. · Go to Home | Available now | | 8 | Forbidden (403) | The API answers 403. Unverified accounts are redirected to /register/pending before this. | You don't have access to Events · Your account can't open this content right now. If you think this is a mistake, ask an owner or an admin. · Go to Home | Available now |
| 9 | Type not found | 404 content_type_not_found on /content/unknown. | Content type not found · It may have been deleted, or the address may be mistyped. · Go to Home | Available now | | 9 | Type not found | 404 content_type_not_found on /content/unknown. | Content type not found · It may have been deleted, or the address may be mistyped. · Go to Home | Available now |
## Media field (pass 5)
Spec, states, exact copy, measurements, backend needs and accessibility: `media-field-changes.md`, section 3.5. Board groups: 5 Content and entry list.
+3
View File
@@ -25,3 +25,6 @@ The form is generated from the schema, one control per field in schema order. Re
| 11 | Entry not found | 404 entry_not_found, for example after a delete elsewhere. | Entry not found · It may have been deleted by someone else. · Back to Events | Available now | | 11 | Entry not found | 404 entry_not_found, for example after a delete elsewhere. | Entry not found · It may have been deleted by someone else. · Back to Events | Available now |
| 12 | Schema changed since load | 422 invalid_entry: room: required, or unknown_field. The form is read-only until reloaded. | The fields of Events changed · A field was removed and a new required field, Room, was added after you opened this form. Reload the form to continue. What you typed here can't be saved against the old fields. · Reload form | Available now | | 12 | Schema changed since load | 422 invalid_entry: room: required, or unknown_field. The form is read-only until reloaded. | The fields of Events changed · A field was removed and a new required field, Room, was added after you opened this form. Reload the form to continue. What you typed here can't be saved against the old fields. · Reload form | Available now |
| 13 | Delete entry: confirm | Delete. | Delete this entry? · "Lime plaster workshop" will be deleted from Events. This can't be undone. · Cancel · Delete entry | Available now | | 13 | Delete entry: confirm | Delete. | Delete this entry? · "Lime plaster workshop" will be deleted from Events. This can't be undone. · Cancel · Delete entry | Available now |
## Media field (pass 5)
Spec, states, exact copy, measurements, backend needs and accessibility: `media-field-changes.md`, section 3.6. Board groups: 6 Entry editor.
+3
View File
@@ -45,3 +45,6 @@ The Library tab of the picker gets a Variant select. Options are Original plus t
| 3 | No variants defined | Only Original is offered. | "Articles" / "How we price a bathroom renovation" / "Edit article" | | 3 | No variants defined | Only Original is offered. | "Articles" / "How we price a bathroom renovation" / "Edit article" |
| 4 | Variant deleted | The block keeps its URL. Pick another variant opens the select. | "Articles" / "How we price a bathroom renovation" / "Edit article" / "Variant 'hero' no longer exists." | | 4 | Variant deleted | The block keeps its URL. Pick another variant opens the select. | "Articles" / "How we price a bathroom renovation" / "Edit article" / "Variant 'hero' no longer exists." |
| 5 | Variant disabled | Same block, different cause. Proposed copy. | "Articles" / "How we price a bathroom renovation" / "Edit article" / "Variant 'hero' is disabled." | | 5 | Variant disabled | Same block, different cause. Proposed copy. | "Articles" / "How we price a bathroom renovation" / "Edit article" / "Variant 'hero' is disabled." |
## Media field (pass 5)
Spec, states, exact copy, measurements, backend needs and accessibility: `media-field-changes.md`, section 3.7. Board groups: 10 Media picker for a field.
+3
View File
@@ -113,3 +113,6 @@ A secondary "Purge duplicates" button (icon merge) in the toolbar next to the so
|---|---|---|---| |---|---|---|---|
| 1 | Duplicates tab with the button | Owner or admin. | | | 1 | Duplicates tab with the button | Owner or admin. | |
| 2 | Duplicates tab: offline | The button is disabled with the existing banner. | | | 2 | Duplicates tab: offline | The button is disabled with the existing banner. | |
## Media field (pass 5)
Spec, states, exact copy, measurements, backend needs and accessibility: `media-field-changes.md`, section 3.8. Board groups: 11 Media library usage.
+3
View File
@@ -76,3 +76,6 @@ One frame per type: inspector options, the entry form control (default and open
| 4 | Yes or no | type: "boolean" | Yes or no · An on or off switch · On by default · Yes or no fields have no limits. · Not available for yes or no fields. (Unique) · Choose yes or no for Online. · Online must be yes or no. | Available now | | 4 | Yes or no | type: "boolean" | Yes or no · An on or off switch · On by default · Yes or no fields have no limits. · Not available for yes or no fields. (Unique) · Choose yes or no for Online. · Online must be yes or no. | Available now |
| 5 | Date | type: "date" | Date · A calendar day, without a time · Earliest date · Latest date · Pick a date · Pick a date for Starts on. · Starts on must be a date, like 2026-11-21. · Starts on can't be before 1 Jan 2026. · Starts on can't be after 31 Dec 2027. | Available now | | 5 | Date | type: "date" | Date · A calendar day, without a time · Earliest date · Latest date · Pick a date · Pick a date for Starts on. · Starts on must be a date, like 2026-11-21. · Starts on can't be before 1 Jan 2026. · Starts on can't be after 31 Dec 2027. | Available now |
| 6 | Choice | type: "select" | Choice · One option from a list you define · Choices · Choose an option · Choose one of: Talk, Workshop or Meetup. · Another entry already uses this choice for Category. | Available now | | 6 | Choice | type: "select" | Choice · One option from a list you define · Choices · Choose an option · Choose one of: Talk, Workshop or Meetup. · Another entry already uses this choice for Category. | Available now |
## Media field (pass 5)
Spec, states, exact copy, measurements, backend needs and accessibility: `media-field-changes.md`, section 3.1 to 3.4. Board groups: 1 Schema list, 2 Schema builder, 3 Review, 4 Field types.
+20 -13
View File
@@ -53,6 +53,8 @@ class Component extends DCLogic {
] ]
const VC = { 1: 4, 2: 5, 3: 5, 4: 0, 5: 3, 6: 0, 7: 2, 8: 0, 9: 1, 10: 3, 11: 4, 12: 5 } const VC = { 1: 4, 2: 5, 3: 5, 4: 0, 5: 3, 6: 0, 7: 2, 8: 0, 9: 1, 10: 3, 11: 4, 12: 5 }
IM.forEach(x => { x.vc = VC[x.id] || 0 }) IM.forEach(x => { x.vc = VC[x.id] || 0 })
const ENT = { 10: 3, 11: 5 }
IM.forEach(x => { x.ent = s.ent ? (ENT[x.id] || 0) : 0 })
const byId = id => IM.find(x => x.id === id) const byId = id => IM.find(x => x.id === id)
const AR = [['How we price a bathroom renovation', 1], ['Winter checklist for timber windows', 0], ['Before and after: the Rue Verte kitchen', 1], ['Why we reuse original floorboards', 1], ['Choosing lime plaster for old stone walls', 0]] const AR = [['How we price a bathroom renovation', 1], ['Winter checklist for timber windows', 0], ['Before and after: the Rue Verte kitchen', 1], ['Why we reuse original floorboards', 1], ['Choosing lime plaster for old stone walls', 0]]
const usedList = n => AR.slice(0, Math.min(n, 5)) const usedList = n => AR.slice(0, Math.min(n, 5))
@@ -60,8 +62,8 @@ class Component extends DCLogic {
const imgs = ids.map(byId) const imgs = ids.map(byId)
const sel = s.sel || [] const sel = s.sel || []
const pl = n => n + (n === 1 ? ' article' : ' articles') const pl = n => n + (n === 1 ? ' article' : ' articles')
const label = im => im.n + ', ' + im.sz + ', ' + (im.used ? 'used in ' + pl(im.used) : 'unused') const label = im => im.n + ', ' + im.sz + ', ' + (im.used + im.ent ? 'used in ' + [im.used && pl(im.used), im.ent && (im.ent + (im.ent === 1 ? ' entry' : ' entries'))].filter(Boolean).join(' and ') : 'unused')
const usedBadge = im => im.used ? Bd('Used in ' + im.used, 'used') : Bd('Unused', 'unused') const usedBadge = im => { const n = im.used + im.ent, b = n ? Bd('Used in ' + n, 'used') : Bd('Unused', 'unused'); return s.tip === im.id ? S('position:relative;display:inline-flex', b, D('position:absolute;left:0;top:26px;z-index:10;padding:6px 8px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font-size:12px;line-height:18px;white-space:nowrap;box-shadow:var(--rc-shadow-pop)', im.used > 0 && D('', 'Used in articles: ' + im.used), D('', 'Used in entries: ' + im.ent))) : b }
// ---------- Media page pieces // ---------- Media page pieces
const Card = im => { const Card = im => {
@@ -196,6 +198,8 @@ class Component extends DCLogic {
const BulkBar = () => D('position:absolute;z-index:30;bottom:' + (m ? 16 : 24) + 'px;' + (m ? 'left:16px;right:16px' : 'left:calc(224px + (100% - 224px) / 2);transform:translateX(-50%);width:400px') + ';display:flex;align-items:center;gap:8px;padding:8px 8px 8px 16px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);box-shadow:var(--rc-shadow-pop)', S('flex:1;font-weight:500', sel.length + ' selected'), B('Delete', { k: 'danger', icon: 'trash-2' }), B('Clear', { k: 'inv' })) const BulkBar = () => D('position:absolute;z-index:30;bottom:' + (m ? 16 : 24) + 'px;' + (m ? 'left:16px;right:16px' : 'left:calc(224px + (100% - 224px) / 2);transform:translateX(-50%);width:400px') + ';display:flex;align-items:center;gap:8px;padding:8px 8px 8px 16px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);box-shadow:var(--rc-shadow-pop)', S('flex:1;font-weight:500', sel.length + ' selected'), B('Delete', { k: 'danger', icon: 'trash-2' }), B('Clear', { k: 'inv' }))
// ---------- detail panel // ---------- detail panel
const ENTL = [['Events', 'Lime plaster workshop'], ['Events', 'Heritage stone walk'], ['Events', 'Winter open day']]
const EntBox = im => D('display:flex;flex-direction:column;gap:8px', S('font:600 14px/22px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', 'Used in entries'), D('border:1px solid var(--ui-border)', ...ENTL.map(([ty, tt], i) => D('display:flex;align-items:center;gap:8px;min-height:' + (m ? 48 : 36) + 'px;padding:0 12px;border-top:' + (i ? '1px solid var(--ui-border-muted)' : '0'), S('width:52px;flex-shrink:0;font-size:12px;color:var(--ui-text-muted)', ty), S('flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;text-decoration:underline;text-underline-offset:3px;color:var(--ui-text-highlighted)', tt), I('arrow-up-right', 14, 'color:var(--ui-text-muted)'))), im.ent > 3 && D('padding:8px 12px;border-top:1px solid var(--ui-border-muted);color:var(--ui-text-muted)', 'and ' + (im.ent - 3) + ' more')))
const Panel = () => { const Panel = () => {
const im = byId(s.panel.id), list = usedList(im.used) const im = byId(s.panel.id), list = usedList(im.used)
const meta = [['Type', im.ty], ['Size', im.sz], ['Dimensions', im.dim], ['Uploaded', im.d], ['Uploaded by', im.by]] const meta = [['Type', im.ty], ['Size', im.sz], ['Dimensions', im.dim], ['Uploaded', im.d], ['Uploaded by', im.by]]
@@ -204,14 +208,14 @@ class Component extends DCLogic {
D('width:' + w + ';height:100%;background:var(--ui-bg);display:flex;flex-direction:column;' + (m ? '' : 'box-shadow:var(--rc-shadow-modal)'), D('width:' + w + ';height:100%;background:var(--ui-bg);display:flex;flex-direction:column;' + (m ? '' : 'box-shadow:var(--rc-shadow-modal)'),
D('height:' + (m ? 56 : 56) + 'px;flex-shrink:0;display:flex;align-items:center;gap:' + (m ? 4 : 12) + 'px;padding:0 ' + (m ? 6 : 20) + 'px;border-bottom:1px solid var(--ui-border)', m && S('width:44px;height:44px;display:flex;align-items:center;justify-content:center', I('arrow-left', 20)), S('flex:1;min-width:0;font:600 16px/24px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', im.n), !m && S('width:28px;height:28px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x'))), D('height:' + (m ? 56 : 56) + 'px;flex-shrink:0;display:flex;align-items:center;gap:' + (m ? 4 : 12) + 'px;padding:0 ' + (m ? 6 : 20) + 'px;border-bottom:1px solid var(--ui-border)', m && S('width:44px;height:44px;display:flex;align-items:center;justify-content:center', I('arrow-left', 20)), S('flex:1;min-width:0;font:600 16px/24px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', im.n), !m && S('width:28px;height:28px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x'))),
D('flex:1;min-height:0;overflow:hidden;padding:' + (m ? 16 : 20) + 'px;display:flex;flex-direction:column;gap:20px', D('flex:1;min-height:0;overflow:hidden;padding:' + (m ? 16 : 20) + 'px;display:flex;flex-direction:column;gap:20px',
Th(im, 'aspect-ratio:' + (m ? '4/3' : '16/10') + ';border:1px solid var(--ui-border);flex-shrink:0', 40), Th(im, 'aspect-ratio:' + (im.ent ? (m ? '16/3.6' : '16/6') : m ? '4/3' : '16/10') + ';border:1px solid var(--ui-border);flex-shrink:0', 40),
D('display:flex;gap:8px;' + (m ? 'flex-wrap:wrap' : ''), B('Copy URL', { icon: 'link', full: m }), B('Rename', { icon: 'pencil', full: m }), B('Delete', { k: 'del', icon: 'trash-2', full: m })), D('display:flex;gap:8px;' + (m ? 'flex-wrap:wrap' : ''), B('Copy URL', { icon: 'link', full: m }), B('Rename', { icon: 'pencil', full: m }), B('Delete', { k: 'del', icon: 'trash-2', full: m })),
im.dup && Alert('info', 'copy', 'Identical to 2 other images', 'floorboards-copy.jpg and IMG_2208.jpg have the same content.', 'Review duplicates', { icon: 'arrow-right' }), im.dup && Alert('info', 'copy', 'Identical to 2 other images', 'floorboards-copy.jpg and IMG_2208.jpg have the same content.', 'Review duplicates', { icon: 'arrow-right' }),
D('display:grid;grid-template-columns:110px minmax(0,1fr);gap:8px 12px;color:var(--ui-text-toned)', ...meta.flatMap(([k, v]) => [S('color:var(--ui-text-muted)', k), S('color:var(--ui-text-highlighted)', v)]), S('color:var(--ui-text-muted)', 'URL'), S('font:400 12px/20px \'IBM Plex Mono\',monospace;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', 'cms.renew.example/media/' + im.n)), D('display:grid;grid-template-columns:110px minmax(0,1fr);gap:8px 12px;color:var(--ui-text-toned)', ...meta.flatMap(([k, v]) => [S('color:var(--ui-text-muted)', k), S('color:var(--ui-text-highlighted)', v)]), S('color:var(--ui-text-muted)', 'URL'), S('font:400 12px/20px \'IBM Plex Mono\',monospace;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', 'cms.renew.example/media/' + im.n)),
D('display:flex;flex-direction:column;gap:8px', S('font:600 14px/22px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', im.used ? 'Used in ' + pl(im.used) : 'Not used in any article'), D('display:flex;flex-direction:column;gap:8px', S('font:600 14px/22px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', im.used ? 'Used in ' + pl(im.used) : 'Not used in any article'),
im.used ? D('border:1px solid var(--ui-border)', ...list.map(([t, on], i) => D('display:flex;align-items:center;gap:8px;min-height:' + (m ? 48 : 40) + 'px;padding:0 12px;border-top:' + (i ? '1px solid var(--ui-border-muted)' : '0'), S('flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;text-decoration:underline;text-underline-offset:3px;color:var(--ui-text-highlighted)', t), on ? Bd('Online', 'on', 22) : Bd('Draft', 'draft', 22), I('arrow-up-right', 14, 'color:var(--ui-text-muted)')))) im.used ? D('border:1px solid var(--ui-border)', ...list.map(([t, on], i) => D('display:flex;align-items:center;gap:8px;min-height:' + (m ? 48 : 40) + 'px;padding:0 12px;border-top:' + (i ? '1px solid var(--ui-border-muted)' : '0'), S('flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;text-decoration:underline;text-underline-offset:3px;color:var(--ui-text-highlighted)', t), on ? Bd('Online', 'on', 22) : Bd('Draft', 'draft', 22), I('arrow-up-right', 14, 'color:var(--ui-text-muted)'))))
: S('color:var(--ui-text-muted)', 'This image is safe to delete. No article shows it.'), : S('color:var(--ui-text-muted)', im.ent ? 'No article shows it.' : 'This image is safe to delete. No article shows it.'),
im.used ? S('color:var(--ui-text-muted);font-size:12px', 'Counted from the text of your articles each time you open this page.') : null)))) im.used ? S('color:var(--ui-text-muted);font-size:12px', 'Counted from the text of your articles each time you open this page.') : null), im.ent > 0 && EntBox(im))))
} }
// ---------- modal // ---------- modal
@@ -221,6 +225,7 @@ class Component extends DCLogic {
const md = s.modal, k = md.k const md = s.modal, k = md.k
if (k === 'rename') return { title: 'Rename image', desc: 'Only the filename changes. The URL stays the same, so articles that use this image keep working.', body: [Field('Filename', md.err ? '' : md.val || 'north-wall', { val: !md.err, suffix: '.jpg', focus: !md.loading, err: md.err, dis: md.loading, help: md.err ? '' : 'Letters, numbers, dashes and underscores. The .jpg ending stays.' })], cancel: 'Cancel', confirm: md.loading ? 'Renaming…' : 'Rename' } if (k === 'rename') return { title: 'Rename image', desc: 'Only the filename changes. The URL stays the same, so articles that use this image keep working.', body: [Field('Filename', md.err ? '' : md.val || 'north-wall', { val: !md.err, suffix: '.jpg', focus: !md.loading, err: md.err, dis: md.loading, help: md.err ? '' : 'Letters, numbers, dashes and underscores. The .jpg ending stays.' })], cancel: 'Cancel', confirm: md.loading ? 'Renaming…' : 'Rename' }
if (k === 'del') return { title: 'Delete this image?', desc: '"window-frame.jpg" will be deleted from your library. No article uses it. This can\'t be undone.', cancel: 'Cancel', confirm: md.loading ? 'Deleting…' : 'Delete image', tone: 'danger' } if (k === 'del') return { title: 'Delete this image?', desc: '"window-frame.jpg" will be deleted from your library. No article uses it. This can\'t be undone.', cancel: 'Cancel', confirm: md.loading ? 'Deleting…' : 'Delete image', tone: 'danger' }
if (k === 'delEnt') return { title: 'Delete an image that\'s in use?', desc: '"lime-plaster.jpg" is used in 5 entries and 2 articles. Those entry fields will show "This image is no longer in the library", and the articles will show a broken image. This can\'t be undone.', body: [EntBox(byId(11)), ArtBox(usedList(2))], cancel: 'Cancel', confirm: 'Delete image', tone: 'danger' }
if (k === 'delUsed') return { title: 'Delete an image that\'s in use?', desc: '"north-wall.jpg" is used in 2 articles. If you delete it, they will show a broken image. This can\'t be undone.', body: [ArtBox(usedList(2))], cancel: 'Cancel', confirm: md.loading ? 'Deleting…' : 'Delete image', tone: 'danger' } if (k === 'delUsed') return { title: 'Delete an image that\'s in use?', desc: '"north-wall.jpg" is used in 2 articles. If you delete it, they will show a broken image. This can\'t be undone.', body: [ArtBox(usedList(2))], cancel: 'Cancel', confirm: md.loading ? 'Deleting…' : 'Delete image', tone: 'danger' }
if (k === 'bulk') return { title: 'Delete 3 images?', desc: '2 of them are used in 5 articles, which will show a broken image. The other one isn\'t used anywhere. This can\'t be undone.', body: [D('display:flex;flex-direction:column;border:1px solid var(--ui-border)', ...[['north-wall.jpg', 'Used in 2'], ['kitchen-after.webp', 'Used in 3'], ['window-frame.jpg', 'Unused']].map(([n, u], i) => D('display:flex;align-items:center;gap:8px;min-height:36px;padding:0 12px;border-top:' + (i ? '1px solid var(--ui-border-muted)' : '0'), S('flex:1;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', n), Bd(u === 'Unused' ? 'Unused' : u, u === 'Unused' ? 'unused' : 'used'))))], cancel: 'Cancel', confirm: md.loading ? 'Deleting…' : 'Delete 3 images', tone: 'danger' } if (k === 'bulk') return { title: 'Delete 3 images?', desc: '2 of them are used in 5 articles, which will show a broken image. The other one isn\'t used anywhere. This can\'t be undone.', body: [D('display:flex;flex-direction:column;border:1px solid var(--ui-border)', ...[['north-wall.jpg', 'Used in 2'], ['kitchen-after.webp', 'Used in 3'], ['window-frame.jpg', 'Unused']].map(([n, u], i) => D('display:flex;align-items:center;gap:8px;min-height:36px;padding:0 12px;border-top:' + (i ? '1px solid var(--ui-border-muted)' : '0'), S('flex:1;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', n), Bd(u === 'Unused' ? 'Unused' : u, u === 'Unused' ? 'unused' : 'used'))))], cancel: 'Cancel', confirm: md.loading ? 'Deleting…' : 'Delete 3 images', tone: 'danger' }
if (k === 'merge') return { title: 'Merge into floorboards.jpg?', desc: 'Articles that use the other 2 copies will be switched to floorboards.jpg, and the other 2 copies will be deleted. 5 articles will be updated. This can\'t be undone.', body: [D('display:flex;gap:12px;align-items:center;border:1px solid var(--ui-border);padding:10px 12px', Th(byId(12), 'width:56px;height:42px;flex-shrink:0;border:1px solid var(--ui-border)', 16), D('display:flex;flex-direction:column;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', 'floorboards.jpg'), S('font-size:12px;color:var(--ui-text-muted)', 'Kept · used in 4 articles now')))], cancel: 'Cancel', confirm: md.loading ? 'Merging…' : 'Merge 2 copies', tone: 'danger' } if (k === 'merge') return { title: 'Merge into floorboards.jpg?', desc: 'Articles that use the other 2 copies will be switched to floorboards.jpg, and the other 2 copies will be deleted. 5 articles will be updated. This can\'t be undone.', body: [D('display:flex;gap:12px;align-items:center;border:1px solid var(--ui-border);padding:10px 12px', Th(byId(12), 'width:56px;height:42px;flex-shrink:0;border:1px solid var(--ui-border)', 16), D('display:flex;flex-direction:column;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', 'floorboards.jpg'), S('font-size:12px;color:var(--ui-text-muted)', 'Kept · used in 4 articles now')))], cancel: 'Cancel', confirm: md.loading ? 'Merging…' : 'Merge 2 copies', tone: 'danger' }
@@ -245,6 +250,7 @@ class Component extends DCLogic {
S('display:block', 'A bathroom is priced by what has to happen behind the walls before anything gets tiled.'), S('display:block', 'A bathroom is priced by what has to happen behind the walls before anything gets tiled.'),
s.inArticle && D('position:relative;aspect-ratio:16/9;border:1px solid var(--ui-border);overflow:hidden', Th(byId(1), 'position:absolute;inset:0', 40), S('position:absolute;top:8px;right:8px;height:28px;padding:0 10px;display:flex;align-items:center;gap:6px;background:var(--ui-bg);border:1px solid var(--ui-border-accented);color:var(--ui-text-highlighted);font:500 12px \'IBM Plex Sans\',sans-serif', I('trash-2', 14), 'Remove image')), s.inArticle && D('position:relative;aspect-ratio:16/9;border:1px solid var(--ui-border);overflow:hidden', Th(byId(1), 'position:absolute;inset:0', 40), S('position:absolute;top:8px;right:8px;height:28px;padding:0 10px;display:flex;align-items:center;gap:6px;background:var(--ui-bg);border:1px solid var(--ui-border-accented);color:var(--ui-text-highlighted);font:500 12px \'IBM Plex Sans\',sans-serif', I('trash-2', 14), 'Remove image')),
S('display:block', 'We don\'t add a margin on materials you choose yourself.')))) S('display:block', 'We don\'t add a margin on materials you choose yourself.'))))
const FEditor = () => D('flex:1;min-height:0;overflow:hidden;background:var(--ui-bg-muted);display:flex;flex-direction:column', D('background:var(--ui-bg);border-bottom:1px solid var(--ui-border);padding:12px ' + (m ? 16 : 24) + 'px;display:flex;align-items:center;gap:12px', S('flex:1;font:600 ' + (m ? 16 : 20) + 'px/28px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', 'Lime plaster workshop'), !m && B('Cancel'), !m && B('Save', { k: 'primary' })), D('padding:' + (m ? 16 : 24) + 'px;display:flex;flex-direction:column;gap:16px;max-width:760px', D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:16px;display:flex;flex-direction:column;gap:12px', S('font-weight:500', 'Title'), D('height:32px;border:1px solid var(--ui-border-accented);display:flex;align-items:center;padding:0 10px', 'Lime plaster workshop'), S('font-weight:500', 'Thumbnail'), D('height:120px;border:1px solid var(--ui-border-accented);background:var(--ui-bg)'))))
const PT = s.pk || {} const PT = s.pk || {}
const pImgs = (PT.ids || [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]).map(byId) const pImgs = (PT.ids || [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]).map(byId)
const inArt = [1, 4] const inArt = [1, 4]
@@ -252,7 +258,7 @@ class Component extends DCLogic {
const PTile = im => { const PTile = im => {
const on = PT.sel === im.id const on = PT.sel === im.id
return D('display:flex;flex-direction:column;gap:6px;min-width:0', D('position:relative;' + (on ? 'outline:2px solid var(--ui-primary);outline-offset:2px;' : ''), Th(im, 'aspect-ratio:1/1;border:1px solid var(--ui-border)', 20), return D('display:flex;flex-direction:column;gap:6px;min-width:0', D('position:relative;' + (on ? 'outline:2px solid var(--ui-primary);outline-offset:2px;' : ''), Th(im, 'aspect-ratio:1/1;border:1px solid var(--ui-border)', 20),
inArt.includes(im.id) && S('position:absolute;left:4px;bottom:4px;height:18px;padding:0 5px;display:flex;align-items:center;background:var(--rc-sand);color:var(--rc-on-sand);font-size:11px;font-weight:500', 'In this article'), (s.field ? im.id === PT.cur : inArt.includes(im.id)) && S('position:absolute;left:4px;bottom:4px;height:18px;padding:0 5px;display:flex;align-items:center;background:var(--rc-sand);color:var(--rc-on-sand);font-size:11px;font-weight:500', s.field ? 'Current' : 'In this article'),
on && S('position:absolute;top:4px;right:4px;width:20px;height:20px;display:flex;align-items:center;justify-content:center;background:var(--ui-primary);color:var(--ui-bg)', I('check', 14))), on && S('position:absolute;top:4px;right:4px;width:20px;height:20px;display:flex;align-items:center;justify-content:center;background:var(--ui-primary);color:var(--ui-bg)', I('check', 14))),
S('font-size:12px;color:var(--ui-text-toned);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', im.n)) S('font-size:12px;color:var(--ui-text-toned);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', im.n))
} }
@@ -267,35 +273,36 @@ class Component extends DCLogic {
} }
const kids = [] const kids = []
kids.push(D('height:' + (m ? 44 : 32) + 'px;padding:0 4px 0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:' + (PT.q ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)') + (m ? ';font-size:16px' : ''), I('search', 14), S('flex:1', PT.q || 'Search by filename'), PT.q && S('width:24px;height:24px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x', 14)))) kids.push(D('height:' + (m ? 44 : 32) + 'px;padding:0 4px 0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:' + (PT.q ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)') + (m ? ';font-size:16px' : ''), I('search', 14), S('flex:1', PT.q || 'Search by filename'), PT.q && S('width:24px;height:24px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x', 14))))
if (s.field && !PT.req && !PT.error && !PT.empty && !PT.loading) { const on = PT.sel === 'none'; kids.push(D('display:flex;align-items:center;gap:10px;min-height:' + (m ? 48 : 40) + 'px;padding:0 12px;border:1px solid ' + (on ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (on ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-highlighted)'), I('image-off', 16), S('font-weight:500', 'No image'), S('flex:1;color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-muted)'), 'Leave this field empty.'), on && I('check', 16))) }
if (PT.error) kids.push(Alert('error', 'circle-x', 'Couldn\'t load your library', 'Check your connection and try again.', 'Try again')) if (PT.error) kids.push(Alert('error', 'circle-x', 'Couldn\'t load your library', 'Check your connection and try again.', 'Try again'))
else if (PT.empty === 'first') kids.push(Empty('images', 'Your library is empty', 'Images you upload appear here, ready to use in any article.', 'Upload an image', true, 32)) else if (PT.empty === 'first') kids.push(Empty('images', 'Your library is empty', s.field ? 'Images you upload appear here, ready to use in any article or entry.' : 'Images you upload appear here, ready to use in any article.', 'Upload an image', true, 32))
else if (PT.empty === 'search') kids.push(Empty('search', 'No images match "wall"', 'Check the spelling, or search for a shorter part of the filename.', 'Clear search', false, 32)) else if (PT.empty === 'search') kids.push(Empty('search', 'No images match "wall"', 'Check the spelling, or search for a shorter part of the filename.', 'Clear search', false, 32))
else if (PT.loading) kids.push(PSkel()) else if (PT.loading) kids.push(PSkel())
else { else {
kids.push(S('color:var(--ui-text-muted);font-size:12px', 'Newest first · 48 images'), D('min-height:0;overflow:hidden;' + (PT.sel ? 'max-height:' + (m ? 120 : 190) + 'px' : 'max-height:' + (m ? 300 : 300) + 'px'), PGrid())) kids.push(S('color:var(--ui-text-muted);font-size:12px', 'Newest first · 48 images'), D('min-height:0;overflow:hidden;' + (PT.sel ? 'max-height:' + (m ? 120 : 190) + 'px' : 'max-height:' + (m ? 300 : 300) + 'px'), PGrid()))
if (!PT.sel) kids.push(D('display:flex;justify-content:center', B(PT.more ? 'Loading…' : 'Load more', { icon: PT.more ? 'loader-circle' : null, dis: !!PT.more }))) if (!PT.sel) kids.push(D('display:flex;justify-content:center', B(PT.more ? 'Loading…' : 'Load more', { icon: PT.more ? 'loader-circle' : null, dis: !!PT.more })))
} }
if (PT.sel) { const im = byId(PT.sel); kids.push(D('display:flex;flex-direction:column;gap:12px;padding-top:12px;border-top:1px solid var(--ui-border)', D('display:flex;gap:12px;align-items:center', Th(im, 'width:56px;height:56px;flex-shrink:0;border:1px solid var(--ui-border)', 16), D('display:flex;flex-direction:column;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', im.n), S('font-size:12px;color:var(--ui-text-muted)', im.dim + ' · ' + im.sz))), Field('Alt text (optional)', PT.alt || 'e.g. North wall of the kitchen before plastering', { val: !!PT.alt, focus: !!PT.alt, help: 'Describes the image for people who use a screen reader, and shows if it doesn\'t load. Leave it empty if the image is only decoration.' }))) } if (PT.sel && PT.sel !== 'none') { const im = byId(PT.sel); kids.push(D('display:flex;flex-direction:column;gap:12px;padding-top:12px;border-top:1px solid var(--ui-border)', D('display:flex;gap:12px;align-items:center', Th(im, 'width:56px;height:56px;flex-shrink:0;border:1px solid var(--ui-border)', 16), D('display:flex;flex-direction:column;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', im.n), S('font-size:12px;color:var(--ui-text-muted)', im.dim + ' · ' + im.sz))), !s.field && Field('Alt text (optional)', PT.alt || 'e.g. North wall of the kitchen before plastering', { val: !!PT.alt, focus: !!PT.alt, help: 'Describes the image for people who use a screen reader, and shows if it doesn\'t load. Leave it empty if the image is only decoration.' }))) }
return D('display:flex;flex-direction:column;gap:12px', ...kids) return D('display:flex;flex-direction:column;gap:12px', ...kids)
} }
const Picker = () => { const Picker = () => {
const ins = PT.tab === 'Library' const ins = PT.tab === 'Library'
return Shell({ title: 'Add an image', close: true, w: 640, top: 40, cancel: 'Cancel', confirm: ins ? 'Insert image' : null, cdis: ins && !PT.sel }, D('display:flex;flex-direction:column;min-height:0;flex:1', PTabs(), D('padding:16px 24px 0;min-height:0;overflow:hidden;display:flex;flex-direction:column', PBody()))) return Shell({ title: s.field ? 'Choose an image' : 'Add an image', close: true, w: 640, top: 40, cancel: 'Cancel', confirm: ins ? (s.field ? (PT.sel === 'none' ? 'Remove image' : 'Use this image') : 'Insert image') : null, cdis: ins && !PT.sel }, D('display:flex;flex-direction:column;min-height:0;flex:1', PTabs(), D('padding:16px 24px 0;min-height:0;overflow:hidden;display:flex;flex-direction:column', PBody())))
} }
// ---------- shell // ---------- shell
const isPicker = s.kind === 'picker' const isPicker = s.kind === 'picker'
const navKey = isPicker ? 'articles' : 'media' const navKey = isPicker ? (s.field ? 'content' : 'articles') : 'media'
const crumbs = isPicker ? ['Articles', 'How we price a bathroom renovation'] : ['Media'] const crumbs = isPicker ? (s.field ? ['Content', 'Events', 'Lime plaster workshop'] : ['Articles', 'How we price a bathroom renovation']) : ['Media']
const offline = s.offline && D('flex-shrink:0;display:flex;align-items:center;gap:10px;padding:10px 16px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted)', I('wifi-off'), S('flex:1', 'You\'re offline. You can look through the images that are loaded, but uploading, renaming and deleting need a connection.')) const offline = s.offline && D('flex-shrink:0;display:flex;align-items:center;gap:10px;padding:10px 16px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted)', I('wifi-off'), S('flex:1', 'You\'re offline. You can look through the images that are loaded, but uploading, renaming and deleting need a connection.'))
const pad = m ? 16 : 24 const pad = m ? 16 : 24
const content = isPicker ? Editor() : D('flex:1;min-height:0;overflow:hidden;padding:' + pad + 'px;display:flex;flex-direction:column;gap:16px;position:relative', Header(), ...pageBody()) const content = isPicker ? (s.field ? FEditor() : Editor()) : D('flex:1;min-height:0;overflow:hidden;padding:' + pad + 'px;display:flex;flex-direction:column;gap:16px;position:relative', Header(), ...pageBody())
const dragOv = s.drag && D('position:absolute;z-index:35;inset:' + (m ? 8 : 12) + 'px;top:' + (m ? 64 : 60) + 'px;border:2px dashed var(--ui-primary);background:var(--rc-sand);color:var(--rc-on-sand);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;text-align:center', I('upload', 28), S('font-weight:600;font-size:16px', 'Drop images to upload'), S('color:var(--rc-on-sand)', 'PNG, JPEG, WEBP, SVG · max 10 MB each')) const dragOv = s.drag && D('position:absolute;z-index:35;inset:' + (m ? 8 : 12) + 'px;top:' + (m ? 64 : 60) + 'px;border:2px dashed var(--ui-primary);background:var(--rc-sand);color:var(--rc-on-sand);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;text-align:center', I('upload', 28), S('font-weight:600;font-size:16px', 'Drop images to upload'), S('color:var(--rc-on-sand)', 'PNG, JPEG, WEBP, SVG · max 10 MB each'))
const fab = m && !isPicker && !(sel.length) && !s.panel && !s.modal && !s.error && s.empty !== 'first' && !s.drag && D('position:absolute;left:16px;right:16px;bottom:16px;height:48px;display:flex;align-items:center;justify-content:center;gap:8px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500;font-size:15px;box-shadow:var(--rc-shadow-pop);opacity:' + (s.limited || s.offline ? 0.4 : 1), I(s.limited ? 'timer' : 'upload', 18), s.limited ? 'Try again in 0:42' : 'Upload') const fab = m && !isPicker && !(sel.length) && !s.panel && !s.modal && !s.error && s.empty !== 'first' && !s.drag && D('position:absolute;left:16px;right:16px;bottom:16px;height:48px;display:flex;align-items:center;justify-content:center;gap:8px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500;font-size:15px;box-shadow:var(--rc-shadow-pop);opacity:' + (s.limited || s.offline ? 0.4 : 1), I(s.limited ? 'timer' : 'upload', 18), s.limited ? 'Try again in 0:42' : 'Upload')
const ann = s.ann && D('position:absolute;z-index:20;' + (m ? 'left:16px;bottom:24px' : 'left:248px;bottom:20px'), Note(s.ann)) const ann = s.ann && D('position:absolute;z-index:20;' + (m ? 'left:16px;bottom:24px' : 'left:248px;bottom:20px'), Note(s.ann))
const main = D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column', offline, content) const main = D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column', offline, content)
const ov = D('display:contents', dragOv, fab, ann, sel.length > 0 && !s.panel && !s.modal && BulkBar(), s.panel && Panel(), isPicker && s.picker && Picker(), s.modal && Modal(), s.toasts && Toasts()) const ov = D('display:contents', dragOv, fab, ann, sel.length > 0 && !s.panel && !s.modal && BulkBar(), s.panel && Panel(), isPicker && s.picker && Picker(), s.modal && Modal(), s.toasts && Toasts())
const shell = { kind: 'slot', display: 'Marta Alves', nav: navKey, crumbs, mTitle: isPicker ? 'Edit article' : 'Media', mLead: isPicker ? 'arrow-left' : undefined, mAction: isPicker ? 'ellipsis' : undefined } const shell = { kind: 'slot', display: 'Marta Alves', nav: navKey, crumbs, mTitle: isPicker ? (s.field ? 'Lime plaster workshop' : 'Edit article') : 'Media', mLead: isPicker ? 'arrow-left' : undefined, mAction: isPicker ? 'ellipsis' : undefined, ...(s.field ? { content: [{ key: 'events', name: 'Events', icon: 'files' }, { key: 'recipes', name: 'Recipes', icon: 'files' }, { key: 'press-mentions', name: 'Press mentions', icon: 'files' }], contentOn: 'events' } : {}) }
return { shell, mob: m, main, ov } return { shell, mob: m, main, ov }
} }
} }
@@ -17,7 +17,7 @@
<div style="display:flex;align-items:flex-end;gap:32px;max-width:1400px"> <div style="display:flex;align-items:flex-end;gap:32px;max-width:1400px">
<div style="flex:1;display:flex;flex-direction:column;gap:10px"> <div style="flex:1;display:flex;flex-direction:column;gap:10px">
<h1 style="margin:0;font:600 36px/44px 'IBM Plex Sans',sans-serif;letter-spacing:-0.02em;color:var(--ui-text-highlighted)">Screens: custom content types</h1> <h1 style="margin:0;font:600 36px/44px 'IBM Plex Sans',sans-serif;letter-spacing:-0.02em;color:var(--ui-text-highlighted)">Screens: custom content types</h1>
<p style="margin:0;max-width:900px;font-size:16px;line-height:26px;color:var(--ui-text-toned);text-wrap:pretty">Schema list, builder, change review, field-type gallery, content navigation, entry list and entry editor, plus the later screens: relations, permissions, export and import. Every state at 1440 px (shown at 50%) and 390 px (shown at 75%); the switch shows dark. Each state is tagged <b>Available now</b> or <b>Later</b>. Spec tables at the end: scope, routes, components with their Nuxt UI mapping, errors, needs backend, decisions, accessibility. Same shell, tokens and copy tone as <a href="RenewCMS Screens Back-office.dc.html">the back-office board</a>. Changed in AppFrame: a Schema item and a Content group in the sidebar and the mobile drawer.</p> <p style="margin:0;max-width:900px;font-size:16px;line-height:26px;color:var(--ui-text-toned);text-wrap:pretty">Schema list, builder, change review, field-type gallery, content navigation, entry list and entry editor, plus the later screens: relations, permissions, export and import. Every state at 1440 px (shown at 50%) and 390 px (shown at 75%); the switch shows dark. Each state is tagged <b>Available now</b> or <b>Later</b>. Spec tables at the end: scope, routes, components with their Nuxt UI mapping, errors, needs backend, decisions, accessibility. Same shell, tokens and copy tone as <a href="RenewCMS Screens Back-office.dc.html">the back-office board</a>. New field type Media (one library image) is drawn inside groups 1 to 6, plus groups 10 (picker) and 11 (media library usage), and the tables "Media field: …" at the end. Changed in AppFrame: a Schema item and a Content group in the sidebar and the mobile drawer.</p>
</div> </div>
<div role="radiogroup" aria-label="Theme" style="display:flex;border:1px solid var(--ui-border-accented);background:var(--ui-bg)"> <div role="radiogroup" aria-label="Theme" style="display:flex;border:1px solid var(--ui-border-accented);background:var(--ui-bg)">
<sc-for list="{{ modes }}" as="m" hint-placeholder-count="3"> <sc-for list="{{ modes }}" as="m" hint-placeholder-count="3">
@@ -37,8 +37,8 @@
<div style="display:flex;flex-direction:column;gap:12px;width:1037px"> <div style="display:flex;flex-direction:column;gap:12px;width:1037px">
<div style="display:flex;flex-direction:column;gap:2px"><span style="font:600 16px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ st.name }}<span style="margin-left:10px;padding:1px 6px;border:{{ st.chipBd }};color:var(--ui-text-toned);font:500 11px/16px 'IBM Plex Mono',monospace;vertical-align:middle">{{ st.scopeLabel }}</span></span><span style="font-size:13px;color:var(--ui-text-muted)">{{ st.trigger }}</span></div> <div style="display:flex;flex-direction:column;gap:2px"><span style="font:600 16px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ st.name }}<span style="margin-left:10px;padding:1px 6px;border:{{ st.chipBd }};color:var(--ui-text-toned);font:500 11px/16px 'IBM Plex Mono',monospace;vertical-align:middle">{{ st.scopeLabel }}</span></span><span style="font-size:13px;color:var(--ui-text-muted)">{{ st.trigger }}</span></div>
<div style="display:flex;gap:24px;align-items:flex-start"> <div style="display:flex;gap:24px;align-items:flex-start">
<div style="width:720px;height:450px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:1440px;height:900px;zoom:0.5"><dc-import name="SchemaFrame" s="{{ st.s }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></div></div> <div style="width:720px;height:450px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:1440px;height:900px;zoom:0.5"><sc-if value="{{ st.isSchema }}"><dc-import name="SchemaFrame" s="{{ st.s }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></sc-if><sc-if value="{{ st.isMedia }}"><dc-import name="MediaFrame" s="{{ st.s }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></sc-if></div></div>
<div style="width:293px;height:633px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:390px;height:844px;zoom:0.75"><dc-import name="SchemaFrame" s="{{ st.s }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></div></div> <div style="width:293px;height:633px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:390px;height:844px;zoom:0.75"><sc-if value="{{ st.isSchema }}"><dc-import name="SchemaFrame" s="{{ st.s }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></sc-if><sc-if value="{{ st.isMedia }}"><dc-import name="MediaFrame" s="{{ st.s }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></sc-if></div></div>
</div> </div>
<p style="margin:0;font-size:12px;line-height:18px;color:var(--ui-text-muted);text-wrap:pretty"><b style="color:var(--ui-text-toned)">Copy:</b> {{ st.copy }}</p> <p style="margin:0;font-size:12px;line-height:18px;color:var(--ui-text-muted);text-wrap:pretty"><b style="color:var(--ui-text-toned)">Copy:</b> {{ st.copy }}</p>
</div> </div>
@@ -69,7 +69,7 @@ class Component extends DCLogic {
componentDidUpdate(p) { if (p.theme !== this.props.theme && this.props.theme) this.setState({ mode: this.props.theme }); this.apply() } componentDidUpdate(p) { if (p.theme !== this.props.theme && this.props.theme) this.setState({ mode: this.props.theme }); this.apply() }
renderVals() { renderVals() {
const modes = [['system', 'System'], ['light', 'Light'], ['dark', 'Dark']].map(([k, label]) => { const on = this.state.mode === k; return { label, on, bg: on ? 'var(--ui-primary)' : 'transparent', fg: on ? 'var(--ui-bg)' : 'var(--ui-text-toned)', pick: () => this.setState({ mode: k }) } }) const modes = [['system', 'System'], ['light', 'Light'], ['dark', 'Dark']].map(([k, label]) => { const on = this.state.mode === k; return { label, on, bg: on ? 'var(--ui-primary)' : 'transparent', fg: on ? 'var(--ui-bg)' : 'var(--ui-text-toned)', pick: () => this.setState({ mode: k }) } })
const groups = this.state.spec.groups.map(g => ({ ...g, states: g.states.map(s => ({ ...s, scopeLabel: s.scope === 'later' ? 'Later' : 'Available now', chipBd: s.scope === 'later' ? '1px dashed var(--ui-border-accented)' : '1px solid var(--ui-border-accented)' })) })) const groups = this.state.spec.groups.map(g => ({ ...g, states: g.states.map(s => ({ ...s, isMedia: !!(s.s && s.s.frame === 'media'), isSchema: !(s.s && s.s.frame === 'media'), scopeLabel: s.scope === 'later' ? 'Later' : 'Available now', chipBd: s.scope === 'later' ? '1px dashed var(--ui-border-accented)' : '1px solid var(--ui-border-accented)' })) }))
const tables = this.state.spec.tables.map(t => ({ ...t, rows: t.rows.map(r => ({ cells: r })) })) const tables = this.state.spec.tables.map(t => ({ ...t, rows: t.rows.map(r => ({ cells: r })) }))
return { rootRef: this.rootRef, modes, groups, tables } return { rootRef: this.rootRef, modes, groups, tables }
} }
+62 -33
View File
@@ -61,7 +61,7 @@ class Component extends DCLogic {
const Empty = (icon, title, text, action) => D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:40px 24px;display:flex;flex-direction:column;align-items:center;gap:12px;text-align:center', S('width:44px;height:44px;display:flex;align-items:center;justify-content:center;background:var(--ui-bg-elevated);color:var(--ui-text-toned)', I(icon, 20)), S('font-weight:600;font-size:15px;color:var(--ui-text-highlighted)', title), S('color:var(--ui-text-muted);max-width:360px;text-wrap:pretty', text), action && B(action, { k: 'primary', icon: 'plus', px: 16 })) const Empty = (icon, title, text, action) => D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:40px 24px;display:flex;flex-direction:column;align-items:center;gap:12px;text-align:center', S('width:44px;height:44px;display:flex;align-items:center;justify-content:center;background:var(--ui-bg-elevated);color:var(--ui-text-toned)', I(icon, 20)), S('font-weight:600;font-size:15px;color:var(--ui-text-highlighted)', title), S('color:var(--ui-text-muted);max-width:360px;text-wrap:pretty', text), action && B(action, { k: 'primary', icon: 'plus', px: 16 }))
// ---------- data // ---------- data
const FT = { text: ['type', 'Text', 'Short text, like a title or a name'], richtext: ['pilcrow', 'Rich text', 'Long text with formatting, written in Markdown'], number: ['hash', 'Number', 'Whole or decimal numbers'], boolean: ['toggle-left', 'Yes or no', 'An on or off switch'], date: ['calendar', 'Date', 'A calendar day, without a time'], select: ['list', 'Choice', 'One option from a list you define'] } const FT = { text: ['type', 'Text', 'Short text, like a title or a name'], richtext: ['pilcrow', 'Rich text', 'Long text with formatting, written in Markdown'], number: ['hash', 'Number', 'Whole or decimal numbers'], boolean: ['toggle-left', 'Yes or no', 'An on or off switch'], date: ['calendar', 'Date', 'A calendar day, without a time'], select: ['list', 'Choice', 'One option from a list you define'], media: ['image', 'Media', 'One image from your media library'] }
const EV = [ const EV = [
{ key: 'title', label: 'Title', type: 'text', req: true, uniq: true, max: 80 }, { key: 'starts_on', label: 'Starts on', type: 'date', req: true }, { key: 'ends_on', label: 'Ends on', type: 'date' }, { key: 'title', label: 'Title', type: 'text', req: true, uniq: true, max: 80 }, { key: 'starts_on', label: 'Starts on', type: 'date', req: true }, { key: 'ends_on', label: 'Ends on', type: 'date' },
{ key: 'online', label: 'Online', type: 'boolean', def: false }, { key: 'capacity', label: 'Capacity', type: 'number', min: 1, max: 5000 }, { key: 'category', label: 'Category', type: 'select', opts: ['Talk', 'Workshop', 'Meetup'] }, { key: 'description', label: 'Description', type: 'richtext' }].map(f => ({ ...f, saved: true })) { key: 'online', label: 'Online', type: 'boolean', def: false }, { key: 'capacity', label: 'Capacity', type: 'number', min: 1, max: 5000 }, { key: 'category', label: 'Category', type: 'select', opts: ['Talk', 'Workshop', 'Meetup'] }, { key: 'description', label: 'Description', type: 'richtext' }].map(f => ({ ...f, saved: true }))
@@ -81,6 +81,7 @@ class Component extends DCLogic {
{ id: 38, title: 'Timber joinery for beginners', starts_on: '14 Jan 2027', ends_on: '15 Jan 2027', online: false, capacity: 12, category: 'Workshop', description: 'Mortise, tenon and a lot of patience.', c: '28 Sep 2026', u: '7 Oct 2026, 10:05', by: 'Inès Duarte' }, { id: 38, title: 'Timber joinery for beginners', starts_on: '14 Jan 2027', ends_on: '15 Jan 2027', online: false, capacity: 12, category: 'Workshop', description: 'Mortise, tenon and a lot of patience.', c: '28 Sep 2026', u: '7 Oct 2026, 10:05', by: 'Inès Duarte' },
{ id: 37, title: 'Q&A with the site managers', starts_on: '28 Oct 2026', ends_on: '', online: true, capacity: null, category: 'Meetup', description: '', c: '21 Sep 2026', u: '2 Oct 2026, 17:48', by: 'Jonas Pereira' }, { id: 37, title: 'Q&A with the site managers', starts_on: '28 Oct 2026', ends_on: '', online: true, capacity: null, category: 'Meetup', description: '', c: '21 Sep 2026', u: '2 Oct 2026, 17:48', by: 'Jonas Pereira' },
{ id: 36, title: 'Reclaimed floorboards talk', starts_on: '17 Oct 2026', ends_on: '', online: false, capacity: 60, category: 'Talk', description: 'Where to find them and how to lay them.', c: '14 Sep 2026', u: '29 Sep 2026, 08:30', by: 'Marta Alves' }] { id: 36, title: 'Reclaimed floorboards talk', starts_on: '17 Oct 2026', ends_on: '', online: false, capacity: 60, category: 'Talk', description: 'Where to find them and how to lay them.', c: '14 Sep 2026', u: '29 Sep 2026, 08:30', by: 'Marta Alves' }]
ROWS.forEach((r, i) => { r.thumbnail = ['ok', 'ok', '', 'miss', 'ok', '', 'ok'][i] })
const mdSample = 'Two days of hands-on work with **lime putty** and old stone.\n\n- Bring work clothes\n- Lunch is included' const mdSample = 'Two days of hands-on work with **lime putty** and old stone.\n\n- Bring work clothes\n- Lunch is included'
const sampleVal = f => f.type === 'text' ? (f.def ?? 'Example text') : f.type === 'richtext' ? (f.def ?? 'Markdown text') : f.type === 'number' ? (f.def ?? f.min ?? 0) : f.type === 'boolean' ? (f.def ?? false) : f.type === 'date' ? (f.def ?? '2026-11-21') : (f.def ?? (f.opts && f.opts[0]) ?? null) const sampleVal = f => f.type === 'text' ? (f.def ?? 'Example text') : f.type === 'richtext' ? (f.def ?? 'Markdown text') : f.type === 'number' ? (f.def ?? f.min ?? 0) : f.type === 'boolean' ? (f.def ?? false) : f.type === 'date' ? (f.def ?? '2026-11-21') : (f.def ?? (f.opts && f.opts[0]) ?? null)
const apiJson = (fs_, key) => JSON.stringify({ id: 42, content_type: key, data: Object.fromEntries(fs_.map(f => [f.key, sampleVal(f)])), created_by: 3, updated_by: 3, created_at: '2026-10-15T11:02:00Z', updated_at: '2026-10-15T11:02:00Z' }, null, 2) const apiJson = (fs_, key) => JSON.stringify({ id: 42, content_type: key, data: Object.fromEntries(fs_.map(f => [f.key, sampleVal(f)])), created_by: 3, updated_by: 3, created_at: '2026-10-15T11:02:00Z', updated_at: '2026-10-15T11:02:00Z' }, null, 2)
@@ -88,6 +89,23 @@ class Component extends DCLogic {
const dot = (t, ic) => S('display:inline-flex;align-items:center;gap:6px', I(ic, 14), t) const dot = (t, ic) => S('display:inline-flex;align-items:center;gap:6px', I(ic, 14), t)
// ---------- inspector // ---------- inspector
const stripe = 'repeating-linear-gradient(135deg,var(--ui-bg-elevated) 0 6px,var(--ui-bg-accented) 6px 7px)'
const THUMB = { key: 'thumbnail', label: 'Thumbnail', type: 'media', saved: true }
const Ph = (w, hh, ex, ...c) => D('width:' + w + ';' + (hh ? 'height:' + hh + ';' : '') + 'flex-shrink:0;box-sizing:border-box;display:flex;align-items:center;justify-content:center;background:' + stripe + ';color:var(--ui-text-toned);' + mono + 'font-size:11px;line-height:16px;' + (ex || ''), ...c)
const Miss = (w, hh, ic = 'image-off', z = 20, ex = '') => h('div', { role: 'img', 'aria-label': 'Image no longer in the library', style: P('width:' + w + ';' + (hh ? 'height:' + hh + ';' : '') + 'flex-shrink:0;display:flex;align-items:center;justify-content:center;border:1px dashed var(--ui-border-accented);color:var(--ui-text-muted);box-sizing:border-box;' + ex) }, I(ic, z))
const cellM = (st, z) => st === 'ok' ? Ph(z + 'px', z + 'px', '') : st === 'miss' ? Miss(z + 'px', z + 'px', 'unlink', z > 32 ? 14 : 12) : S('color:var(--ui-text-muted);width:' + z + 'px;text-align:center;display:inline-block', '–')
const MThumb = o => D('position:relative;flex-shrink:0;box-sizing:border-box;overflow:hidden;width:' + (m ? '100%' : '160px') + ';' + (m ? 'aspect-ratio:16/9;' : 'height:120px;') + 'border:1px solid ' + (o.hover && !m ? 'var(--ui-text-muted)' : 'var(--ui-border-accented)') + ';' + (o.focus ? 'outline:2px solid var(--ui-primary);outline-offset:2px;' : '') + 'opacity:' + (o.dis ? 0.6 : 1), Ph('100%', '100%', '', '1600 × 900'), o.hover && !m && D('position:absolute;left:0;right:0;bottom:0;height:28px;display:flex;align-items:center;justify-content:center;gap:6px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font-size:12px;font-weight:500', I('image', 14), 'Change image'))
const MCtl = (f, o = {}) => {
const dis = !!o.dis, st = o.st || 'empty'
const bd = o.err ? 'border:1px solid var(--ui-error);box-shadow:inset 0 0 0 1px var(--ui-error);' : st === 'empty' ? 'border:1px dashed var(--ui-border-accented);' : 'border:1px solid var(--ui-border-accented);'
const row = (...c) => D('display:flex;flex-direction:' + (m ? 'column' : 'row') + ';gap:' + (m ? 12 : 16) + 'px;padding:12px;align-items:' + (m ? 'stretch' : 'flex-start'), ...c)
const col = (...c) => D('flex:1;min-width:0;display:flex;flex-direction:column;gap:12px;' + (m ? '' : 'justify-content:space-between;min-height:120px'), ...c)
let inner
if (st === 'empty') inner = D('display:flex;flex-direction:' + (m ? 'column' : 'row') + ';align-items:' + (m ? 'stretch' : 'center') + ';gap:12px;padding:12px', D('display:flex;align-items:center;gap:12px;flex:1;min-width:0', S('width:40px;height:40px;display:flex;align-items:center;justify-content:center;background:var(--ui-bg-elevated);color:var(--ui-text-toned);flex-shrink:0', I('image', 20)), S('color:var(--ui-text-muted)', 'No image selected.')), B('Pick an image', { icon: 'image-plus', dis, ring: o.ringBtn === 'pick' }))
else if (st === 'filled') inner = row(MThumb(o), col(D('display:flex;flex-direction:column;gap:2px;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', 'lime-plaster-workshop.jpg'), S('color:var(--ui-text-muted);font-size:12px;line-height:18px', '1600 × 900 · 240 KB')), D('display:flex;gap:8px', B('Change image', { icon: 'image', dis, full: m }), B('Remove', { k: 'ghost', icon: 'x', dis, full: m }))))
else inner = row(Miss(m ? '100%' : '160px', m ? null : '120px', 'image-off', 24, (m ? 'aspect-ratio:16/9;' : '') + (dis ? 'opacity:0.6;' : '')), col(D('display:flex;flex-direction:column;gap:4px', S('font-weight:500;color:var(--ui-text-highlighted)', 'This image is no longer in the library'), S('color:var(--ui-text-muted);font-size:12px;line-height:18px;text-wrap:pretty', f.req ? 'Thumbnail is required. Choose another image to save.' : 'You can still save. The entry keeps the link until you change it.')), D('display:flex;gap:8px;flex-wrap:wrap', B('Choose another image', { icon: 'image', dis, ring: o.ringBtn === 'choose', full: m }), B('Clear', { k: 'ghost', dis, full: m }))))
return D('display:flex;flex-direction:column;gap:6px;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', f.label, f.req && ' *'), D(bd + 'background:var(--ui-bg);box-sizing:border-box', inner), o.err ? S('display:flex;gap:6px;align-items:flex-start;color:var(--ui-error);font-size:12px;line-height:18px', I('circle-alert', 14, 'margin-top:2px'), o.err) : st === 'missing' ? null : S('color:var(--ui-text-muted);font-size:12px;line-height:18px', 'One image from your library.'))
}
const Insp = (f, o = {}) => { const Insp = (f, o = {}) => {
const t = f.type, e = f.err || {}, one = m || o.one, locked = !!f.saved const t = f.type, e = f.err || {}, one = m || o.one, locked = !!f.saved
const [mnL, mxL, suf] = MM(t), canU = ['text', 'number', 'date', 'select'].includes(t), hasMM = ['text', 'richtext', 'number', 'date'].includes(t) const [mnL, mxL, suf] = MM(t), canU = ['text', 'number', 'date', 'select'].includes(t), hasMM = ['text', 'richtext', 'number', 'date'].includes(t)
@@ -96,15 +114,15 @@ class Component extends DCLogic {
const mmErr = e.min || '' const mmErr = e.min || ''
const minV = f.min != null ? String(f.min) : '', maxV = f.max != null ? String(f.max) : '' const minV = f.min != null ? String(f.min) : '', maxV = f.max != null ? String(f.max) : ''
const defCtl = t === 'boolean' ? null : F('Default value', f.def != null ? String(f.def) : '', { opt: true, ph: f.def == null, phText: t === 'select' ? 'None' : t === 'date' ? 'No default' : 'No default', sel: t === 'select', ico: t === 'date' ? 'calendar' : null, area: t === 'richtext', err: e.def, dis: !!f.uniq, help: f.uniq ? 'A field with unique values can\'t have a default.' : e.def ? '' : 'Used when an entry is created and this field is left out.' }) const defCtl = t === 'boolean' ? null : F('Default value', f.def != null ? String(f.def) : '', { opt: true, ph: f.def == null, phText: t === 'select' ? 'None' : t === 'date' ? 'No default' : 'No default', sel: t === 'select', ico: t === 'date' ? 'calendar' : null, area: t === 'richtext', err: e.def, dis: !!f.uniq, help: f.uniq ? 'A field with unique values can\'t have a default.' : e.def ? '' : 'Used when an entry is created and this field is left out.' })
const left = D('display:flex;flex-direction:column;min-width:0;border-top:1px solid var(--ui-border)', SwR(!!f.req, 'Required', 'An entry can\'t be saved with this field empty.'), SwR(!!f.uniq, 'Unique values', canU ? 'Each entry needs a different value.' : t === 'richtext' ? 'Not available for rich text.' : 'Not available for yes or no fields.', !canU), t === 'boolean' && SwR(!!f.def, 'On by default', 'New entries start with this switch ' + (f.def ? 'on' : 'off') + ' when the field is left out.')) const left = D('display:flex;flex-direction:column;min-width:0;border-top:1px solid var(--ui-border)', SwR(!!f.req, 'Required', 'An entry can\'t be saved with this field empty.'), t !== 'media' && SwR(!!f.uniq, 'Unique values', canU ? 'Each entry needs a different value.' : t === 'richtext' ? 'Not available for rich text.' : 'Not available for yes or no fields.', !canU), t === 'boolean' && SwR(!!f.def, 'On by default', 'New entries start with this switch ' + (f.def ? 'on' : 'off') + ' when the field is left out.'))
const right = hasMM ? [F(mnL, minV, { suffix: suf, ph: minV === '', phText: 'No minimum', err: mmErr, help: mmErr ? '' : null }), F(mxL, maxV, { suffix: suf, ph: maxV === '', phText: 'No maximum', help: mmErr ? '' : t === 'text' || t === 'richtext' ? 'Counted in characters. Entries show a counter.' : t === 'number' ? 'Entries outside the range are refused.' : 'Entries outside the range are refused.' }), defCtl] : [defCtl, D('display:flex;flex-direction:column;gap:6px;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', 'Limits'), S('color:var(--ui-text-muted);font-size:12px;line-height:18px', t === 'boolean' ? 'Yes or no fields have no limits.' : 'Limits come from the choices below.'))] const right = t === 'media' ? [] : hasMM ? [F(mnL, minV, { suffix: suf, ph: minV === '', phText: 'No minimum', err: mmErr, help: mmErr ? '' : null }), F(mxL, maxV, { suffix: suf, ph: maxV === '', phText: 'No maximum', help: mmErr ? '' : t === 'text' || t === 'richtext' ? 'Counted in characters. Entries show a counter.' : t === 'number' ? 'Entries outside the range are refused.' : 'Entries outside the range are refused.' }), defCtl] : [defCtl, D('display:flex;flex-direction:column;gap:6px;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', 'Limits'), S('color:var(--ui-text-muted);font-size:12px;line-height:18px', t === 'boolean' ? 'Yes or no fields have no limits.' : 'Limits come from the choices below.'))]
const ch = t === 'select' ? Choices(f) : null const ch = t === 'select' ? Choices(f) : t === 'media' ? D('display:flex;gap:8px;padding:10px 12px;background:var(--rc-info-soft);color:var(--ui-info)', S('padding-top:2px;display:flex', I('info', 16)), S('color:var(--ui-text-toned);text-wrap:pretty', 'Holds one image from the media library. Entries link to the image instead of keeping a copy, so they always show its current version.')) : null
return D('display:flex;flex-direction:column;gap:' + (m ? 16 : 14) + 'px;min-width:0', return D('display:flex;flex-direction:column;gap:' + (m ? 16 : 14) + 'px;min-width:0',
D('display:grid;grid-template-columns:' + g2 + ';gap:14px', F('Label', f.label, { req: true, err: e.label, focus: o.focus === 'label', ph: !f.label, phText: 'For example, Title' }), D('display:grid;grid-template-columns:' + g2 + ';gap:14px', F('Label', f.label, { req: true, err: e.label, focus: o.focus === 'label', ph: !f.label, phText: 'For example, Title' }),
D('display:flex;flex-direction:column;gap:6px;min-width:0', F('Key', f.key || '', { mono: true, auto: !locked && !e.key && !!f.key, lock: locked, err: e.key, ph: !f.key, phText: 'title', dis: false, help: locked ? 'Used in the API, so it can\'t change.' : e.key ? '' : 'The name used in the API. Starts with a letter. Lowercase letters, digits and underscores.' }))), D('display:flex;flex-direction:column;gap:6px;min-width:0', F('Key', f.key || '', { mono: true, auto: !locked && !e.key && !!f.key, lock: locked, err: e.key, ph: !f.key, phText: 'title', dis: false, help: locked ? 'Used in the API, so it can\'t change.' : e.key ? '' : 'The name used in the API. Starts with a letter. Lowercase letters, digits and underscores.' }))),
D('display:flex;flex-direction:column;gap:6px', D('display:flex;justify-content:space-between;gap:8px', S('font-weight:500;color:var(--ui-text-highlighted)', 'Type'), locked && S('color:var(--ui-text-muted);font-size:12px;display:flex;gap:4px;align-items:center', I('lock', 12), 'Can\'t change after saving')), D('display:grid;grid-template-columns:repeat(' + (one ? 2 : 3) + ',minmax(0,1fr));gap:8px', ...Object.keys(FT).map(tile))), D('display:flex;flex-direction:column;gap:6px', D('display:flex;justify-content:space-between;gap:8px', S('font-weight:500;color:var(--ui-text-highlighted)', 'Type'), locked && S('color:var(--ui-text-muted);font-size:12px;display:flex;gap:4px;align-items:center', I('lock', 12), 'Can\'t change after saving')), D('display:grid;grid-template-columns:repeat(' + (one ? 2 : 3) + ',minmax(0,1fr));gap:8px', ...Object.keys(FT).map(tile))),
left, left,
D('display:grid;grid-template-columns:' + g2 + ';gap:14px;align-items:start', ...right.filter(Boolean)), right.length > 0 && D('display:grid;grid-template-columns:' + g2 + ';gap:14px;align-items:start', ...right.filter(Boolean)),
ch) ch)
} }
const Choices = f => { const Choices = f => {
@@ -141,6 +159,7 @@ class Component extends DCLogic {
const Cal = () => { const cells = [...Array(6).fill(''), ...Array.from({ length: 30 }, (_, i) => i + 1)]; return D('width:' + (m ? 280 : 252) + 'px;padding:8px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop)', D('display:flex;align-items:center;justify-content:space-between;height:32px', IB('chevron-left'), S('font-weight:600', 'November 2026'), IB('chevron-right')), D('display:grid;grid-template-columns:repeat(7,1fr)', ...['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'].map(d => S('height:28px;display:flex;align-items:center;justify-content:center;font-size:12px;color:var(--ui-text-muted)', d)), ...cells.map(c => S('height:' + (m ? 34 : 30) + 'px;display:flex;align-items:center;justify-content:center;background:' + (c === 21 ? 'var(--ui-primary)' : 'transparent') + ';color:' + (c === 21 ? 'var(--ui-bg)' : 'var(--ui-text-highlighted)'), c))) ) } const Cal = () => { const cells = [...Array(6).fill(''), ...Array.from({ length: 30 }, (_, i) => i + 1)]; return D('width:' + (m ? 280 : 252) + 'px;padding:8px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop)', D('display:flex;align-items:center;justify-content:space-between;height:32px', IB('chevron-left'), S('font-weight:600', 'November 2026'), IB('chevron-right')), D('display:grid;grid-template-columns:repeat(7,1fr)', ...['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'].map(d => S('height:28px;display:flex;align-items:center;justify-content:center;font-size:12px;color:var(--ui-text-muted)', d)), ...cells.map(c => S('height:' + (m ? 34 : 30) + 'px;display:flex;align-items:center;justify-content:center;background:' + (c === 21 ? 'var(--ui-primary)' : 'transparent') + ';color:' + (c === 21 ? 'var(--ui-bg)' : 'var(--ui-text-highlighted)'), c))) ) }
const Ctl = (f, o = {}) => { const Ctl = (f, o = {}) => {
const t = f.type, v = o.v == null ? '' : String(o.v) const t = f.type, v = o.v == null ? '' : String(o.v)
if (t === 'media') return MCtl(f, o)
const lab = D('display:flex;justify-content:space-between;gap:8px', S('font-weight:500;color:var(--ui-text-highlighted)', f.label, f.req && ' *'), o.count && S(mono + 'font-size:12px;color:' + (o.countErr ? 'var(--ui-error)' : 'var(--ui-text-muted)'), o.count), o.def && Bd('Default', 'neu')) const lab = D('display:flex;justify-content:space-between;gap:8px', S('font-weight:500;color:var(--ui-text-highlighted)', f.label, f.req && ' *'), o.count && S(mono + 'font-size:12px;color:' + (o.countErr ? 'var(--ui-error)' : 'var(--ui-text-muted)'), o.count), o.def && Bd('Default', 'neu'))
const bd = o.err ? 'var(--ui-error)' : o.focus ? 'var(--ui-primary)' : 'var(--ui-border-accented)' const bd = o.err ? 'var(--ui-error)' : o.focus ? 'var(--ui-primary)' : 'var(--ui-border-accented)'
const box = (...inner) => D('display:flex;align-items:center;min-height:' + ih + 'px;border:1px solid ' + bd + ';background:' + (o.dis ? 'var(--ui-bg-elevated)' : 'var(--ui-bg)') + ';font-size:' + fs + 'px;' + (o.err ? 'box-shadow:inset 0 0 0 1px var(--ui-error);' : o.focus ? 'box-shadow:inset 0 0 0 1px var(--ui-primary);' : ''), ...inner) const box = (...inner) => D('display:flex;align-items:center;min-height:' + ih + 'px;border:1px solid ' + bd + ';background:' + (o.dis ? 'var(--ui-bg-elevated)' : 'var(--ui-bg)') + ';font-size:' + fs + 'px;' + (o.err ? 'box-shadow:inset 0 0 0 1px var(--ui-error);' : o.focus ? 'box-shadow:inset 0 0 0 1px var(--ui-primary);' : ''), ...inner)
@@ -157,6 +176,7 @@ class Component extends DCLogic {
} }
const Cell = (f, v) => { const Cell = (f, v) => {
if (v === undefined || v === null || v === '') return S('color:var(--ui-text-muted)', '–') if (v === undefined || v === null || v === '') return S('color:var(--ui-text-muted)', '–')
if (f.type === 'media') return cellM(v, 40)
if (f.type === 'boolean') return S('display:flex;align-items:center;gap:6px', I(v ? 'check' : 'minus', 14, 'color:var(--ui-text-muted)'), v ? 'Yes' : 'No') if (f.type === 'boolean') return S('display:flex;align-items:center;gap:6px', I(v ? 'check' : 'minus', 14, 'color:var(--ui-text-muted)'), v ? 'Yes' : 'No')
if (f.type === 'select') return S('height:20px;padding:0 6px;display:inline-flex;align-items:center;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned);font-size:12px;justify-self:start', v) if (f.type === 'select') return S('height:20px;padding:0 6px;display:inline-flex;align-items:center;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned);font-size:12px;justify-self:start', v)
if (f.type === 'number') return S('justify-self:end;font-variant-numeric:tabular-nums', v) if (f.type === 'number') return S('justify-self:end;font-variant-numeric:tabular-nums', v)
@@ -183,12 +203,13 @@ class Component extends DCLogic {
const newBtn = B('New content type', { k: 'primary', icon: 'plus', px: 14, dis: k === 'loading' }) const newBtn = B('New content type', { k: 'primary', icon: 'plus', px: 14, dis: k === 'loading' })
const impExp = s.later ? [B('Import', { icon: 'upload' }), B('Export', { icon: 'download' })] : [] const impExp = s.later ? [B('Import', { icon: 'upload' }), B('Export', { icon: 'download' })] : []
if (k === 'forbidden') { shell.role = 'user'; shell.crumbs = ['Schema']; main = Center('lock', 'You don\'t have access to Schema', 'Only owners and admins can change content types. You can still add and edit entries from the Content menu.', B('Go to Home', { k: 'primary', px: 16 })) } if (k === 'forbidden') { shell.role = 'user'; shell.crumbs = ['Schema']; main = Center('lock', 'You don\'t have access to Schema', 'Only owners and admins can change content types. You can still add and edit entries from the Content menu.', B('Go to Home', { k: 'primary', px: 16 })) }
else if (k === 'builtin') { else if (k === 'builtin' || k === 'customro') {
shell.crumbs = ['Schema', 'Articles']; shell.mTitle = 'Articles'; shell.mLead = 'arrow-left' const cr = k === 'customro'
const AF = [['Title', 'title', 'text', 'Required · up to 200 characters'], ['Slug', 'slug', 'text', 'Required · unique'], ['Body', 'body', 'richtext', 'Up to 10,000 characters'], ['Online', 'online', 'boolean', 'Off by default'], ['Published on', 'published_on', 'date', '']] shell.crumbs = ['Schema', cr ? 'Events' : 'Articles']; shell.mTitle = cr ? 'Events' : 'Articles'; shell.mLead = 'arrow-left'
const AF = cr ? [['Title', 'title', 'text', 'Required · unique · up to 80 characters'], ['Starts on', 'starts_on', 'date', 'Required'], ['Category', 'category', 'select', 'Talk, Workshop, Meetup'], ['Description', 'description', 'richtext', ''], ['Thumbnail', 'thumbnail', 'media', 'One image from the library']] : [['Title', 'title', 'text', 'Required · up to 200 characters'], ['Slug', 'slug', 'text', 'Required · unique'], ['Body', 'body', 'richtext', 'Up to 10,000 characters'], ['Online', 'online', 'boolean', 'Off by default'], ['Published on', 'published_on', 'date', '']]
const cols = '28px minmax(0,1fr) minmax(0,1fr) 120px minmax(0,1.2fr)' const cols = '28px minmax(0,1fr) minmax(0,1fr) 120px minmax(0,1.2fr)'
main = Page(pad, D('display:flex;align-items:center;gap:12px;flex-shrink:0', I('lock', 18, 'color:var(--ui-text-muted)'), S('font:600 20px/28px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', 'Articles'), Bd('Built-in', 'built', 'lock')), main = Page(pad, D('display:flex;align-items:center;gap:12px;flex-shrink:0', I('lock', 18, 'color:var(--ui-text-muted)'), S('font:600 20px/28px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', cr ? 'Events' : 'Articles'), cr ? Bd('Read only', 'built', 'lock') : Bd('Built-in', 'built', 'lock')),
Alert('info', 'info', 'Managed by RenewCMS', 'Articles is a built-in type. You can read its fields here, but you can\'t edit it, delete it or add fields.'), cr ? Alert('info', 'info', 'You can read these fields here', 'Only an owner or admin can change a content type.') : Alert('info', 'info', 'Managed by RenewCMS', 'Articles is a built-in type. You can read its fields here, but you can\'t edit it, delete it or add fields.'),
m ? D('background:var(--ui-bg);border:1px solid var(--ui-border)', ...AF.map(f => D('display:flex;gap:12px;align-items:center;padding:12px 16px;border-top:1px solid var(--ui-border);min-height:64px', S('width:28px;height:28px;display:flex;align-items:center;justify-content:center;background:var(--ui-bg-elevated)', I(FT[f[2]][0], 16)), D('flex:1;min-width:0;display:flex;flex-direction:column', S('font-weight:500', f[0]), S('font-size:12px;color:var(--ui-text-muted)', S(mono, f[1]), f[3] ? ' · ' + f[3] : ''))))) : m ? D('background:var(--ui-bg);border:1px solid var(--ui-border)', ...AF.map(f => D('display:flex;gap:12px;align-items:center;padding:12px 16px;border-top:1px solid var(--ui-border);min-height:64px', S('width:28px;height:28px;display:flex;align-items:center;justify-content:center;background:var(--ui-bg-elevated)', I(FT[f[2]][0], 16)), D('flex:1;min-width:0;display:flex;flex-direction:column', S('font-weight:500', f[0]), S('font-size:12px;color:var(--ui-text-muted)', S(mono, f[1]), f[3] ? ' · ' + f[3] : ''))))) :
D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('display:grid;grid-template-columns:' + cols + ';gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', S('', ''), S('', 'Label'), S('', 'Key'), S('', 'Type'), S('', 'Rules')), ...AF.map(f => D('display:grid;grid-template-columns:' + cols + ';gap:12px;height:48px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border)', I(FT[f[2]][0], 16, 'color:var(--ui-text-toned)'), S('font-weight:500', f[0]), S(mono + 'font-size:12px;color:var(--ui-text-muted)', f[1]), S('', FT[f[2]][1]), S('color:var(--ui-text-muted)', f[3] || '–')))), S('color:var(--ui-text-muted);font-size:12px', 'Entries of built-in types are managed from their own screens, like Articles and Authors.')) D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('display:grid;grid-template-columns:' + cols + ';gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', S('', ''), S('', 'Label'), S('', 'Key'), S('', 'Type'), S('', 'Rules')), ...AF.map(f => D('display:grid;grid-template-columns:' + cols + ';gap:12px;height:48px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border)', I(FT[f[2]][0], 16, 'color:var(--ui-text-toned)'), S('font-weight:500', f[0]), S(mono + 'font-size:12px;color:var(--ui-text-muted)', f[1]), S('', FT[f[2]][1]), S('color:var(--ui-text-muted)', f[3] || '–')))), S('color:var(--ui-text-muted);font-size:12px', 'Entries of built-in types are managed from their own screens, like Articles and Authors.'))
} else { } else {
@@ -203,12 +224,15 @@ class Component extends DCLogic {
} }
// 2 builder // 2 builder
const entN = v === 'review' && (k === 'mrefuse' || k === 'mclean') ? 12 : 37
const bld = () => { const bld = () => {
let fl = EV, name = 'Events', key = 'events', sel = 0, st = 'clean', isNew = false, api = k === 'api', kb = -1, tErr = {}, banner = null, removed = null, cause = false, tip = false, toast = null, info = true, nErr = 0 let fl = EV, name = 'Events', key = 'events', sel = 0, st = 'clean', isNew = false, api = k === 'api', kb = -1, tErr = {}, banner = null, removed = null, cause = false, tip = false, toast = null, info = true, nErr = 0
if (v === 'review') { const rk = k; if (rk === 'confirm' || rk === 'fallback') { fl = RC; name = 'Recipes'; key = 'recipes'; info = false } else if (rk === 'blocked') { sel = 0 } else { fl = DIRTY; sel = 4; st = 'dirty'; removed = EV[6] } } if (v === 'review') { const rk = k; if (rk === 'confirm' || rk === 'fallback') { fl = RC; name = 'Recipes'; key = 'recipes'; info = false } else if (rk === 'blocked') { sel = 0 } else if (rk === 'mrefuse' || rk === 'mclean') { fl = [...EV, { key: 'thumbnail', label: 'Thumbnail', type: 'media', isNew: true, req: rk === 'mrefuse' }]; sel = 7; st = 'dirty' } else { fl = DIRTY; sel = 4; st = 'dirty'; removed = EV[6] } }
if (v === 'rel') { } if (v === 'rel') { }
if (v === 'builder') { if (v === 'builder') {
if (k === 'locked') { sel = 1; tip = true } if (k === 'locked') { sel = 1; tip = true }
if (k === 'media' || k === 'mreq') { fl = [...EV, k === 'mreq' ? { ...THUMB, req: true } : THUMB]; sel = 7 }
if (k === 'mnew') { fl = [...EV, { key: 'thumbnail', label: 'Thumbnail', type: 'media', isNew: true }]; sel = 7; st = 'dirty' }
if (['dirty', 'saving', 'saved', 'fail', 'incompat', 'offline'].includes(k)) { fl = DIRTY; sel = 4; st = k === 'incompat' ? 'dirty' : k; removed = EV[6] } if (['dirty', 'saving', 'saved', 'fail', 'incompat', 'offline'].includes(k)) { fl = DIRTY; sel = 4; st = k === 'incompat' ? 'dirty' : k; removed = EV[6] }
if (k === 'saved') { removed = null; st = 'saved'; fl = DIRTY.map(f => ({ ...f, isNew: false, changed: false, saved: true })); toast = Toast('success', 'circle-check', 'Content type saved', 'Events now has 8 fields.') } if (k === 'saved') { removed = null; st = 'saved'; fl = DIRTY.map(f => ({ ...f, isNew: false, changed: false, saved: true })); toast = Toast('success', 'circle-check', 'Content type saved', 'Events now has 8 fields.') }
if (k === 'fail') banner = Alert('error', 'circle-x', 'Couldn\'t save the content type', 'Something went wrong on our side. Your changes are still here. Try again in a moment.', 'Try again') if (k === 'fail') banner = Alert('error', 'circle-x', 'Couldn\'t save the content type', 'Something went wrong on our side. Your changes are still here. Try again in a moment.', 'Try again')
@@ -227,7 +251,7 @@ class Component extends DCLogic {
const keyF = F('Key', key, { mono: true, lock: !isNew, auto: isNew && !!key && !tErr.key, err: tErr.key, ph: !key, phText: 'events', dis: dim, help: tErr.key ? '' : isNew ? 'Used in URLs and the API. Lowercase letters, digits and hyphens. It can\'t change after you save.' : null }) const keyF = F('Key', key, { mono: true, lock: !isNew, auto: isNew && !!key && !tErr.key, err: tErr.key, ph: !key, phText: 'events', dis: dim, help: tErr.key ? '' : isNew ? 'Used in URLs and the API. Lowercase letters, digits and hyphens. It can\'t change after you save.' : null })
const save = D('display:flex;align-items:center;gap:' + (m ? 8 : 12) + 'px;flex-shrink:0', !m && stChip(st, nErr), !m && B('Discard', { dis: st === 'clean' || st === 'saving' || st === 'saved' || (st === 'errs' && isNew && k === 'new') }), !m && B(st === 'saving' ? 'Saving…' : 'Save', { k: 'primary', icon: st === 'saving' ? 'loader-circle' : null, px: 16, dis: st === 'clean' || st === 'saved' || st === 'saving' || st === 'errs' || st === 'offline' })) const save = D('display:flex;align-items:center;gap:' + (m ? 8 : 12) + 'px;flex-shrink:0', !m && stChip(st, nErr), !m && B('Discard', { dis: st === 'clean' || st === 'saving' || st === 'saved' || (st === 'errs' && isNew && k === 'new') }), !m && B(st === 'saving' ? 'Saving…' : 'Save', { k: 'primary', icon: st === 'saving' ? 'loader-circle' : null, px: 16, dis: st === 'clean' || st === 'saved' || st === 'saving' || st === 'errs' || st === 'offline' }))
const top = m ? D('display:flex;flex-direction:column;gap:12px;padding:16px;flex-shrink:0;background:var(--ui-bg);border-bottom:1px solid var(--ui-border)', nameF, keyF) : D('display:flex;align-items:flex-start;gap:16px;padding:16px 24px;flex-shrink:0;background:var(--ui-bg);border-bottom:1px solid var(--ui-border);position:relative', D('width:320px', nameF), D('width:320px', keyF), D('flex:1'), D('display:flex;align-items:center;gap:12px;height:32px;margin-top:26px', save, IB('ellipsis')), tip && D('position:absolute;left:352px;top:84px;z-index:30', Tip('The key is used in URLs and the API, so it can\'t change after the type is created.'))) const top = m ? D('display:flex;flex-direction:column;gap:12px;padding:16px;flex-shrink:0;background:var(--ui-bg);border-bottom:1px solid var(--ui-border)', nameF, keyF) : D('display:flex;align-items:flex-start;gap:16px;padding:16px 24px;flex-shrink:0;background:var(--ui-bg);border-bottom:1px solid var(--ui-border);position:relative', D('width:320px', nameF), D('width:320px', keyF), D('flex:1'), D('display:flex;align-items:center;gap:12px;height:32px;margin-top:26px', save, IB('ellipsis')), tip && D('position:absolute;left:352px;top:84px;z-index:30', Tip('The key is used in URLs and the API, so it can\'t change after the type is created.')))
const infoBar = info && !isNew && D('flex-shrink:0;display:flex;align-items:center;gap:8px;padding:8px ' + (m ? 16 : 24) + 'px;background:var(--rc-info-soft);color:var(--ui-info);font-size:12px;line-height:18px', I('info', 14, 'flex-shrink:0'), S('color:var(--ui-text-toned)', '37 entries use this content type. Changes are checked against them when you save.')) const infoBar = info && !isNew && D('flex-shrink:0;display:flex;align-items:center;gap:8px;padding:8px ' + (m ? 16 : 24) + 'px;background:var(--rc-info-soft);color:var(--ui-info);font-size:12px;line-height:18px', I('info', 14, 'flex-shrink:0'), S('color:var(--ui-text-toned)', entN + ' entries use this content type. Changes are checked against them when you save.'))
const listHdr = D('display:flex;align-items:center;justify-content:space-between;height:28px', S('font-weight:600;color:var(--ui-text-highlighted)', 'Fields'), S(mono + 'font-size:12px;color:var(--ui-text-muted)', fl.length + ' of 50')) const listHdr = D('display:flex;align-items:center;justify-content:space-between;height:28px', S('font-weight:600;color:var(--ui-text-highlighted)', 'Fields'), S(mono + 'font-size:12px;color:var(--ui-text-muted)', fl.length + ' of 50'))
const live = kb >= 0 && D('padding:8px 10px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font-size:12px;line-height:18px', S('font-weight:600', 'Moving Ends on. Position 2 of 7.'), ' Press Up or Down to move, Space to drop, Esc to cancel.') const live = kb >= 0 && D('padding:8px 10px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font-size:12px;line-height:18px', S('font-weight:600', 'Moving Ends on. Position 2 of 7.'), ' Press Up or Down to move, Space to drop, Esc to cancel.')
const rows = fl.length ? fl.map((x, i) => FRow(x, i, { sel: m ? -1 : sel, kb, dim, cause })) : [D('display:flex;flex-direction:column;align-items:center;gap:8px;text-align:center;padding:32px 16px;border:1px dashed ' + (tErr.fields ? 'var(--ui-error)' : 'var(--ui-border-accented)'), I('rows-3', 20, 'color:var(--ui-text-muted)'), S('font-weight:600', 'No fields yet'), S('color:' + (tErr.fields ? 'var(--ui-error)' : 'var(--ui-text-muted)'), tErr.fields || 'Add the first field.'))] const rows = fl.length ? fl.map((x, i) => FRow(x, i, { sel: m ? -1 : sel, kb, dim, cause })) : [D('display:flex;flex-direction:column;align-items:center;gap:8px;text-align:center;padding:32px 16px;border:1px dashed ' + (tErr.fields ? 'var(--ui-error)' : 'var(--ui-border-accented)'), I('rows-3', 20, 'color:var(--ui-text-muted)'), S('font-weight:600', 'No fields yet'), S('color:' + (tErr.fields ? 'var(--ui-error)' : 'var(--ui-text-muted)'), tErr.fields || 'Add the first field.'))]
@@ -240,7 +264,7 @@ class Component extends DCLogic {
shell.nav = 'schema'; shell.crumbs = ['Schema', isNew ? 'New content type' : name]; shell.mTitle = isNew ? 'New content type' : name; shell.mLead = 'arrow-left'; shell.mAction = 'ellipsis' shell.nav = 'schema'; shell.crumbs = ['Schema', isNew ? 'New content type' : name]; shell.mTitle = isNew ? 'New content type' : name; shell.mLead = 'arrow-left'; shell.mAction = 'ellipsis'
shell.offline = false shell.offline = false
main = D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;position:relative', st === 'offline' && Offline(), top, infoBar, banner && D('padding:12px ' + (m ? 16 : 24) + 'px 0', banner), D('flex:1;min-height:0;display:flex;' + (m ? 'flex-direction:column' : ''), list, inspPane), m ? bar : ApiPanel(fl, key || 'events', api)) main = D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;position:relative', st === 'offline' && Offline(), top, infoBar, banner && D('padding:12px ' + (m ? 16 : 24) + 'px 0', banner), D('flex:1;min-height:0;display:flex;' + (m ? 'flex-direction:column' : ''), list, inspPane), m ? bar : ApiPanel(fl, key || 'events', api))
if (m && f && (s.sheet || (v === 'builder' && ['edit-sheet', 'choices'].includes(k)))) ov.push(Sheet({ title: 'Field: ' + (f.label || 'Untitled field') }, Insp(f), [B('Done', { k: 'primary', full: true })])) if (m && f && (s.sheet || (v === 'builder' && ['edit-sheet', 'choices', 'media', 'mreq', 'mnew'].includes(k)))) ov.push(Sheet({ title: 'Field: ' + (f.label || 'Untitled field') }, Insp(f), [B('Done', { k: 'primary', full: true })]))
if (m && api) ov.push(Sheet({ title: 'API preview' }, [S('color:var(--ui-text-muted);font-size:12px', 'GET /v1/content-type/' + key + '/entry'), S('display:block;flex:1;overflow:hidden;padding:10px 12px;background:var(--ui-bg-elevated);border:1px solid var(--ui-border);white-space:pre;' + mono + 'font-size:12px;line-height:19px;color:var(--ui-text-highlighted)', apiJson(fl, key))], [B('Copy JSON', { k: 'primary', full: true, icon: 'copy' })])) if (m && api) ov.push(Sheet({ title: 'API preview' }, [S('color:var(--ui-text-muted);font-size:12px', 'GET /v1/content-type/' + key + '/entry'), S('display:block;flex:1;overflow:hidden;padding:10px 12px;background:var(--ui-bg-elevated);border:1px solid var(--ui-border);white-space:pre;' + mono + 'font-size:12px;line-height:19px;color:var(--ui-text-highlighted)', apiJson(fl, key))], [B('Copy JSON', { k: 'primary', full: true, icon: 'copy' })]))
if (toast) ov.push(toast) if (toast) ov.push(toast)
} }
@@ -258,28 +282,29 @@ class Component extends DCLogic {
if (k === 'refused') ov.push(Shell({ title: 'Nothing was changed', desc: 'RenewCMS refused the changes because some entries don\'t fit the new fields. It doesn\'t say which entries.', w: 560, top: 60, close: true, cancel: 'Discard changes', confirm: 'Back to editing' }, [Alert('error', 'circle-x', 'Your content type is as it was', 'No field was added, changed or removed.'), S('font-weight:600;color:var(--ui-text-highlighted)', 'The change that can cause this in your edit'), chg('pencil', 'n', 'Change Capacity', 'Highest value goes from 5000 to 2000. An entry may have a higher value.', 'Possible cause'), S('color:var(--ui-text-muted);font-size:12px;line-height:18px;text-wrap:pretty', 'This kind of change is refused when an entry is over the new limit, a new required field has no default, a field becomes unique while entries share a value, or a removed choice is still in use.')])) if (k === 'refused') ov.push(Shell({ title: 'Nothing was changed', desc: 'RenewCMS refused the changes because some entries don\'t fit the new fields. It doesn\'t say which entries.', w: 560, top: 60, close: true, cancel: 'Discard changes', confirm: 'Back to editing' }, [Alert('error', 'circle-x', 'Your content type is as it was', 'No field was added, changed or removed.'), S('font-weight:600;color:var(--ui-text-highlighted)', 'The change that can cause this in your edit'), chg('pencil', 'n', 'Change Capacity', 'Highest value goes from 5000 to 2000. An entry may have a higher value.', 'Possible cause'), S('color:var(--ui-text-muted);font-size:12px;line-height:18px;text-wrap:pretty', 'This kind of change is refused when an entry is over the new limit, a new required field has no default, a field becomes unique while entries share a value, or a removed choice is still in use.')]))
if (k === 'blocked') ov.push(Shell({ title: 'You can\'t delete Events yet', desc: 'A content type can only be deleted when it has no entries.', close: true, cancel: 'Close', confirm: 'View entries' }, [Alert('warning', 'triangle-alert', 'Events has 37 entries', 'Delete all of its entries first, then delete the content type.')])) if (k === 'blocked') ov.push(Shell({ title: 'You can\'t delete Events yet', desc: 'A content type can only be deleted when it has no entries.', close: true, cancel: 'Close', confirm: 'View entries' }, [Alert('warning', 'triangle-alert', 'Events has 37 entries', 'Delete all of its entries first, then delete the content type.')]))
if (k === 'confirm') ov.push(Shell({ title: 'Delete Recipes?', desc: 'Recipes has no entries. Its fields and its API routes will be deleted. This can\'t be undone.', close: true, cancel: 'Cancel', confirm: 'Delete content type', tone: 'danger' }, [S('color:var(--ui-text-toned)', 'Key: ', S(mono + 'font-size:12px', 'recipes'))])) if (k === 'confirm') ov.push(Shell({ title: 'Delete Recipes?', desc: 'Recipes has no entries. Its fields and its API routes will be deleted. This can\'t be undone.', close: true, cancel: 'Cancel', confirm: 'Delete content type', tone: 'danger' }, [S('color:var(--ui-text-toned)', 'Key: ', S(mono + 'font-size:12px', 'recipes'))]))
if (k === 'mrefuse' || k === 'mclean') { const rf = k === 'mrefuse'; ov.push(Shell({ title: 'Review changes to Events', desc: 'Apply them to save the content type.', w: 560, top: 60, cancel: 'Back to editing', confirm: 'Apply changes', cdis: rf }, [D('display:flex;flex-direction:column;gap:2px', S('font-weight:600;font-size:15px;color:var(--ui-text-highlighted)', 'Add 1 field'), S('color:var(--ui-text-muted)', 'Events has 12 entries. Each one is checked against the new fields when you apply.')), chg('plus', 'n', 'Add Thumbnail', rf ? 'Media, required. A media field can\'t have a default, so the 12 existing entries would have no image. Make Thumbnail optional to add it.' : 'Media, optional. 12 entries are unaffected.', rf ? 'Can\'t be applied' : null), rf && S('color:var(--ui-text-muted);font-size:12px;line-height:18px', 'Back to editing keeps your other changes.')])) }
if (k === 'fallback') ov.push(Shell({ title: 'Delete Recipes?', desc: 'Recipes has no entries. Its fields and its API routes will be deleted. This can\'t be undone.', close: true, cancel: 'Close', confirm: 'View entries' }, [Alert('error', 'circle-x', 'Recipes now has entries', 'Someone added an entry after this page loaded, so nothing was deleted. Delete the entries first, then try again.')])) if (k === 'fallback') ov.push(Shell({ title: 'Delete Recipes?', desc: 'Recipes has no entries. Its fields and its API routes will be deleted. This can\'t be undone.', close: true, cancel: 'Close', confirm: 'View entries' }, [Alert('error', 'circle-x', 'Recipes now has entries', 'Someone added an entry after this page loaded, so nothing was deleted. Delete the entries first, then try again.')]))
} }
// 4 gallery // 4 gallery
const GF = { text: EV[0], richtext: { key: 'description', label: 'Description', type: 'richtext', max: 5000 }, number: EV[4], boolean: EV[3], date: { key: 'starts_on', label: 'Starts on', type: 'date', req: true, max: '31 Dec 2027' }, select: { ...EV[5], req: false } } const GF = { media: THUMB, text: EV[0], richtext: { key: 'description', label: 'Description', type: 'richtext', max: 5000 }, number: EV[4], boolean: EV[3], date: { key: 'starts_on', label: 'Starts on', type: 'date', req: true, max: '31 Dec 2027' }, select: { ...EV[5], req: false } }
if (v === 'gallery') { if (v === 'gallery') {
bare = true; if (m) { bw = '390px'; bhh = '844px' } bare = true; if (m) { bw = '390px'; bhh = '844px' }
const f = { ...GF[k], saved: false }, t = k, L = f.label const f = { ...GF[k], saved: false }, t = k, L = f.label
const ERR = { text: [['required', 422, 'Fill in ' + L + '.'], ['type', 422, L + ' must be text.'], ['min', 422, L + ' needs at least 3 characters.'], ['max', 422, L + ' can be up to 80 characters.'], ['options', '', 'Not used for text.'], ['unique', 409, 'Another entry already uses this ' + L + '. Enter a different one.']], richtext: [['required', 422, 'Fill in ' + L + '.'], ['type', 422, L + ' must be text.'], ['min', 422, L + ' needs at least 10 characters.'], ['max', 422, L + ' can be up to 5000 characters.'], ['options', '', 'Not used for rich text.'], ['unique', '', 'Not used for rich text.']], number: [['required', 422, 'Fill in ' + L + '.'], ['type', 422, L + ' must be a number.'], ['min', 422, L + ' must be at least 1.'], ['max', 422, L + ' must be at most 5000.'], ['options', '', 'Not used for numbers.'], ['unique', 409, 'Another entry already uses this ' + L + '.']], boolean: [['required', 422, 'Choose yes or no for ' + L + '.'], ['type', 422, L + ' must be yes or no.'], ['min', '', 'Not used for yes or no.'], ['max', '', 'Not used for yes or no.'], ['options', '', 'Not used for yes or no.'], ['unique', '', 'Not used for yes or no.']], date: [['required', 422, 'Pick a date for ' + L + '.'], ['type', 422, L + ' must be a date, like 2026-11-21.'], ['min', 422, L + ' can\'t be before 1 Jan 2026.'], ['max', 422, L + ' can\'t be after 31 Dec 2027.'], ['options', '', 'Not used for dates.'], ['unique', 409, 'Another entry already uses this date for ' + L + '.']], select: [['required', 422, 'Choose an option for ' + L + '.'], ['type', 422, L + ' must be one of the choices.'], ['min', '', 'Not used for choices.'], ['max', '', 'Not used for choices.'], ['options', 422, 'Choose one of: Talk, Workshop or Meetup.'], ['unique', 409, 'Another entry already uses this choice for ' + L + '.']] }[t] const ERR = { media: [['required', 422, 'Pick an image for ' + L + '.'], ['type', 422, L + ' must be an image from the library.'], ['min', '', 'Not used for media.'], ['max', '', 'Not used for media.'], ['options', '', 'Not used for media.'], ['unique', '', 'Not used for media.']], text: [['required', 422, 'Fill in ' + L + '.'], ['type', 422, L + ' must be text.'], ['min', 422, L + ' needs at least 3 characters.'], ['max', 422, L + ' can be up to 80 characters.'], ['options', '', 'Not used for text.'], ['unique', 409, 'Another entry already uses this ' + L + '. Enter a different one.']], richtext: [['required', 422, 'Fill in ' + L + '.'], ['type', 422, L + ' must be text.'], ['min', 422, L + ' needs at least 10 characters.'], ['max', 422, L + ' can be up to 5000 characters.'], ['options', '', 'Not used for rich text.'], ['unique', '', 'Not used for rich text.']], number: [['required', 422, 'Fill in ' + L + '.'], ['type', 422, L + ' must be a number.'], ['min', 422, L + ' must be at least 1.'], ['max', 422, L + ' must be at most 5000.'], ['options', '', 'Not used for numbers.'], ['unique', 409, 'Another entry already uses this ' + L + '.']], boolean: [['required', 422, 'Choose yes or no for ' + L + '.'], ['type', 422, L + ' must be yes or no.'], ['min', '', 'Not used for yes or no.'], ['max', '', 'Not used for yes or no.'], ['options', '', 'Not used for yes or no.'], ['unique', '', 'Not used for yes or no.']], date: [['required', 422, 'Pick a date for ' + L + '.'], ['type', 422, L + ' must be a date, like 2026-11-21.'], ['min', 422, L + ' can\'t be before 1 Jan 2026.'], ['max', 422, L + ' can\'t be after 31 Dec 2027.'], ['options', '', 'Not used for dates.'], ['unique', 409, 'Another entry already uses this date for ' + L + '.']], select: [['required', 422, 'Choose an option for ' + L + '.'], ['type', 422, L + ' must be one of the choices.'], ['min', '', 'Not used for choices.'], ['max', '', 'Not used for choices.'], ['options', 422, 'Choose one of: Talk, Workshop or Meetup.'], ['unique', 409, 'Another entry already uses this choice for ' + L + '.']] }[t]
const SAMPLE = { text: ['Lime plaster workshop', ''], richtext: [mdSample, ''], number: ['18', ''], boolean: ['true', 'false'], date: ['21 Nov 2026', ''], select: ['Workshop', ''] }[t] const SAMPLE = { media: ['', ''], text: ['Lime plaster workshop', ''], richtext: [mdSample, ''], number: ['18', ''], boolean: ['true', 'false'], date: ['21 Nov 2026', ''], select: ['Workshop', ''] }[t]
const sec = (title, ...c) => D('display:flex;flex-direction:column;gap:10px;min-width:0', S('font:600 15px/24px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', title), ...c) const sec = (title, ...c) => D('display:flex;flex-direction:column;gap:10px;min-width:0', S('font:600 15px/24px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', title), ...c)
const card = (...c) => D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:16px;display:flex;flex-direction:column;gap:14px', ...c) const card = (...c) => D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:16px;display:flex;flex-direction:column;gap:14px', ...c)
const specCtl = { text: Ctl(f, { v: 'Lime plaster workshop, two days of work with the whole team on site', count: '74 / 80', focus: true }), richtext: Ctl({ ...f, max: 5000 }, { v: mdSample, tab: 'write', count: '86 / 5000', help: 'Markdown. Switch to Preview to check the result.' }), number: Ctl(f, { v: '18', focus: true }), boolean: Ctl(f, { v: 'true' }), date: Ctl(f, { v: '21 Nov 2026', focus: true, extra: D('position:absolute;left:0;top:68px;z-index:3', Cal()) }), select: Ctl(f, { v: 'Workshop', focus: true, extra: D('position:absolute;left:0;top:66px;right:0;z-index:3;border:1px solid var(--ui-border);background:var(--ui-bg);box-shadow:var(--rc-shadow-pop);padding:4px', ...['Talk', 'Workshop', 'Meetup'].map(o_ => D('height:' + (m ? 44 : 32) + 'px;padding:0 8px;display:flex;align-items:center;justify-content:space-between;background:' + (o_ === 'Workshop' ? 'var(--ui-bg-elevated)' : 'transparent'), o_, o_ === 'Workshop' && I('check', 14)))) }) }[t] const specCtl = { media: Ctl(f, { st: 'filled', hover: true }), text: Ctl(f, { v: 'Lime plaster workshop, two days of work with the whole team on site', count: '74 / 80', focus: true }), richtext: Ctl({ ...f, max: 5000 }, { v: mdSample, tab: 'write', count: '86 / 5000', help: 'Markdown. Switch to Preview to check the result.' }), number: Ctl(f, { v: '18', focus: true }), boolean: Ctl(f, { v: 'true' }), date: Ctl(f, { v: '21 Nov 2026', focus: true, extra: D('position:absolute;left:0;top:68px;z-index:3', Cal()) }), select: Ctl(f, { v: 'Workshop', focus: true, extra: D('position:absolute;left:0;top:66px;right:0;z-index:3;border:1px solid var(--ui-border);background:var(--ui-bg);box-shadow:var(--rc-shadow-pop);padding:4px', ...['Talk', 'Workshop', 'Meetup'].map(o_ => D('height:' + (m ? 44 : 32) + 'px;padding:0 8px;display:flex;align-items:center;justify-content:space-between;background:' + (o_ === 'Workshop' ? 'var(--ui-bg-elevated)' : 'transparent'), o_, o_ === 'Workshop' && I('check', 14)))) }) }[t]
const spacer = { date: 'height:236px', select: 'height:120px', richtext: '', text: '', number: '', boolean: '' }[t] const spacer = { date: 'height:236px', select: 'height:120px', richtext: '', text: '', number: '', boolean: '' }[t]
const stateLbl = { text: 'Typing, close to the limit', richtext: 'Write tab, with counter', number: 'Focused', boolean: 'On', date: 'Date picker open', select: 'Choices open' }[t] const stateLbl = { media: 'Filled, pointer over the thumbnail', text: 'Typing, close to the limit', richtext: 'Write tab, with counter', number: 'Focused', boolean: 'On', date: 'Date picker open', select: 'Choices open' }[t]
const ctlCol = sec('Entry form control', card(S('font-size:12px;color:var(--ui-text-muted)', stateLbl), D('', specCtl, spacer && D(spacer)), D('border-top:1px solid var(--ui-border)'), S('font-size:12px;color:var(--ui-text-muted)', t === 'richtext' ? 'Preview tab' : t === 'boolean' ? 'Off, and not set' : 'Empty'), t === 'richtext' ? Ctl(f, { v: mdSample, tab: 'preview', help: '' }) : t === 'boolean' ? Ctl(f, { v: 'false' }) : Ctl(f, { v: '' }))) const ctlCol = sec('Entry form control', card(S('font-size:12px;color:var(--ui-text-muted)', stateLbl), D('', specCtl, spacer && D(spacer)), D('border-top:1px solid var(--ui-border)'), S('font-size:12px;color:var(--ui-text-muted)', t === 'richtext' ? 'Preview tab' : t === 'boolean' ? 'Off, and not set' : 'Empty'), t === 'richtext' ? Ctl(f, { v: mdSample, tab: 'preview', help: '' }) : t === 'boolean' ? Ctl(f, { v: 'false' }) : Ctl(f, { v: '' })))
const cell = (val, lab) => D('display:grid;grid-template-columns:' + (m ? '90px' : '110px') + ' minmax(0,1fr);gap:12px;align-items:center;min-height:40px;padding:0 12px;border-top:1px solid var(--ui-border)', S('font-size:12px;color:var(--ui-text-muted)', lab), Cell(f, val)) const cell = (val, lab) => D('display:grid;grid-template-columns:' + (m ? '90px' : '110px') + ' minmax(0,1fr);gap:12px;align-items:center;min-height:40px;padding:0 12px;border-top:1px solid var(--ui-border)', S('font-size:12px;color:var(--ui-text-muted)', lab), Cell(f, val))
const cellVals = { text: ['Lime plaster workshop', ''], richtext: ['Two days of hands-on work with lime putty and old stone.', ''], number: [18, null], boolean: [true, null], date: ['21 Nov 2026', ''], select: ['Workshop', ''] }[t] const cellVals = { media: ['ok', ''], text: ['Lime plaster workshop', ''], richtext: ['Two days of hands-on work with lime putty and old stone.', ''], number: [18, null], boolean: [true, null], date: ['21 Nov 2026', ''], select: ['Workshop', ''] }[t]
const listCol = sec('List cell', D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('display:grid;grid-template-columns:' + (m ? '90px' : '110px') + ' minmax(0,1fr);gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', S('', 'Value'), S('', L)), D('', cell(cellVals[0], 'Filled'), cell(cellVals[1], 'Empty'))), S('font-size:12px;color:var(--ui-text-muted)', { text: 'Truncated on one line, full text on hover.', richtext: 'First line as plain text, truncated.', number: 'Right-aligned, tabular figures.', boolean: 'Yes or No with an icon. Empty only when the field has no value.', date: 'Day, month and year.', select: 'The chosen option as a small tag.' }[t])) const listCol = sec('List cell', D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('display:grid;grid-template-columns:' + (m ? '90px' : '110px') + ' minmax(0,1fr);gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', S('', 'Value'), S('', L)), D('', cell(cellVals[0], 'Filled'), cell(cellVals[1], 'Empty'), t === 'media' && cell('miss', 'Image missing'))), S('font-size:12px;color:var(--ui-text-muted)', { text: 'Truncated on one line, full text on hover.', richtext: 'First line as plain text, truncated.', number: 'Right-aligned, tabular figures.', boolean: 'Yes or No with an icon. Empty only when the field has no value.', date: 'Day, month and year.', select: 'The chosen option as a small tag.', media: 'A 40 px square thumbnail, 32 px in cards. Not sortable. A dash when empty.' }[t]))
const errCol = sec('Errors by rule', D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('display:grid;grid-template-columns:' + (m ? '64px 38px' : '72px 40px') + ' minmax(0,1fr);gap:10px;height:32px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', S('', 'Rule'), S('', 'HTTP'), S('', 'Message')), ...ERR.map(r => D('display:grid;grid-template-columns:' + (m ? '64px 38px' : '72px 40px') + ' minmax(0,1fr);gap:10px;padding:8px 12px;border-top:1px solid var(--ui-border);align-items:start;line-height:18px', S(mono + 'font-size:12px;color:var(--ui-text-highlighted)', r[0]), S(mono + 'font-size:12px;color:var(--ui-text-muted)', String(r[1] || '–')), S('color:' + (r[1] ? 'var(--ui-error)' : 'var(--ui-text-muted)') + ';text-wrap:pretty', r[2]))))) const errCol = sec('Errors by rule', D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('display:grid;grid-template-columns:' + (m ? '64px 38px' : '72px 40px') + ' minmax(0,1fr);gap:10px;height:32px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', S('', 'Rule'), S('', 'HTTP'), S('', 'Message')), ...ERR.map(r => D('display:grid;grid-template-columns:' + (m ? '64px 38px' : '72px 40px') + ' minmax(0,1fr);gap:10px;padding:8px 12px;border-top:1px solid var(--ui-border);align-items:start;line-height:18px', S(mono + 'font-size:12px;color:var(--ui-text-highlighted)', r[0]), S(mono + 'font-size:12px;color:var(--ui-text-muted)', String(r[1] || '–')), S('color:' + (r[1] ? 'var(--ui-error)' : 'var(--ui-text-muted)') + ';text-wrap:pretty', r[2])))))
const FW = { text: [['contains', 'Any text'], 'text'], richtext: [['contains', 'Any text'], 'text'], number: [['between'], 'num'], boolean: [['is'], 'bool'], date: [['between'], 'date'], select: [['is one of'], 'sel'] }[t] const FW = { media: [['has an image'], 'media'], text: [['contains', 'Any text'], 'text'], richtext: [['contains', 'Any text'], 'text'], number: [['between'], 'num'], boolean: [['is'], 'bool'], date: [['between'], 'date'], select: [['is one of'], 'sel'] }[t]
const fw = FW[1] === 'bool' ? Seg([['any', 'Any'], ['yes', 'Yes'], ['no', 'No']], 'any') : FW[1] === 'sel' ? D('display:flex;gap:6px;flex-wrap:wrap', ...['Talk', 'Workshop', 'Meetup'].map((o_, i) => S('height:28px;padding:0 10px;display:flex;align-items:center;gap:6px;border:1px solid ' + (i === 1 ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (i === 1 ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (i === 1 ? 'var(--rc-on-sand)' : 'var(--ui-text-toned)'), i === 1 && I('check', 12), o_))) : FW[1] === 'num' || FW[1] === 'date' ? D('display:flex;gap:8px;align-items:center', F('', '', { ph: true, phText: FW[1] === 'date' ? 'From' : 'Min', ico: FW[1] === 'date' ? 'calendar' : null }), S('color:var(--ui-text-muted)', 'to'), F('', '', { ph: true, phText: FW[1] === 'date' ? 'Until' : 'Max', ico: FW[1] === 'date' ? 'calendar' : null })) : F('', '', { ph: true, phText: 'Contains…', ico: 'search' }) const fw = FW[1] === 'media' ? Seg([['any', 'Any'], ['yes', 'Has an image'], ['no', 'No image']], 'any') : FW[1] === 'bool' ? Seg([['any', 'Any'], ['yes', 'Yes'], ['no', 'No']], 'any') : FW[1] === 'sel' ? D('display:flex;gap:6px;flex-wrap:wrap', ...['Talk', 'Workshop', 'Meetup'].map((o_, i) => S('height:28px;padding:0 10px;display:flex;align-items:center;gap:6px;border:1px solid ' + (i === 1 ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (i === 1 ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (i === 1 ? 'var(--rc-on-sand)' : 'var(--ui-text-toned)'), i === 1 && I('check', 12), o_))) : FW[1] === 'num' || FW[1] === 'date' ? D('display:flex;gap:8px;align-items:center', F('', '', { ph: true, phText: FW[1] === 'date' ? 'From' : 'Min', ico: FW[1] === 'date' ? 'calendar' : null }), S('color:var(--ui-text-muted)', 'to'), F('', '', { ph: true, phText: FW[1] === 'date' ? 'Until' : 'Max', ico: FW[1] === 'date' ? 'calendar' : null })) : F('', '', { ph: true, phText: 'Contains…', ico: 'search' })
const filtCol = sec('Filter in the entry list', D('border:1px dashed var(--ui-border-accented);padding:14px;display:flex;flex-direction:column;gap:10px', D('display:flex;align-items:center;gap:8px', S('font-weight:500;color:var(--ui-text-highlighted)', L + ': ' + FW[0][0]), Later('Later')), fw, S('font-size:12px;color:var(--ui-text-muted);line-height:18px', 'Filtering on custom fields isn\'t available yet. The list only sorts by ID, created and updated.'))) const filtCol = sec('Filter in the entry list', D('border:1px dashed var(--ui-border-accented);padding:14px;display:flex;flex-direction:column;gap:10px', D('display:flex;align-items:center;gap:8px', S('font-weight:500;color:var(--ui-text-highlighted)', L + ': ' + FW[0][0]), Later('Later')), fw, S('font-size:12px;color:var(--ui-text-muted);line-height:18px', 'Filtering on custom fields isn\'t available yet. The list only sorts by ID, created and updated.')))
const head = D('display:flex;align-items:center;gap:14px;flex-shrink:0', S('width:44px;height:44px;display:flex;align-items:center;justify-content:center;background:var(--rc-sand);color:var(--rc-on-sand)', I(FT[t][0], 22)), D('flex:1;display:flex;flex-direction:column', S('font:600 ' + (m ? 20 : 24) + 'px/32px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', FT[t][1]), S('color:var(--ui-text-muted)', FT[t][2])), !m && S(mono + 'font-size:12px;color:var(--ui-text-toned)', 'type: "' + t + '"')) const head = D('display:flex;align-items:center;gap:14px;flex-shrink:0', S('width:44px;height:44px;display:flex;align-items:center;justify-content:center;background:var(--rc-sand);color:var(--rc-on-sand)', I(FT[t][0], 22)), D('flex:1;display:flex;flex-direction:column', S('font:600 ' + (m ? 20 : 24) + 'px/32px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', FT[t][1]), S('color:var(--ui-text-muted)', FT[t][2])), !m && S(mono + 'font-size:12px;color:var(--ui-text-toned)', 'type: "' + t + '"'))
const inspCol = !m && sec('Inspector options', card(Insp(f, { one: true }))) const inspCol = !m && sec('Inspector options', card(Insp(f, { one: true })))
@@ -287,7 +312,7 @@ class Component extends DCLogic {
} }
// 5 entries // 5 entries
const visCols = k === 'cols' ? [EV[0], EV[1], EV[2], EV[3]] : [EV[0], EV[1], EV[2], EV[3]] const visCols = ['thumb', 'thumbcols', 'thumbtip'].includes(k) ? [EV[0], THUMB, EV[1], EV[5]] : [EV[0], EV[1], EV[2], EV[3]]
if (v === 'entries') { if (v === 'entries') {
shell.nav = 'content'; shell.crumbs = ['Content', 'Events']; shell.mTitle = 'Events'; shell.contentOn = k === 'notfound' ? null : 'events' shell.nav = 'content'; shell.crumbs = ['Content', 'Events']; shell.mTitle = 'Events'; shell.contentOn = k === 'notfound' ? null : 'events'
if (s.many && m) { shell.drawer = true; shell.contentOpen = true } if (s.many && m) { shell.drawer = true; shell.contentOpen = true }
@@ -305,19 +330,20 @@ class Component extends DCLogic {
else if (k === 'empty') body = Empty('file-plus', 'No entries yet', 'Use New entry to add the first event. Each entry follows the fields of this content type.', 'New entry') else if (k === 'empty') body = Empty('file-plus', 'No entries yet', 'Use New entry to add the first event. Each entry follows the fields of this content type.', 'New entry')
else { else {
const rows = ROWS.slice(0, size > 7 ? 7 : 5) const rows = ROWS.slice(0, size > 7 ? 7 : 5)
const gc = '48px ' + visCols.map((f, i) => i === 0 ? 'minmax(0,1.6fr)' : f.type === 'boolean' || f.type === 'number' ? '80px' : '120px').join(' ') + ' 110px 150px 130px' const gc = '48px ' + visCols.map((f, i) => i === 0 ? 'minmax(0,1.6fr)' : f.type === 'boolean' || f.type === 'number' || f.type === 'media' ? '80px' : '120px').join(' ') + ' 110px 150px 130px'
const hdrC = (t, o = {}) => S('display:flex;align-items:center;gap:4px;' + (o.r ? 'justify-content:flex-end;' : ''), t, o.sort && I('arrow-down', 12)) const hdrC = (t, o = {}) => S('display:flex;align-items:center;gap:4px;' + (o.r ? 'justify-content:flex-end;' : ''), t, o.sort && I('arrow-down', 12))
const tbl = D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('display:grid;grid-template-columns:' + gc + ';gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', hdrC('ID'), ...visCols.map(f => hdrC(f.label, { r: f.type === 'number' })), hdrC('Created'), hdrC('Updated', { sort: true }), hdrC('Updated by')), const tbl = D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('display:grid;grid-template-columns:' + gc + ';gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', hdrC('ID'), ...visCols.map(f => hdrC(f.label, { r: f.type === 'number' })), hdrC('Created'), hdrC('Updated', { sort: true }), hdrC('Updated by')),
...rows.map((r, i) => D('display:grid;grid-template-columns:' + gc + ';gap:12px;height:48px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border);background:' + (i === 0 && false ? 'var(--ui-bg-elevated)' : 'transparent'), S(mono + 'font-size:12px;color:var(--ui-text-muted)', String(r.id)), ...visCols.map((f, j) => D('min-width:0;' + (j === 0 ? 'font-weight:500;color:var(--ui-text-highlighted);display:flex' : 'display:grid'), Cell(f, r[f.key]))), S('color:var(--ui-text-muted);white-space:nowrap', r.c), S('color:var(--ui-text-muted);white-space:nowrap', r.u.split(',')[0]), S('overflow:hidden;text-overflow:ellipsis;white-space:nowrap', r.by)))) ...rows.map((r, i) => D('display:grid;grid-template-columns:' + gc + ';gap:12px;height:48px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border);background:' + (i === 0 && false ? 'var(--ui-bg-elevated)' : 'transparent'), S(mono + 'font-size:12px;color:var(--ui-text-muted)', String(r.id)), ...visCols.map((f, j) => D('min-width:0;' + (j === 0 ? 'font-weight:500;color:var(--ui-text-highlighted);display:flex' : 'display:grid'), Cell(f, r[f.key]))), S('color:var(--ui-text-muted);white-space:nowrap', r.c), S('color:var(--ui-text-muted);white-space:nowrap', r.u.split(',')[0]), S('overflow:hidden;text-overflow:ellipsis;white-space:nowrap', r.by))))
const cards = D('background:var(--ui-bg);border:1px solid var(--ui-border)', ...ROWS.slice(0, 6).map((r, i) => D('display:flex;align-items:center;gap:8px;padding:12px 4px 12px 16px;border-top:' + (i ? '1px solid var(--ui-border)' : 'none') + ';min-height:68px', D('flex:1;min-width:0;display:flex;flex-direction:column;gap:4px', S('font-weight:500;font-size:15px;line-height:21px;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', r.title), D('display:flex;align-items:center;gap:8px;font-size:12px;color:var(--ui-text-muted)', S('', r.starts_on), r.category && Cell(EV[5], r.category), S('overflow:hidden;text-overflow:ellipsis;white-space:nowrap', '· ' + r.by))), S('width:36px;height:44px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('chevron-right', 18))))) const cards = D('background:var(--ui-bg);border:1px solid var(--ui-border)', ...ROWS.slice(0, 6).map((r, i) => D('display:flex;align-items:center;gap:8px;padding:12px 4px 12px 16px;border-top:' + (i ? '1px solid var(--ui-border)' : 'none') + ';min-height:68px', visCols.some(f => f.type === 'media') && cellM(r.thumbnail, 32), D('flex:1;min-width:0;display:flex;flex-direction:column;gap:4px', S('font-weight:500;font-size:15px;line-height:21px;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', r.title), D('display:flex;align-items:center;gap:8px;font-size:12px;color:var(--ui-text-muted)', S('', r.starts_on), r.category && Cell(EV[5], r.category), S('overflow:hidden;text-overflow:ellipsis;white-space:nowrap', '· ' + r.by))), S('width:36px;height:44px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('chevron-right', 18)))))
const pgB = (c, on, dis) => S('width:' + bh + 'px;height:' + bh + 'px;display:flex;align-items:center;justify-content:center;border:1px solid ' + (on ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (on ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-highlighted)') + ';opacity:' + (dis ? 0.4 : 1) + ';font-weight:' + (on ? 500 : 400), typeof c === 'string' && c.length > 2 ? I(c, 14) : c) const pgB = (c, on, dis) => S('width:' + bh + 'px;height:' + bh + 'px;display:flex;align-items:center;justify-content:center;border:1px solid ' + (on ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (on ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-highlighted)') + ';opacity:' + (dis ? 0.4 : 1) + ';font-weight:' + (on ? 500 : 400), typeof c === 'string' && c.length > 2 ? I(c, 14) : c)
const pager = !paged ? S('color:var(--ui-text-muted)', '7 entries') : m ? D('display:flex;align-items:center;justify-content:space-between;gap:8px', pgB('chevron-left', false, true), S('color:var(--ui-text-muted)', 'Page 1 of 8'), pgB('chevron-right')) : D('display:flex;align-items:center;gap:16px', S('flex:1;color:var(--ui-text-muted)', 'Showing 1–5 of 37'), D('display:flex;align-items:center;gap:8px;height:32px;padding:0 10px;border:1px solid var(--ui-border-accented);background:var(--ui-bg)', '5 per page', I('chevron-down', 14, 'color:var(--ui-text-muted)')), D('display:flex;gap:4px', pgB('chevrons-left', false, true), pgB('chevron-left', false, true), pgB('1', true), pgB('2'), pgB('3'), pgB('…'), pgB('8'), pgB('chevron-right'), pgB('chevrons-right'))) const pager = !paged ? S('color:var(--ui-text-muted)', '7 entries') : m ? D('display:flex;align-items:center;justify-content:space-between;gap:8px', pgB('chevron-left', false, true), S('color:var(--ui-text-muted)', 'Page 1 of 8'), pgB('chevron-right')) : D('display:flex;align-items:center;gap:16px', S('flex:1;color:var(--ui-text-muted)', 'Showing 1–5 of 37'), D('display:flex;align-items:center;gap:8px;height:32px;padding:0 10px;border:1px solid var(--ui-border-accented);background:var(--ui-bg)', '5 per page', I('chevron-down', 14, 'color:var(--ui-text-muted)')), D('display:flex;gap:4px', pgB('chevrons-left', false, true), pgB('chevron-left', false, true), pgB('1', true), pgB('2'), pgB('3'), pgB('…'), pgB('8'), pgB('chevron-right'), pgB('chevrons-right')))
body = D('display:flex;flex-direction:column;gap:12px;min-height:0', m ? cards : tbl, pager) body = D('display:flex;flex-direction:column;gap:12px;min-height:0', m ? cards : tbl, pager)
} }
main = Page(pad, Title('Events', 'events · 7 fields', !m && B('New entry', { k: 'primary', icon: 'plus', px: 14, dis: k === 'loading' })), ...(k === 'error' || k === 'empty' || k === 'loading' ? [k !== 'error' ? toolbar : null, body] : [toolbar, body])) main = Page(pad, Title('Events', 'events · 7 fields', !m && B('New entry', { k: 'primary', icon: 'plus', px: 14, dis: k === 'loading' })), ...(k === 'error' || k === 'empty' || k === 'loading' ? [k !== 'error' ? toolbar : null, body] : [toolbar, body]))
if (m && k !== 'error' && k !== 'loading') ov.push(Fab('New entry')) if (m && k !== 'error' && k !== 'loading') ov.push(Fab('New entry'))
if (k === 'cols') { if (k === 'thumbtip' && !m) ov.push(D('position:absolute;z-index:30;left:609px;top:416px;padding:6px 8px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font-size:12px;line-height:18px;box-shadow:var(--rc-shadow-pop);white-space:nowrap', 'Image no longer in the library'))
const items = EV.map((f, i) => [f, i < 4]) if (k === 'cols' || k === 'thumbcols') {
const items = k === 'thumbcols' ? [...EV, THUMB].map(f => [f, ['title', 'thumbnail', 'starts_on', 'category'].includes(f.key)]) : EV.map((f, i) => [f, i < 4])
const lst = D('display:flex;flex-direction:column', ...items.map(([f, on]) => D('display:flex;align-items:center;gap:10px;min-height:' + (m ? 48 : 36) + 'px;padding:0 8px', Chk(on), I(FT[f.type][0], 14, 'color:var(--ui-text-muted)'), S('flex:1', f.label), S(mono + 'font-size:12px;color:var(--ui-text-muted)', f.key))), D('display:flex;align-items:center;gap:10px;min-height:' + (m ? 48 : 36) + 'px;padding:0 8px;color:var(--ui-text-muted)', Chk(false), I('clock', 14), S('', 'Created and updated dates always show'))) const lst = D('display:flex;flex-direction:column', ...items.map(([f, on]) => D('display:flex;align-items:center;gap:10px;min-height:' + (m ? 48 : 36) + 'px;padding:0 8px', Chk(on), I(FT[f.type][0], 14, 'color:var(--ui-text-muted)'), S('flex:1', f.label), S(mono + 'font-size:12px;color:var(--ui-text-muted)', f.key))), D('display:flex;align-items:center;gap:10px;min-height:' + (m ? 48 : 36) + 'px;padding:0 8px;color:var(--ui-text-muted)', Chk(false), I('clock', 14), S('', 'Created and updated dates always show')))
if (m) ov.push(Sheet({ title: 'Columns', z: 45 }, [S('color:var(--ui-text-muted)', 'Choose up to 6 fields to show. 4 selected.'), lst], [B('Reset', { full: true }), B('Done', { k: 'primary', full: true })])) if (m) ov.push(Sheet({ title: 'Columns', z: 45 }, [S('color:var(--ui-text-muted)', 'Choose up to 6 fields to show. 4 selected.'), lst], [B('Reset', { full: true }), B('Done', { k: 'primary', full: true })]))
else ov.push(D('position:absolute;z-index:40;left:' + (224 + 24 + 330) + 'px;top:' + (48 + 24 + 28 + 18 + 16 + 40) + 'px;width:300px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:8px;display:flex;flex-direction:column;gap:8px', D('display:flex;justify-content:space-between;padding:4px 8px', S('font-weight:600', 'Columns'), S('color:var(--ui-text-muted);font-size:12px', '4 of 6')), lst, D('display:flex;justify-content:flex-end;padding:4px 8px', B('Reset', { h: 28, fs: 12 })))) else ov.push(D('position:absolute;z-index:40;left:' + (224 + 24 + 330) + 'px;top:' + (48 + 24 + 28 + 18 + 16 + 40) + 'px;width:300px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:8px;display:flex;flex-direction:column;gap:8px', D('display:flex;justify-content:space-between;padding:4px 8px', S('font-weight:600', 'Columns'), S('color:var(--ui-text-muted);font-size:12px', '4 of 6')), lst, D('display:flex;justify-content:flex-end;padding:4px 8px', B('Reset', { h: 28, fs: 12 }))))
@@ -327,6 +353,7 @@ class Component extends DCLogic {
// 6 entry // 6 entry
if (v === 'entry') { if (v === 'entry') {
const mk = s.m || null, mErr = mk === 'err' || mk === 'missingreq'
shell.nav = 'content'; shell.contentOn = 'events'; shell.crumbs = ['Content', 'Events', k === 'new' || k === 'required' ? 'New entry' : 'Lime plaster workshop']; shell.mTitle = k === 'new' || k === 'required' ? 'New entry' : 'Lime plaster workshop'; shell.mLead = 'arrow-left'; shell.mAction = k === 'new' || k === 'required' ? null : 'trash-2' shell.nav = 'content'; shell.contentOn = 'events'; shell.crumbs = ['Content', 'Events', k === 'new' || k === 'required' ? 'New entry' : 'Lime plaster workshop']; shell.mTitle = k === 'new' || k === 'required' ? 'New entry' : 'Lime plaster workshop'; shell.mLead = 'arrow-left'; shell.mAction = k === 'new' || k === 'required' ? null : 'trash-2'
if (k === 'notfound') main = Center('file-x', 'Entry not found', 'It may have been deleted by someone else.', B('Back to Events', { k: 'primary', px: 16 })) if (k === 'notfound') main = Center('file-x', 'Entry not found', 'It may have been deleted by someone else.', B('Back to Events', { k: 'primary', px: 16 }))
else { else {
@@ -338,16 +365,18 @@ class Component extends DCLogic {
if (k === 'rules') { val.title = 'Lime plaster workshop, two days of hands-on work with the whole team on site and lunch'; E.title = 'Title can be up to 80 characters.'; val.ends_on = '31/11/2026'; E.ends_on = 'Ends on must be a date, like 2026-11-21.'; val.capacity = '6000'; E.capacity = 'Capacity must be at most 5000.'; val.category = 'Seminar'; E.category = 'Choose one of: Talk, Workshop or Meetup.' } if (k === 'rules') { val.title = 'Lime plaster workshop, two days of hands-on work with the whole team on site and lunch'; E.title = 'Title can be up to 80 characters.'; val.ends_on = '31/11/2026'; E.ends_on = 'Ends on must be a date, like 2026-11-21.'; val.capacity = '6000'; E.capacity = 'Capacity must be at most 5000.'; val.category = 'Seminar'; E.category = 'Choose one of: Talk, Workshop or Meetup.' }
if (k === 'unique') { val.title = 'Heat pumps: what the numbers say'; E.title = 'Another entry already uses this Title. Enter a different one.' } if (k === 'unique') { val.title = 'Heat pumps: what the numbers say'; E.title = 'Another entry already uses this Title. Enter a different one.' }
const dis = k === 'saving' || k === 'changed' const dis = k === 'saving' || k === 'changed'
const sk = k === 'dirty' ? 'dirty' : k === 'saving' ? 'saving' : k === 'saved' ? 'saved' : k === 'fail' ? 'fail' : (k === 'required' || k === 'rules' || k === 'unique') ? 'fail' : 'clean' const sk = k === 'dirty' ? 'dirty' : k === 'saving' ? 'saving' : k === 'saved' ? 'saved' : k === 'fail' ? 'fail' : (k === 'required' || k === 'rules' || k === 'unique' || mErr) ? 'fail' : 'clean'
const chip = k === 'required' || k === 'rules' || k === 'unique' ? S('display:flex;align-items:center;gap:6px;font-size:12px;color:var(--ui-error);white-space:nowrap', I('circle-alert', 14), 'Not saved') : isNew ? S('font-size:12px;color:var(--ui-text-muted);white-space:nowrap', 'New entry') : stChip(sk) const chip = k === 'required' || k === 'rules' || k === 'unique' || mErr ? S('display:flex;align-items:center;gap:6px;font-size:12px;color:var(--ui-error);white-space:nowrap', I('circle-alert', 14), 'Not saved') : isNew ? S('font-size:12px;color:var(--ui-text-muted);white-space:nowrap', 'New entry') : stChip(sk)
const canSave = k === 'dirty' || k === 'fail' || k === 'new' || k === 'required' || k === 'rules' || k === 'unique' const canSave = k === 'dirty' || k === 'fail' || k === 'new' || k === 'required' || k === 'rules' || k === 'unique' || mErr
const acts = D('display:flex;align-items:center;gap:' + (m ? 8 : 12) + 'px', !m && chip, !m && !isNew && B('Delete', { k: 'del', icon: 'trash-2' }), !m && B('Cancel', { dis: dis }), !m && B(k === 'saving' ? 'Saving…' : 'Save', { k: 'primary', icon: k === 'saving' ? 'loader-circle' : null, px: 16, dis: !canSave && k !== 'saving' })) const acts = D('display:flex;align-items:center;gap:' + (m ? 8 : 12) + 'px', !m && chip, !m && !isNew && B('Delete', { k: 'del', icon: 'trash-2' }), !m && B('Cancel', { dis: dis }), !m && B(k === 'saving' ? 'Saving…' : 'Save', { k: 'primary', icon: k === 'saving' ? 'loader-circle' : null, px: 16, dis: !canSave && k !== 'saving' }))
const fieldsUI = EV.map(f => { const vv = val[f.key], e = E[f.key]; const o = { v: vv, err: e, dis, def: isNew && f.key === 'online', focus: k === 'dirty' && f.key === 'title' }; if (f.key === 'title') { const n = (vv || '').length; o.count = n + ' / 80'; o.countErr = n > 80; if (k === 'unique') o.count = n + ' / 80' } if (f.key === 'description') { o.tab = k === 'preview' ? 'preview' : 'write'; o.help = 'Markdown. Switch to Preview to check the result.' } if (f.key === 'capacity') o.help = 'Between 1 and 5000.'; if (f.key === 'title' && !e) o.help = 'Each entry needs a different title.'; return Ctl(f, o) }) const fieldsUI = EV.map(f => { const vv = val[f.key], e = E[f.key]; const o = { v: vv, err: e, dis, def: isNew && f.key === 'online', focus: k === 'dirty' && f.key === 'title' }; if (f.key === 'title') { const n = (vv || '').length; o.count = n + ' / 80'; o.countErr = n > 80; if (k === 'unique') o.count = n + ' / 80' } if (f.key === 'description') { o.tab = k === 'preview' ? 'preview' : 'write'; o.help = 'Markdown. Switch to Preview to check the result.' } if (f.key === 'capacity') o.help = 'Between 1 and 5000.'; if (f.key === 'title' && !e) o.help = 'Each entry needs a different title.'; return Ctl(f, o) })
const mo = { hover: { st: 'filled', hover: true }, focus: { st: 'filled', focus: true }, filled: { st: 'filled' }, err: { st: 'empty', err: 'Pick an image for Thumbnail.', ringBtn: 'pick' }, missing: { st: 'missing' }, missingreq: { st: 'missing', err: 'Pick an image for Thumbnail.', ringBtn: 'choose' } }[mk] || { st: 'empty' }
const mUI = mk && Ctl({ ...THUMB, req: ['emptyreq', 'err', 'missingreq'].includes(mk) }, { ...mo, dis })
const grid = (a, b) => D('display:grid;grid-template-columns:' + (m ? '1fr' : '1fr 1fr') + ';gap:16px', a, b) const grid = (a, b) => D('display:grid;grid-template-columns:' + (m ? '1fr' : '1fr 1fr') + ';gap:16px', a, b)
const form = D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:' + (m ? 16 : 24) + 'px;display:flex;flex-direction:column;gap:20px;max-width:760px;opacity:' + (dis ? 0.7 : 1), fieldsUI[0], grid(fieldsUI[1], fieldsUI[2]), grid(fieldsUI[3], fieldsUI[4]), fieldsUI[5], fieldsUI[6], D('border-top:1px solid var(--ui-border);padding-top:16px;display:grid;grid-template-columns:' + (m ? '1fr' : 'auto 1fr') + ';gap:6px 16px;font-size:12px;line-height:18px', S('color:var(--ui-text-muted)', 'Entry'), S('', isNew ? 'Not saved yet' : S(mono, 'events / 42')), S('color:var(--ui-text-muted)', 'Created by'), S('', isNew ? '–' : 'Inès Duarte · 12 Oct 2026, 09:14'), S('color:var(--ui-text-muted)', 'Updated by'), S('', isNew ? '–' : k === 'saved' ? 'Marta Alves · 19 Oct 2026, 11:02' : 'Marta Alves · 15 Oct 2026, 11:02'))) const form = D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:' + (m ? 16 : 24) + 'px;display:flex;flex-direction:column;gap:20px;max-width:760px;opacity:' + (dis ? 0.7 : 1), fieldsUI[0], grid(fieldsUI[1], fieldsUI[2]), grid(fieldsUI[3], fieldsUI[4]), fieldsUI[5], fieldsUI[6], mUI, D('border-top:1px solid var(--ui-border);padding-top:16px;display:grid;grid-template-columns:' + (m ? '1fr' : 'auto 1fr') + ';gap:6px 16px;font-size:12px;line-height:18px', S('color:var(--ui-text-muted)', 'Entry'), S('', isNew ? 'Not saved yet' : S(mono, 'events / 42')), S('color:var(--ui-text-muted)', 'Created by'), S('', isNew ? '–' : 'Inès Duarte · 12 Oct 2026, 09:14'), S('color:var(--ui-text-muted)', 'Updated by'), S('', isNew ? '–' : k === 'saved' ? 'Marta Alves · 19 Oct 2026, 11:02' : 'Marta Alves · 15 Oct 2026, 11:02')))
const ban = k === 'fail' ? Alert('error', 'circle-x', 'Couldn\'t save the entry', 'Something went wrong on our side. Your changes are still here. Try again in a moment.', 'Try again') : k === 'changed' ? Alert('warning', 'triangle-alert', 'The fields of Events changed', 'A field was removed and a new required field, Room, was added after you opened this form. Reload the form to continue. What you typed here can\'t be saved against the old fields.', 'Reload form') : k === 'unique' ? Alert('error', 'circle-x', 'Not saved', 'Another entry already uses this title. Change it and save again.') : null const ban = k === 'fail' ? Alert('error', 'circle-x', 'Couldn\'t save the entry', 'Something went wrong on our side. Your changes are still here. Try again in a moment.', 'Try again') : k === 'changed' && mk ? Alert('warning', 'triangle-alert', 'The fields of Events changed', 'The Thumbnail field was changed after you opened this form. Reload the form to continue. What you typed here can\'t be saved against the old fields.', 'Reload form') : k === 'changed' ? Alert('warning', 'triangle-alert', 'The fields of Events changed', 'A field was removed and a new required field, Room, was added after you opened this form. Reload the form to continue. What you typed here can\'t be saved against the old fields.', 'Reload form') : k === 'unique' ? Alert('error', 'circle-x', 'Not saved', 'Another entry already uses this title. Change it and save again.') : null
const bar = m && D('flex-shrink:0;display:flex;align-items:center;gap:8px;padding:12px 16px;border-top:1px solid var(--ui-border);background:var(--ui-bg);position:relative;z-index:1', B('Cancel', { full: true, dis }), B(k === 'saving' ? 'Saving…' : 'Save', { k: 'primary', full: true, icon: k === 'saving' ? 'loader-circle' : null, dis: !canSave && k !== 'saving' })) const bar = m && D('flex-shrink:0;display:flex;align-items:center;gap:8px;padding:12px 16px;border-top:1px solid var(--ui-border);background:var(--ui-bg);position:relative;z-index:1', B('Cancel', { full: true, dis }), B(k === 'saving' ? 'Saving…' : 'Save', { k: 'primary', full: true, icon: k === 'saving' ? 'loader-circle' : null, dis: !canSave && k !== 'saving' }))
main = D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;position:relative', Page(pad, Title(isNew ? 'New entry' : 'Lime plaster workshop', isNew ? 'Events · Fields marked * are required.' : 'Events · Entry 42', acts), m && D('display:flex;align-items:center;justify-content:space-between', chip), ban, form), bar) main = D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;position:relative', Page(pad, Title(isNew ? 'New entry' : 'Lime plaster workshop', isNew ? 'Events · Fields marked * are required.' : 'Events · Entry 42', acts), m && D('display:flex;align-items:center;justify-content:space-between', chip), ban, mk ? D('flex:1;min-height:0;overflow:hidden', D('margin-top:' + (m ? (k === 'changed' ? -740 : -560) : -380) + 'px', form)) : form), bar)
if (k === 'delete') ov.push(Shell({ title: 'Delete this entry?', desc: '"Lime plaster workshop" will be deleted from Events. This can\'t be undone.', close: true, cancel: 'Cancel', confirm: 'Delete entry', tone: 'danger' }, [])) if (k === 'delete') ov.push(Shell({ title: 'Delete this entry?', desc: '"Lime plaster workshop" will be deleted from Events. This can\'t be undone.', close: true, cancel: 'Cancel', confirm: 'Delete entry', tone: 'danger' }, []))
if (k === 'saved') ov.push(Toast('success', 'circle-check', 'Entry saved', '"Lime plaster workshop" is up to date.')) if (k === 'saved') ov.push(Toast('success', 'circle-check', 'Entry saved', '"Lime plaster workshop" is up to date.'))
} }
+446
View File
@@ -0,0 +1,446 @@
export const tables = [
{
"title": "Media field: scope",
"tpl": "260px 140px minmax(0,1fr)",
"cols": [
"Screen or state",
"Scope",
"Note"
],
"rows": [
[
"2 Builder: media field selected, new, required",
"Available now",
"Needs the media type in the schema API."
],
[
"3 Review: refused and clean",
"Available now",
"The refusal is known to the client before the server answers."
],
[
"4 Field types: Media frame",
"Available now",
"The filter widget is Later: filtering on custom fields isn't in the API."
],
[
"5 Entry list: Thumbnail column, Columns menu, tooltip",
"Available now",
"Needs image summaries in the entry list payload."
],
[
"6 Entry editor: Media control, 10 states",
"Available now",
""
],
[
"10 Picker for fields, 8 states",
"Available now",
"Same endpoints as the article picker."
],
[
"11 Media library usage, 4 states",
"Available now",
"Needs entries in the usage endpoint."
],
[
"1 Schema list: custom type read-only view",
"Available now",
"Table only; the route is a decision, see conflicts."
],
[
"Several images in one field",
"Not drawn",
"Out of scope."
]
]
},
{
"title": "Media field: exact copy",
"tpl": "200px 200px minmax(0,1fr)",
"cols": [
"Surface",
"Element",
"Copy"
],
"rows": [
[
"Inspector",
"Hint",
"Holds one image from the media library. Entries link to the image instead of keeping a copy, so they always show its current version."
],
[
"Inspector",
"Locked type",
"Media · Can't change after saving."
],
[
"Inspector",
"Required",
"Required · An entry can't be saved with this field empty."
],
[
"Field row",
"Tag",
"Required"
],
[
"Review",
"Refusal row",
"Add Thumbnail · Can't be applied · Media, required. A media field can't have a default, so the 12 existing entries would have no image. Make Thumbnail optional to add it."
],
[
"Review",
"Clean row",
"Add Thumbnail · Media, optional. 12 entries are unaffected."
],
[
"Control",
"Empty",
"No image selected. · Pick an image"
],
[
"Control",
"Filled",
"lime-plaster-workshop.jpg · 1600 × 900 · 240 KB · Change image · Remove"
],
[
"Control",
"Help",
"One image from your library."
],
[
"Control",
"Error",
"Pick an image for Thumbnail."
],
[
"Control",
"Missing",
"This image is no longer in the library · Choose another image · Clear"
],
[
"Control",
"Missing help",
"Optional: You can still save. The entry keeps the link until you change it. Required: Thumbnail is required. Choose another image to save."
],
[
"Control",
"Announcements (live, polite)",
"Image selected: lime-plaster-workshop.jpg · Image removed from Thumbnail. · Thumbnail cleared."
],
[
"Read view",
"Rules cell",
"Optional · One image from the library"
],
[
"Gallery",
"Name, description",
"Media · One image from your media library"
],
[
"Picker",
"Title, search, row",
"Choose an image · Search by filename · No image · Leave this field empty."
],
[
"Picker",
"Badge and buttons",
"Current · Load more · Cancel · Use this image · Remove image (when No image is chosen)"
],
[
"Picker",
"States",
"Your library is empty · Images you upload appear here, ready to use in any article or entry. · Upload an image · Couldn't load your library · Check your connection and try again. · Try again"
],
[
"Entry list",
"Header, empty, missing",
"Thumbnail · – · Image no longer in the library"
],
[
"Media library",
"Badge and tooltip",
"Used in 3 · Used in entries: 3"
],
[
"Media library",
"Panel",
"Used in entries · and 2 more"
],
[
"Media library",
"Delete",
"Delete an image that's in use? · \"lime-plaster.jpg\" is used in 5 entries and 2 articles. Those entry fields will show \"This image is no longer in the library\", and the articles will show a broken image. This can't be undone. · Cancel · Delete image"
]
]
},
{
"title": "Media field: components, reused and new",
"tpl": "220px 140px minmax(0,1fr)",
"cols": [
"Component",
"Status",
"Notes"
],
"rows": [
[
"AppFrame, SchemaFrame builder rows, Insp, FRow, review dialog rows, entry form, entry list and Columns menu",
"Reused",
"The inspector hides Unique, default and limits for media, as it does for yes or no. One more type tile (seven)."
],
[
"MediaFrame: grid card, list row, detail panel, delete dialog, picker dialog",
"Reused",
"Picker gains a field mode (no alt text, no variant select, Current, No image). Panel gains a Used in entries list. Badge counts articles plus entries."
],
[
"MediaFieldControl",
"New (the only one)",
"Props: label, required, modelValue (image id or null), image (summary or missing), disabled, error. Emits update:modelValue. Opens the picker."
],
[
"Nuxt UI mapping",
"Nuxt UI v4",
"UFormField (label, help, error, required) · UButton \"Pick an image\", \"Change image\", \"Choose another image\" (outline) · UButton \"Remove\", \"Clear\" (ghost) · UModal on desktop and a bottom UDrawer on mobile for the picker, as the article picker · UTooltip in the list and on the badge · UIcon lucide:image, lucide:image-off, lucide:unlink. The thumbnail is a plain button."
]
]
},
{
"title": "Picker and field failures: status to copy",
"tpl": "160px minmax(0,1fr)",
"cols": [
"Request and status",
"Copy"
],
"rows": [
[
"GET /v1/media/ 400",
"That request wasn't valid. Check the fields and try again. (search is trimmed first, so this is rare)"
],
[
"GET /v1/media/ 401, 403",
"Global redirect, no local copy."
],
[
"GET /v1/media/ 429",
"Too many requests. Try again in a few minutes. (countdown alert as on the Media page)"
],
[
"GET /v1/media/ 500, network",
"Couldn't load your library · Check your connection and try again. · Try again (500 body: Something went wrong on our side. Nothing was changed. Try again in a moment.)"
],
[
"POST /v1/media/ 413",
"That file is too large."
],
[
"POST /v1/media/ 400",
"That request wasn't valid. Check the fields and try again."
],
[
"POST /v1/media/ 429",
"Too many requests. Try again in a few minutes."
],
[
"POST /v1/media/ 500, network",
"Something went wrong on our side. Nothing was changed. Try again in a moment."
],
[
"PUT entry 422 invalid_entry thumbnail: required",
"Pick an image for Thumbnail."
],
[
"PUT entry 422 invalid_entry thumbnail: type",
"Thumbnail must be an image from the library. (the image was deleted between the pick and the save)"
],
[
"PUT entry 409",
"This changed somewhere else. Reload and try again."
],
[
"DELETE /v1/media/{id} 404",
"That item no longer exists."
],
[
"DELETE /v1/media/{id} 500, network",
"Something went wrong on our side. Nothing was changed. Try again in a moment."
]
]
},
{
"title": "Row height with media",
"tpl": "220px minmax(0,1fr)",
"cols": [
"Surface",
"Choice and reason"
],
"rows": [
[
"Desktop table",
"The design rule is 48 px rows (56 px for the media library). The brief mentions 32 px, which the design does not use. The thumbnail is 40 px, so a 48 px row keeps 4 px above and below and does not grow. No row exceeds 48 px."
],
[
"Mobile card",
"Cards are 68 px minimum. The thumbnail is 32 px and leads the card. Cards do not grow."
],
[
"Missing image",
"Dashed square with the same 40 px (32 px) footprint, so the columns stay aligned and the row does not move."
]
]
},
{
"title": "Accessibility",
"tpl": "220px minmax(0,1fr)",
"cols": [
"Topic",
"Notes"
],
"rows": [
[
"Group and label",
"MediaFieldControl is role=\"group\" labelled by the field label. A required field adds aria-required to the control button and the * is part of the label text."
],
[
"Button names",
"Pick an image → \"Pick an image for Thumbnail\". Thumbnail button → \"Change image, lime-plaster-workshop.jpg, 1600 by 900, 240 KB\". Remove → \"Remove image from Thumbnail\". Clear → \"Clear Thumbnail\". Missing placeholder: role img, \"Image no longer in the library\". Each name starts with the visible label."
],
[
"Focus order",
"Label, thumbnail, Change image, Remove, help or error. The thumbnail duplicates Change image; if reviewers prefer one stop, make it tabindex -1 and keep the pointer shortcut."
],
[
"Announcements",
"One polite live region on the control: \"Image selected: lime-plaster-workshop.jpg\", \"Image removed from Thumbnail.\", \"Thumbnail cleared.\" No announcement when the picker opens."
],
[
"Focus after actions",
"Picker closes with Use this image: focus goes to Change image. Remove or Clear: focus goes to Pick an image. Cancel or Esc: focus returns to the button that opened it. Save refused: focus goes to the first invalid control (Pick an image or Choose another image)."
],
[
"Error",
"The error text has an id. The control button gets aria-invalid=\"true\" and aria-describedby set to the error id, then the help id. aria-invalid is not defined for group, so it sits on the focusable button."
],
[
"Picker",
"Tabs follow the existing tablist pattern. Tiles are buttons with aria-pressed and names like \"stone-steps.jpg, 310 KB\" and \", Current\". No image is a button with aria-pressed. Use this image uses aria-disabled while nothing is chosen. Load more keeps focus until new tiles arrive."
],
[
"Contrast and targets",
"Current badge is on-sand on sand (14.3). Text on selected tiles uses on-sand, never muted. The hover bar is inverted text on inverted ground (18.9). Dashed borders use border-accented (3.6). Mobile targets are 44 px."
],
[
"Motion and touch",
"No hover on mobile. Hover and focus never carry information alone."
]
]
},
{
"title": "Needs backend",
"tpl": "260px minmax(0,1fr)",
"cols": [
"Item",
"What is needed"
],
"rows": [
[
"Media field type",
"Schema API accepts type \"media\" with label, key, required only. The value is an image id or null. Writes with a missing id on a changed value return 422 invalid_entry, type."
],
[
"Image summary in entries",
"Entry and list responses include, per media field, filename, width, height, size and a small thumbnail URL, or a flag that the image is missing, so the editor and list need no extra requests."
],
[
"Usage by entries",
"GET /v1/media/{id}/usage returns articles and entries (content type name, key, entry id, title), a total count and the first few items."
],
[
"Counts for the badge and delete",
"GET /v1/media/ list items carry the combined use count. DELETE keeps working for used images; the entries keep their ids."
],
[
"Required with entries",
"The server refuses a new required media field on a type with entries with schema_incompatible. The client shows the refusal first."
]
]
},
{
"title": "Media field: conflicts with the existing design, decide before coding",
"tpl": "40px 260px minmax(0,1fr)",
"cols": [
"#",
"Brief",
"Existing design and what the board does"
],
"rows": [
[
"1",
"Rows follow a 32 px density rule.",
"Tables use 48 px rows (56 px for media) and 68 px cards. Drawn at 48 and 68; the 40 px thumbnail fits without growing a row."
],
[
"2",
"Thumbnail sits between Description and Starts on.",
"In the existing editor Description is the last field and Starts on comes second. Drawn after Description, at the end of the form, which is schema order. Moving it needs a different form order."
],
[
"3",
"\"Used in 3\" counts entries.",
"Today \"Used in N\" counts articles. Drawn as articles plus entries; the tooltip and the panel split them."
],
[
"4",
"Delete title \"Delete this image?\".",
"The existing dialog for an image in use is \"Delete an image that's in use?\" with an articles list. Kept that title and added the entries list. \"Delete this image?\" stays the unused-image title."
],
[
"5",
"\"Clear\" in the missing state.",
"The glossary says Remove detaches and the filled state uses Remove. Kept \"Clear\" as written. Suggest Remove for both."
],
[
"6",
"\"1600 x 900 - 240 KB\".",
"The design uses × and the middle dot (\"1600 × 900 · 240 KB\")."
],
[
"7",
"Refuse the required media field in the review step.",
"The review is informational and Apply changes is never disabled; the server decides. This one case is certain, so Apply is off. Alternative: leave Apply on and show the 422 refusal dialog."
],
[
"8",
"Primary button \"Use this image\".",
"The article picker says \"Insert image\". When No image is chosen the button reads \"Remove image\" (my addition). The picker keeps its existing copy for empty and failed states."
],
[
"9",
"Pick an image on empty optional fields too.",
"The brief names the button for required fields only. One name covers both."
],
[
"10",
"Read view of a custom type.",
"Only owners and admins see Schema, and they edit. No read-only route exists for custom types. Table drawn as the built-in one; the route is a decision."
],
[
"11",
"Thumbnail focus ring.",
"The thumbnail and Change image open the same picker, so there are two tab stops. See accessibility."
],
[
"12",
"Disabled look.",
"Entry form fields dim to 60% and foundations.md says 40%. The control follows the form."
],
[
"13",
"Picker page behind the dialog.",
"The existing picker frame shows the article editor. The field picker shows a stand-in for the entry form."
]
]
}
]
+45 -7
View File
@@ -1,3 +1,4 @@
import { tables as mfTables } from './media-field-tables.js'
const N = 'available now', L = 'later' const N = 'available now', L = 'later'
const st = (name, scope, trigger, s, copy, o = {}) => ({ name, scope, trigger, s, copy, ...o }) const st = (name, scope, trigger, s, copy, o = {}) => ({ name, scope, trigger, s, copy, ...o })
@@ -8,7 +9,8 @@ export const groups = [
st('Empty: no custom type yet', N, 'GET /v1/content-type returns []. Built-ins are still listed below.', { v: 'types', k: 'empty' }, 'No content types yet · Create a content type to manage your own kind of content, like events or recipes. The built-in types stay as they are. · New content type'), st('Empty: no custom type yet', N, 'GET /v1/content-type returns []. Built-ins are still listed below.', { v: 'types', k: 'empty' }, 'No content types yet · Create a content type to manage your own kind of content, like events or recipes. The built-in types stay as they are. · New content type'),
st('Error', N, '500 or network failure on the list request.', { v: 'types', k: 'error' }, 'Couldn\'t load content types · GET /v1/content-type failed. Check your connection and try again. · Try again'), st('Error', N, '500 or network failure on the list request.', { v: 'types', k: 'error' }, 'Couldn\'t load content types · GET /v1/content-type failed. Check your connection and try again. · Try again'),
st('Forbidden (403)', N, 'A user who is not owner or admin types /schema. There is no sidebar entry, so the page explains instead of redirecting.', { v: 'types', k: 'forbidden' }, 'You don\'t have access to Schema · Only owners and admins can change content types. You can still add and edit entries from the Content menu. · Go to Home'), st('Forbidden (403)', N, 'A user who is not owner or admin types /schema. There is no sidebar entry, so the page explains instead of redirecting.', { v: 'types', k: 'forbidden' }, 'You don\'t have access to Schema · Only owners and admins can change content types. You can still add and edit entries from the Content menu. · Go to Home'),
st('Built-in type: read-only view', N, 'Click Articles in the list. No edit, no delete, no add field.', { v: 'types', k: 'builtin' }, 'Articles · Built-in · Managed by RenewCMS · Articles is a built-in type. You can read its fields here, but you can\'t edit it, delete it or add fields. · Label · Key · Type · Rules · Entries of built-in types are managed from their own screens, like Articles and Authors.') st('Built-in type: read-only view', N, 'Click Articles in the list. No edit, no delete, no add field.', { v: 'types', k: 'builtin' }, 'Articles · Built-in · Managed by RenewCMS · Articles is a built-in type. You can read its fields here, but you can\'t edit it, delete it or add fields. · Label · Key · Type · Rules · Entries of built-in types are managed from their own screens, like Articles and Authors.'),
st("Custom type: read-only view", N, "The fields table of a custom type with a media field. Same table as the built-in view; the Media type shows the image icon and the name \"Media\".", {"v":"types","k":"customro"}, "Events · Read only · You can read these fields here · Only an owner or admin can change a content type. · Label · Key · Type · Rules · Thumbnail · thumbnail · Media · One image from the library")
] }, ] },
{ label: '2 Schema builder', title: '2 Schema builder', route: '/schema/new, /schema/:key', api: 'POST /v1/content-type, GET/PUT /v1/content-type/{key}', auth: 'Owner or admin', note: 'One screen, three regions: type name and key on top, ordered field list on the left, field inspector on the right, collapsible API preview at the bottom. Mobile: the list is the page, the inspector is a 92% sheet, the API preview is a sheet. Field keys and types of saved fields are locked; fields added since the last save can still choose both.', states: [ { label: '2 Schema builder', title: '2 Schema builder', route: '/schema/new, /schema/:key', api: 'POST /v1/content-type, GET/PUT /v1/content-type/{key}', auth: 'Owner or admin', note: 'One screen, three regions: type name and key on top, ordered field list on the left, field inspector on the right, collapsible API preview at the bottom. Mobile: the list is the page, the inspector is a 92% sheet, the API preview is a sheet. Field keys and types of saved fields are locked; fields added since the last save can still choose both.', states: [
st('New type', N, '/schema/new. One starter field is added because a type needs at least one.', { v: 'builder', k: 'new' }, 'New content type · Name · For example, Events · Key · events · Used in URLs and the API. Lowercase letters, digits and hyphens. It can\'t change after you save. · Fields · 1 of 50 · Add field · Field: Title · Label · Key · The name used in the API. Starts with a letter. Lowercase letters, digits and underscores. · Type · Required · An entry can\'t be saved with this field empty. · Unique values · Default value · Used when an entry is created and this field is left out. · Shortest · Longest · Counted in characters. Entries show a counter. · Save · Discard'), st('New type', N, '/schema/new. One starter field is added because a type needs at least one.', { v: 'builder', k: 'new' }, 'New content type · Name · For example, Events · Key · events · Used in URLs and the API. Lowercase letters, digits and hyphens. It can\'t change after you save. · Fields · 1 of 50 · Add field · Field: Title · Label · Key · The name used in the API. Starts with a letter. Lowercase letters, digits and underscores. · Type · Required · An entry can\'t be saved with this field empty. · Unique values · Default value · Used when an entry is created and this field is left out. · Shortest · Longest · Counted in characters. Entries show a counter. · Save · Discard'),
@@ -26,7 +28,10 @@ export const groups = [
st('Save failed', N, '500 or network failure. Nothing was sent as saved; the edits stay.', { v: 'builder', k: 'fail' }, 'Save failed · Couldn\'t save the content type · Something went wrong on our side. Your changes are still here. Try again in a moment. · Try again'), st('Save failed', N, '500 or network failure. Nothing was sent as saved; the edits stay.', { v: 'builder', k: 'fail' }, 'Save failed · Couldn\'t save the content type · Something went wrong on our side. Your changes are still here. Try again in a moment. · Try again'),
st('Key already taken', N, '409 content_type_key_taken on POST.', { v: 'builder', k: 'taken' }, 'The key "events" is already used by another content type. Choose a different key.'), st('Key already taken', N, '409 content_type_key_taken on POST.', { v: 'builder', k: 'taken' }, 'The key "events" is already used by another content type. Choose a different key.'),
st('Schema incompatible', N, '422 schema_incompatible on PUT. The review dialog (group 3) closes into this state. Changes of the kinds that can cause it are marked.', { v: 'builder', k: 'incompat' }, 'Nothing was changed · Some entries don\'t fit the new fields, so the whole change was refused. RenewCMS can\'t tell which entries. The changes that can cause this are marked. · Review changes · Possible cause'), st('Schema incompatible', N, '422 schema_incompatible on PUT. The review dialog (group 3) closes into this state. Changes of the kinds that can cause it are marked.', { v: 'builder', k: 'incompat' }, 'Nothing was changed · Some entries don\'t fit the new fields, so the whole change was refused. RenewCMS can\'t tell which entries. The changes that can cause this are marked. · Review changes · Possible cause'),
st('Offline', N, 'navigator.onLine is false. Edits are kept; Save is disabled.', { v: 'builder', k: 'offline' }, 'You\'re offline. Changes will be saved when you reconnect. · Waiting for connection') st('Offline', N, 'navigator.onLine is false. Edits are kept; Save is disabled.', { v: 'builder', k: 'offline' }, 'You\'re offline. Changes will be saved when you reconnect. · Waiting for connection'),
st("Media field selected", N, "Thumbnail was saved before. Key and type are locked. The inspector shows Label, Key, Type and Required only; the hint explains the field holds one image.", {"v":"builder","k":"media"}, "Thumbnail · thumbnail · Field: Thumbnail · Key · Used in the API, so it can't change. · Type · Can't change after saving · Media · One image from your media library · Required · An entry can't be saved with this field empty. · Holds one image from the media library. Entries link to the image instead of keeping a copy, so they always show its current version."),
st("New media field, seven types", N, "Add field, then Media. The type tiles show all seven types; key and type can still change.", {"v":"builder","k":"mnew"}, "New · Type · Text · Rich text · Number · Yes or no · Date · Choice · Media · One image from your media library · Key · The name used in the API. Starts with a letter. Lowercase letters, digits and underscores."),
st("Media field, required", N, "A saved required media field. The row carries the Required marker.", {"v":"builder","k":"mreq"}, "Thumbnail · thumbnail · Required (marker) · Required · An entry can't be saved with this field empty.")
] }, ] },
{ label: '3 Review and delete', title: '3 Schema change review and delete type', route: '/schema/:key (dialogs)', api: 'PUT /v1/content-type/{key}, DELETE /v1/content-type/{key}', auth: 'Owner or admin', note: 'The review opens on Save when the type already has entries (37 here). It is informational: the server decides compatibility. Destructive changes (removing a field or a choice, tightening a limit, making a field unique or required) carry a warning flag. Per-change entry counts and a full diff are later.', states: [ { label: '3 Review and delete', title: '3 Schema change review and delete type', route: '/schema/:key (dialogs)', api: 'PUT /v1/content-type/{key}, DELETE /v1/content-type/{key}', auth: 'Owner or admin', note: 'The review opens on Save when the type already has entries (37 here). It is informational: the server decides compatibility. Destructive changes (removing a field or a choice, tightening a limit, making a field unique or required) carry a warning flag. Per-change entry counts and a full diff are later.', states: [
st('Review before saving', N, 'Save on a type that has entries.', { v: 'review', k: 'review' }, 'Review changes to Events · Apply them to save the content type. · Add 2 fields, change 1, remove 1 · Events has 37 entries. Each one is checked against the new fields when you apply. · Add Speaker · Text, optional. · Add Room · Choice, required, default "Main hall". Existing entries get the default, so they still fit. · Change Capacity · Highest value goes from 5000 to 2000. · Entries may not fit · Remove Description · Entries stop returning its values. · Removes data · Flagged changes can be refused if existing entries don\'t fit. If that happens, nothing is changed. · Back to editing · Apply changes'), st('Review before saving', N, 'Save on a type that has entries.', { v: 'review', k: 'review' }, 'Review changes to Events · Apply them to save the content type. · Add 2 fields, change 1, remove 1 · Events has 37 entries. Each one is checked against the new fields when you apply. · Add Speaker · Text, optional. · Add Room · Choice, required, default "Main hall". Existing entries get the default, so they still fit. · Change Capacity · Highest value goes from 5000 to 2000. · Entries may not fit · Remove Description · Entries stop returning its values. · Removes data · Flagged changes can be refused if existing entries don\'t fit. If that happens, nothing is changed. · Back to editing · Apply changes'),
@@ -35,9 +40,11 @@ export const groups = [
st('Review with counts and diff', L, 'Per-change entry counts and a full diff need an API that does not exist yet.', { v: 'review', k: 'later' }, 'Affects 0 entries · Affects 37 entries · Affects 3 entries · Affects 31 entries · View full diff · Per-change counts and diff come later', { notNow: true }), st('Review with counts and diff', L, 'Per-change entry counts and a full diff need an API that does not exist yet.', { v: 'review', k: 'later' }, 'Affects 0 entries · Affects 37 entries · Affects 3 entries · Affects 31 entries · View full diff · Per-change counts and diff come later', { notNow: true }),
st('Delete type: blocked', N, 'Delete content type on a type with entries. No confirm button.', { v: 'review', k: 'blocked' }, 'You can\'t delete Events yet · A content type can only be deleted when it has no entries. · Events has 37 entries · Delete all of its entries first, then delete the content type. · Close · View entries'), st('Delete type: blocked', N, 'Delete content type on a type with entries. No confirm button.', { v: 'review', k: 'blocked' }, 'You can\'t delete Events yet · A content type can only be deleted when it has no entries. · Events has 37 entries · Delete all of its entries first, then delete the content type. · Close · View entries'),
st('Delete type: confirm', N, 'Delete content type on an empty type.', { v: 'review', k: 'confirm' }, 'Delete Recipes? · Recipes has no entries. Its fields and its API routes will be deleted. This can\'t be undone. · Key: recipes · Cancel · Delete content type'), st('Delete type: confirm', N, 'Delete content type on an empty type.', { v: 'review', k: 'confirm' }, 'Delete Recipes? · Recipes has no entries. Its fields and its API routes will be deleted. This can\'t be undone. · Key: recipes · Cancel · Delete content type'),
st('Delete type: server fallback (409)', N, '409 content_type_has_entries. An entry was added after the page loaded.', { v: 'review', k: 'fallback' }, 'Recipes now has entries · Someone added an entry after this page loaded, so nothing was deleted. Delete the entries first, then try again. · Close · View entries') st('Delete type: server fallback (409)', N, '409 content_type_has_entries. An entry was added after the page loaded.', { v: 'review', k: 'fallback' }, 'Recipes now has entries · Someone added an entry after this page loaded, so nothing was deleted. Delete the entries first, then try again. · Close · View entries'),
st("Review: required media field refused", N, "Thumbnail is required and Events has 12 entries. A media field can't have a default, so Apply is off.", {"v":"review","k":"mrefuse"}, "Review changes to Events · Apply them to save the content type. · Add 1 field · Events has 12 entries. Each one is checked against the new fields when you apply. · Add Thumbnail · Can't be applied · Media, required. A media field can't have a default, so the 12 existing entries would have no image. Make Thumbnail optional to add it. · Back to editing keeps your other changes. · Back to editing · Apply changes (disabled)"),
st("Review: optional media field", N, "Thumbnail is optional.", {"v":"review","k":"mclean"}, "Review changes to Events · Add 1 field · Events has 12 entries. Each one is checked against the new fields when you apply. · Add Thumbnail · Media, optional. 12 entries are unaffected. · Back to editing · Apply changes")
] }, ] },
{ label: '4 Field types', title: '4 Field-type gallery', route: 'reference board', api: '', auth: 'n/a', note: 'One frame per type: inspector options, the entry form control (default and open states), the list cell with its empty state, the error message for each rule, and the filter widget. Filters are later: filtering on custom fields is not in the API. Mobile drops the inspector column (the builder frames show it as a sheet).', states: ['text', 'richtext', 'number', 'boolean', 'date', 'select'].map((t, i) => st(['Text', 'Rich text', 'Number', 'Yes or no', 'Date', 'Choice'][i], N, 'type: "' + t + '"', { v: 'gallery', k: t }, ({ text: 'Text · Short text, like a title or a name · Shortest · Longest · characters · 74 / 80 · Fill in Title. · Title must be text. · Title needs at least 3 characters. · Title can be up to 80 characters. · Another entry already uses this Title. Enter a different one.', richtext: 'Rich text · Long text with formatting, written in Markdown · Write · Preview · Markdown. Switch to Preview to check the result. · 86 / 5000 · Not available for rich text. (Unique)', number: 'Number · Whole or decimal numbers · Lowest value · Highest value · Enter a number · Between 1 and 5000. · Description must be a number. · Capacity must be at least 1. · Capacity must be at most 5000.', boolean: 'Yes or no · An on or off switch · On by default · Yes or no fields have no limits. · Not available for yes or no fields. (Unique) · Choose yes or no for Online. · Online must be yes or no.', date: 'Date · A calendar day, without a time · Earliest date · Latest date · Pick a date · Pick a date for Starts on. · Starts on must be a date, like 2026-11-21. · Starts on can\'t be before 1 Jan 2026. · Starts on can\'t be after 31 Dec 2027.', select: 'Choice · One option from a list you define · Choices · Choose an option · Choose one of: Talk, Workshop or Meetup. · Another entry already uses this choice for Category.' })[t])) }, { label: '4 Field types', title: '4 Field-type gallery', route: 'reference board', api: '', auth: 'n/a', note: 'One frame per type: inspector options, the entry form control (default and open states), the list cell with its empty state, the error message for each rule, and the filter widget. Filters are later: filtering on custom fields is not in the API. Mobile drops the inspector column (the builder frames show it as a sheet).', states: ['text', 'richtext', 'number', 'boolean', 'date', 'select', 'media'].map((t, i) => st(['Text', 'Rich text', 'Number', 'Yes or no', 'Date', 'Choice', 'Media'][i], N, 'type: "' + t + '"', { v: 'gallery', k: t }, ({ text: 'Text · Short text, like a title or a name · Shortest · Longest · characters · 74 / 80 · Fill in Title. · Title must be text. · Title needs at least 3 characters. · Title can be up to 80 characters. · Another entry already uses this Title. Enter a different one.', richtext: 'Rich text · Long text with formatting, written in Markdown · Write · Preview · Markdown. Switch to Preview to check the result. · 86 / 5000 · Not available for rich text. (Unique)', number: 'Number · Whole or decimal numbers · Lowest value · Highest value · Enter a number · Between 1 and 5000. · Description must be a number. · Capacity must be at least 1. · Capacity must be at most 5000.', boolean: 'Yes or no · An on or off switch · On by default · Yes or no fields have no limits. · Not available for yes or no fields. (Unique) · Choose yes or no for Online. · Online must be yes or no.', date: 'Date · A calendar day, without a time · Earliest date · Latest date · Pick a date · Pick a date for Starts on. · Starts on must be a date, like 2026-11-21. · Starts on can\'t be before 1 Jan 2026. · Starts on can\'t be after 31 Dec 2027.', media: 'Media · One image from your media library · Label · Key · Required · Holds one image from the media library. Entries link to the image instead of keeping a copy, so they always show its current version. · Pick an image · No image selected. · One image from your library. · Change image · Remove · lime-plaster-workshop.jpg · 1600 × 900 · 240 KB · This image is no longer in the library · Choose another image · Clear · Pick an image for Thumbnail. · Thumbnail must be an image from the library. · Not used for media. · Thumbnail: has an image (later)', select: 'Choice · One option from a list you define · Choices · Choose an option · Choose one of: Talk, Workshop or Meetup. · Another entry already uses this choice for Category.' })[t])) },
{ label: '5 Content and entry list', title: '5 Content navigation and entry list', route: '/content/:key', api: 'GET /v1/content-type/{key}, GET /v1/content-type/{key}/entry', auth: 'Any verified user', note: 'The sidebar gets a "Content" group, one item per custom type (a default icon: types have no icon in the API). With more than 5 types it shows the first 5 and the selected one, then "Show all N"; long names truncate with the full name in a tooltip. On mobile the group is one collapsed row in the drawer. List: ID, up to 6 chosen field columns (default: first 4), Created, Updated, Updated by. Sort: ID, Created, Updated, either direction (default Updated, newest first). Page size 5, 25, 50, 100 (default 25). No filter or search. URL: /content/events?page=2&size=50&sort=created_at:desc (defaults omitted). The response carries total, page, size and sort; the summary, the pager and the review dialog use them.', states: [ { label: '5 Content and entry list', title: '5 Content navigation and entry list', route: '/content/:key', api: 'GET /v1/content-type/{key}, GET /v1/content-type/{key}/entry', auth: 'Any verified user', note: 'The sidebar gets a "Content" group, one item per custom type (a default icon: types have no icon in the API). With more than 5 types it shows the first 5 and the selected one, then "Show all N"; long names truncate with the full name in a tooltip. On mobile the group is one collapsed row in the drawer. List: ID, up to 6 chosen field columns (default: first 4), Created, Updated, Updated by. Sort: ID, Created, Updated, either direction (default Updated, newest first). Page size 5, 25, 50, 100 (default 25). No filter or search. URL: /content/events?page=2&size=50&sort=created_at:desc (defaults omitted). The response carries total, page, size and sort; the summary, the pager and the review dialog use them.', states: [
st('Populated', N, '/content/events. 7 entries, one page: no pager, only the count.', { v: 'entries', k: 'ok' }, 'Content · Events · events · 7 fields · New entry · Sort by · Last updated · Columns · Edit content type · ID · Title · Starts on · Ends on · Online · Created · Updated · Updated by · 7 entries'), st('Populated', N, '/content/events. 7 entries, one page: no pager, only the count.', { v: 'entries', k: 'ok' }, 'Content · Events · events · 7 fields · New entry · Sort by · Last updated · Columns · Edit content type · ID · Title · Starts on · Ends on · Online · Created · Updated · Updated by · 7 entries'),
st('Paginated, 5 per page', N, '/content/events?size=5. 37 entries.', { v: 'entries', k: 'paged' }, 'Showing 1–5 of 37 · 5 per page · Page 1 of 8 (mobile)'), st('Paginated, 5 per page', N, '/content/events?size=5. 37 entries.', { v: 'entries', k: 'paged' }, 'Showing 1–5 of 37 · 5 per page · Page 1 of 8 (mobile)'),
@@ -47,7 +54,10 @@ export const groups = [
st('Empty for this type', N, 'Total is 0. The hint points to New entry.', { v: 'entries', k: 'empty' }, 'No entries yet · Use New entry to add the first event. Each entry follows the fields of this content type. · New entry'), st('Empty for this type', N, 'Total is 0. The hint points to New entry.', { v: 'entries', k: 'empty' }, 'No entries yet · Use New entry to add the first event. Each entry follows the fields of this content type. · New entry'),
st('Error', N, '500 or network failure.', { v: 'entries', k: 'error' }, 'Couldn\'t load entries · GET /v1/content-type/events/entry failed. Check your connection and try again. · Try again'), st('Error', N, '500 or network failure.', { v: 'entries', k: 'error' }, 'Couldn\'t load entries · GET /v1/content-type/events/entry failed. Check your connection and try again. · Try again'),
st('Forbidden (403)', N, 'The API answers 403. Unverified accounts are redirected to /register/pending before this.', { v: 'entries', k: 'forbidden', role: 'user' }, 'You don\'t have access to Events · Your account can\'t open this content right now. If you think this is a mistake, ask an owner or an admin. · Go to Home'), st('Forbidden (403)', N, 'The API answers 403. Unverified accounts are redirected to /register/pending before this.', { v: 'entries', k: 'forbidden', role: 'user' }, 'You don\'t have access to Events · Your account can\'t open this content right now. If you think this is a mistake, ask an owner or an admin. · Go to Home'),
st('Type not found', N, '404 content_type_not_found on /content/unknown.', { v: 'entries', k: 'notfound' }, 'Content type not found · It may have been deleted, or the address may be mistyped. · Go to Home') st('Type not found', N, '404 content_type_not_found on /content/unknown.', { v: 'entries', k: 'notfound' }, 'Content type not found · It may have been deleted, or the address may be mistyped. · Go to Home'),
st("Thumbnail column", N, "Events list with a Thumbnail column: 40 px square thumbnails, one \"–\", one missing image. Row height stays 48 px. Mobile: 32 px thumbnail leads the card. Not sortable.", {"v":"entries","k":"thumb"}, "Thumbnail · Lime plaster workshop · Winter open day · – · Limewash masterclass · Image no longer in the library (accessible name)"),
st("Columns menu with Thumbnail", N, "Columns. Thumbnail is listed with the image icon.", {"v":"entries","k":"thumbcols"}, "Columns · 4 of 6 · Title · Description · Thumbnail · Starts on · Ends on · Online · Capacity · Category · Reset · Choose up to 6 fields to show. 4 selected."),
st("Missing image: tooltip", N, "Hover or focus on the dashed square (desktop). Mobile has no tooltip.", {"v":"entries","k":"thumbtip"}, "Image no longer in the library")
] }, ] },
{ label: '6 Entry editor', title: '6 Entry editor', route: '/content/:key/new, /content/:key/:id', api: 'POST /v1/content-type/{key}/entry, GET/PUT/DELETE /v1/content-type/{key}/entry/{id}', auth: 'Any verified user', note: 'The form is generated from the schema, one control per field in schema order. Required fields carry * and the line "Fields marked * are required." Defaults are pre-filled on create and tagged Default. Saving replaces the whole entry.', states: [ { label: '6 Entry editor', title: '6 Entry editor', route: '/content/:key/new, /content/:key/:id', api: 'POST /v1/content-type/{key}/entry, GET/PUT/DELETE /v1/content-type/{key}/entry/{id}', auth: 'Any verified user', note: 'The form is generated from the schema, one control per field in schema order. Required fields carry * and the line "Fields marked * are required." Defaults are pre-filled on create and tagged Default. Saving replaces the whole entry.', states: [
st('New entry', N, '/content/events/new. Online is pre-filled from its default.', { v: 'entry', k: 'new' }, 'New entry · Events · Fields marked * are required. · Default · Each entry needs a different title. · Between 1 and 5000. · Choose an option · Pick a date · Save · Cancel · New entry · Not saved yet'), st('New entry', N, '/content/events/new. Online is pre-filled from its default.', { v: 'entry', k: 'new' }, 'New entry · Events · Fields marked * are required. · Default · Each entry needs a different title. · Between 1 and 5000. · Choose an option · Pick a date · Save · Cancel · New entry · Not saved yet'),
@@ -62,7 +72,17 @@ export const groups = [
st('Duplicate unique value (409)', N, '409 invalid_entry: title: unique.', { v: 'entry', k: 'unique' }, 'Not saved · Another entry already uses this title. Change it and save again. · Another entry already uses this Title. Enter a different one.'), st('Duplicate unique value (409)', N, '409 invalid_entry: title: unique.', { v: 'entry', k: 'unique' }, 'Not saved · Another entry already uses this title. Change it and save again. · Another entry already uses this Title. Enter a different one.'),
st('Entry not found', N, '404 entry_not_found, for example after a delete elsewhere.', { v: 'entry', k: 'notfound' }, 'Entry not found · It may have been deleted by someone else. · Back to Events'), st('Entry not found', N, '404 entry_not_found, for example after a delete elsewhere.', { v: 'entry', k: 'notfound' }, 'Entry not found · It may have been deleted by someone else. · Back to Events'),
st('Schema changed since load', N, '422 invalid_entry: room: required, or unknown_field. The form is read-only until reloaded.', { v: 'entry', k: 'changed' }, 'The fields of Events changed · A field was removed and a new required field, Room, was added after you opened this form. Reload the form to continue. What you typed here can\'t be saved against the old fields. · Reload form'), st('Schema changed since load', N, '422 invalid_entry: room: required, or unknown_field. The form is read-only until reloaded.', { v: 'entry', k: 'changed' }, 'The fields of Events changed · A field was removed and a new required field, Room, was added after you opened this form. Reload the form to continue. What you typed here can\'t be saved against the old fields. · Reload form'),
st('Delete entry: confirm', N, 'Delete.', { v: 'entry', k: 'delete' }, 'Delete this entry? · "Lime plaster workshop" will be deleted from Events. This can\'t be undone. · Cancel · Delete entry') st('Delete entry: confirm', N, 'Delete.', { v: 'entry', k: 'delete' }, 'Delete this entry? · "Lime plaster workshop" will be deleted from Events. This can\'t be undone. · Cancel · Delete entry'),
st("Media control: empty, optional", N, "Thumbnail follows Description. Empty optional field.", {"v":"entry","k":"m","m":"empty"}, "Thumbnail · No image selected. · Pick an image · One image from your library."),
st("Media control: empty, required", N, "Field marked *.", {"v":"entry","k":"m","m":"emptyreq"}, "Thumbnail * · No image selected. · Pick an image · One image from your library."),
st("Media control: filled", N, "An image is picked.", {"v":"entry","k":"m","m":"filled"}, "Thumbnail · lime-plaster-workshop.jpg · 1600 × 900 · 240 KB · Change image · Remove · One image from your library."),
st("Media control: hover", N, "Pointer over the thumbnail (desktop). The border darkens and a bar reads Change image. Mobile shows the filled state.", {"v":"entry","k":"m","m":"hover"}, "Change image"),
st("Media control: focus", N, "Keyboard focus on the thumbnail: 2 px primary ring, 2 px offset.", {"v":"entry","k":"m","m":"focus"}, "Change image, lime-plaster-workshop.jpg (accessible name)"),
st("Media control: validation error", N, "Save with a required field empty (422 invalid_entry, required). Focus moves to Pick an image.", {"v":"entry","k":"m","m":"err"}, "Pick an image for Thumbnail. · Not saved"),
st("Media control: image no longer in the library", N, "The image was deleted. The entry keeps the link. Optional field: saving is allowed.", {"v":"entry","k":"m","m":"missing"}, "This image is no longer in the library · You can still save. The entry keeps the link until you change it. · Choose another image · Clear"),
st("Media control: missing image, required", N, "Same, on a required field. Save is refused.", {"v":"entry","k":"m","m":"missingreq"}, "This image is no longer in the library · Thumbnail is required. Choose another image to save. · Choose another image · Clear · Pick an image for Thumbnail. · Not saved"),
st("Media control: saving", N, "PUT in flight. The thumbnail and its buttons are disabled with the rest of the form.", {"v":"entry","k":"saving","m":"filled"}, "Saving…"),
st("Media control: read-only, type changed", N, "422 unknown_field. The form is read-only until reloaded.", {"v":"entry","k":"changed","m":"filled"}, "The fields of Events changed · The Thumbnail field was changed after you opened this form. Reload the form to continue. What you typed here can't be saved against the old fields. · Reload form")
] }, ] },
{ label: '7 Relations', title: '7 Relation field and picker', route: '/schema/:key, /content/:key/:id', api: 'not built', auth: 'Owner or admin (picker), any verified user (form)', note: 'All later. The model reads as two sentences, with a live preview of both sides. Three shapes: one to one, one to many, many to many.', states: [ { label: '7 Relations', title: '7 Relation field and picker', route: '/schema/:key, /content/:key/:id', api: 'not built', auth: 'Owner or admin (picker), any verified user (form)', note: 'All later. The model reads as two sentences, with a live preview of both sides. Three shapes: one to one, one to many, many to many.', states: [
st('Relation in the builder', L, 'A seventh type, Relation, in the type gallery.', { v: 'rel', k: 'builder' }, 'Relation · Related content type · How are they connected? · One to one · Each Event has one Venue, and each Venue has one Event. · One to many · Each Event has one Venue. A Venue has many Events. · Many to many · Each Event has many Venues, and each Venue has many Events. · Each Event has one Venue · Each Venue has many Events · shown on Venue as the field "Events"'), st('Relation in the builder', L, 'A seventh type, Relation, in the type gallery.', { v: 'rel', k: 'builder' }, 'Relation · Related content type · How are they connected? · One to one · Each Event has one Venue, and each Venue has one Event. · One to many · Each Event has one Venue. A Venue has many Events. · Many to many · Each Event has many Venues, and each Venue has many Events. · Each Event has one Venue · Each Venue has many Events · shown on Venue as the field "Events"'),
@@ -77,6 +97,22 @@ export const groups = [
st('Export', L, 'Export on /schema.', { v: 'xport', k: 'export' }, 'Export schema · Download the fields of your content types as a file. Entries aren\'t included. · All content types · 3 content types · One content type · Choose which one · File name · renewcms-schema.json · Import this file on another RenewCMS site to create the same content types. · Cancel · Download file'), st('Export', L, 'Export on /schema.', { v: 'xport', k: 'export' }, 'Export schema · Download the fields of your content types as a file. Entries aren\'t included. · All content types · 3 content types · One content type · Choose which one · File name · renewcms-schema.json · Import this file on another RenewCMS site to create the same content types. · Cancel · Download file'),
st('Import preview', L, 'A file was chosen.', { v: 'xport', k: 'import' }, 'Import schema · renewcms-schema.json · 3 content types · Create 1, change 1, no change 1 · Recipes · New content type with 4 fields. · Events · Add 2 fields, remove Description. Events has 37 entries on this site. · Removes data · Press mentions · Same as on this site. · Existing entries are checked against the changes when you import. If any entry doesn\'t fit, nothing is imported. · Cancel · Import schema'), st('Import preview', L, 'A file was chosen.', { v: 'xport', k: 'import' }, 'Import schema · renewcms-schema.json · 3 content types · Create 1, change 1, no change 1 · Recipes · New content type with 4 fields. · Events · Add 2 fields, remove Description. Events has 37 entries on this site. · Removes data · Press mentions · Same as on this site. · Existing entries are checked against the changes when you import. If any entry doesn\'t fit, nothing is imported. · Cancel · Import schema'),
st('Import refused', L, 'The server answers schema_incompatible.', { v: 'xport', k: 'refused' }, 'Nothing was imported · Some entries on this site don\'t fit the imported fields. RenewCMS can\'t tell which entries. The flagged change can cause this. · Try again') st('Import refused', L, 'The server answers schema_incompatible.', { v: 'xport', k: 'refused' }, 'Nothing was imported · Some entries on this site don\'t fit the imported fields. RenewCMS can\'t tell which entries. The flagged change can cause this. · Try again')
] },
{ label: '10 Media picker for fields', title: '10 Image picker from the entry editor', route: '/content/events/:id (dialog)', api: 'GET /v1/media/?q=&limit=&cursor= · POST /v1/media/', auth: 'Any verified user', note: "The existing picker (Media picker and Editor picker groups of the back-office board) with Upload and Library tabs, single selection, search and Load more. Changes: the title is \"Choose an image\", the primary button reads \"Use this image\", there is no alt text and no variant select, the current image carries \"Current\" in place of \"In this article\", and \"No image\" tops the Library tab for optional fields only. Desktop dialog, mobile bottom sheet. The page behind is a stand-in for the entry editor.", states: [
st("Library: nothing chosen", N, "Change image on an optional field. Current marks the image in the field.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Library","cur":1}}, "Choose an image · Upload · Library · Search by filename · No image · Leave this field empty. · Current · Newest first · 48 images · Load more · Cancel · Use this image (disabled)"),
st("Library: image chosen", N, "One tile selected (single selection). A strip shows filename, dimensions and size. No alt text field.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Library","cur":1,"sel":4}}, "kitchen-before.webp · 2400 × 1600 · 1.1 MB · Cancel · Use this image"),
st("Library: No image chosen", N, "Optional fields only. The primary button changes.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Library","cur":1,"sel":"none"}}, "No image · Leave this field empty. · Cancel · Remove image"),
st("Library: required field", N, "No \"No image\" row.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Library","cur":1,"req":true}}, "Choose an image · Cancel · Use this image (disabled)"),
st("Library: empty", N, "Zero images. Upload an image switches to the Upload tab.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Library","empty":"first"}}, "Your library is empty · Images you upload appear here, ready to use in any article or entry. · Upload an image"),
st("Library: failed to load", N, "500 or network failure. Other statuses: see the failures table.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Library","error":true}}, "Couldn't load your library · Check your connection and try again. · Try again"),
st("Library: loading", N, "First open or a new search. Skeleton tiles after 150 ms.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Library","loading":true}}, "(skeleton) · Use this image (disabled)"),
st("Upload tab", N, "The existing upload flow, including crop and resize. The new image lands in the library and is selected.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Upload"}}, "Drop an image here, or choose a file · PNG, JPEG, WEBP, SVG · max 10 MB")
] },
{ label: '11 Media library: usage', title: '11 Media library: usage by entries', route: '/media', api: 'GET /v1/media/ · GET /v1/media/{id}/usage · DELETE /v1/media/{id}', auth: 'Verified users', note: "Same Media screens as the back-office board. Entries count as uses: the \"Used in N\" badge adds articles and entries, its tooltip splits them, and the detail panel gains a \"Used in entries\" list (up to 3 links, then \"and N more\"). Deleting an image that entries use says how many and what the fields will show.", states: [
st("Grid: usage badge tooltip", N, "Hover or focus the \"Used in 3\" badge on bathroom-tiles.png (3 entries, no article).", {"frame":"media","ent":true,"tip":10}, "Used in 3 · Used in entries: 3 · Unused"),
st("List view: usage badge", N, "List view; mobile uses the card rows.", {"frame":"media","ent":true,"view":"list"}, "Used in 3 · Used in 7 · Unused"),
st("Detail panel: used in entries", N, "Click lime-plaster.jpg (2 articles, 5 entries). Right-hand panel; full screen on mobile.", {"frame":"media","ent":true,"panel":{"id":11}}, "Used in 2 articles · Used in entries · Events · Lime plaster workshop · Events · Heritage stone walk · Events · Winter open day · and 2 more"),
st("Delete: image used by entries", N, "Delete in the panel.", {"frame":"media","ent":true,"panel":{"id":11},"modal":{"k":"delEnt"}}, "Delete an image that's in use? · \"lime-plaster.jpg\" is used in 5 entries and 2 articles. Those entry fields will show \"This image is no longer in the library\", and the articles will show a broken image. This can't be undone. · Cancel · Delete image")
] } ] }
] ]
@@ -172,5 +208,7 @@ export const tables = [
['Type picker', 'A radio group. The locked state sets aria-disabled and the line "Can\'t change after saving" is read with the group.'], ['Type picker', 'A radio group. The locked state sets aria-disabled and the line "Can\'t change after saving" is read with the group.'],
['Counters', 'Character counters are polite live regions on pause, not on every key.'], ['Counters', 'Character counters are polite live regions on pause, not on every key.'],
['Contrast', 'Tokens already computed in foundations.md. Muted text is never placed on sand; selected tiles use --rc-on-sand for their description.'], ['Contrast', 'Tokens already computed in foundations.md. Muted text is never placed on sand; selected tiles use --rc-on-sand for their description.'],
['Touch', 'Controls are 44 px on mobile. The inspector, columns and API preview are bottom sheets.']] } ['Touch', 'Controls are 44 px on mobile. The inspector, columns and API preview are bottom sheets.']] },
...mfTables
] ]
+3
View File
@@ -104,3 +104,6 @@ Keys: a type key is 2 to 40 lowercase letters, digits and hyphens (chosen at cre
Schema changes with entries: Save opens the review ("Add 2 fields, change 1, remove 1"); Apply sends the PUT; schema_incompatible shows "Nothing was changed" and names the kind of change that likely caused it, never an entry. A type with entries cannot be deleted ("You can't delete Events yet"). Schema changes with entries: Save opens the review ("Add 2 fields, change 1, remove 1"); Apply sends the PUT; schema_incompatible shows "Nothing was changed" and names the kind of change that likely caused it, never an entry. A type with entries cannot be deleted ("You can't delete Events yet").
Entry rules, 422 except unique (409): required, type, min, max, options, unique, unknown_field. Messages are per type and drawn in the field-type gallery (group "Field types"). Entry rules, 422 except unique (409): required, type, min, max, options, unique, unknown_field. Messages are per type and drawn in the field-type gallery (group "Field types").
## Media field (pass 5)
Copy and states are in `media-field-changes.md` (sections 2 to 6). Entry rules for a media field: required 422 "Pick an image for Thumbnail."; type 422 "Thumbnail must be an image from the library."; min, max, options and unique do not apply. A required media field added to a type with entries is refused client side in the review ("Can't be applied") and by the server as 409 schema_incompatible. Image deleted while entries use it: the control shows "This image is no longer in the library"; saving is refused only when the field is required. HTTP statuses for the picker and the field use the table above (400, 401, 403, 404, 409, 413, 429, 500, network).
+1 -1
View File
@@ -36,7 +36,7 @@ setting does, so a client holding an old value gets a fresh 200. `Cache-Control`
Every generated file is a blob in `image.Storage` (local directory or S3) plus a row in Every generated file is a blob in `image.Storage` (local directory or S3) plus a row in
`image_variant_files` (variant, source stored name, cached stored name, content type, size, settings `image_variant_files` (variant, source stored name, cached stored name, content type, size, settings
fingerprint). The pair (variant, source) is unique. Concurrent first requests share one generation fingerprint). The pair (variant, source) is unique. Concurrent first requests share one generation
(`singleflight` keyed by variant, settings and source); different variants or different images are (a single-flight group keyed by variant, settings and source); different variants or different images are
generated in parallel. generated in parallel.
Only a stored name that has an image record can be a variant source, so generated files and orphan blobs Only a stored name that has an image record can be a variant source, so generated files and orphan blobs
+77
View File
@@ -0,0 +1,77 @@
# Privacy and personal data
This page is for operators: whoever runs a RenewCMS instance is the data controller for it under the GDPR. It lists what the software stores about people, where, for how long, and what it sends elsewhere, so you can fill in your record of processing (art. 30), write your privacy notice (art. 13) and answer requests from the people concerned. It describes the software, not your obligations; it is not legal advice.
## Who is concerned
- **Back-office users**: the owner and the admins they invite.
- **Invitees** who have not accepted yet.
- **People named in content**: authors, and anyone your editors write about or photograph.
- **Anyone who performs an audited action** (logging in, failing to log in, changing anything) has their IP address and browser recorded in the activity log.
Readers of your public site are not tracked by RenewCMS: the public routes set no cookie and log nothing in production.
## What is stored, and for how long
| Data | Where | Kept |
|---|---|---|
| Username, email, display name, role, bcrypt password hash | `users` table | Until the account is deleted (see [Gaps](#gaps)). |
| Verification and password-reset codes | `users` table, bcrypt-hashed | Verification: until the account is verified. Reset: one hour, then useless; cleared when used. |
| Unverified sign-ups | `users` table | Deleted automatically 7 days after their verification code expired. |
| Invites: invitee email, hashed code, inviter | `invites` table | Deleted automatically 30 days after they expired or were accepted. |
| Sessions | The `jwt` cookie in the user's browser, valid 24 hours | Logging out revokes the session on the server; the revocation (a random id and an expiry, nothing else) is deleted once the session would have expired anyway. |
| API keys: name, prefix, SHA-256 hash, creator, last use | `api_keys` table | Until revoked. A revoked key stays listed. |
| Activity log: who (user id and name, API key name, or the username typed at a failed login), what, when, IP address, browser (user agent, truncated to 255 characters) | `audit_events` table | Settings → Activity: 30, 90 (default), 365 days or forever, and an optional size cap. Cleaned up once a night, at 03:00 server time. |
| Authors: name, slug, bio, avatar, website, social links; the linked user's email is shown to admins | `authors` table | Until deleted. |
| Articles and custom entries | `articles`, `entries` tables | Deleted articles are soft-deleted: the row and its content stay in the database (see [Gaps](#gaps)). |
| Uploaded images | `UPLOAD_DIR` or the S3 bucket, plus the `images` table (file name, size, uploader) | Until deleted from the media library. Deleted images are soft-deleted in the table; the file itself is removed. |
### Photo metadata
Since this version, uploads are cleaned before they are stored. JPEG, PNG and WebP files lose their EXIF (GPS position, camera serial number, date), XMP, IPTC, comments and text chunks; only the orientation is kept, so rotated photos still display correctly. The pixels are not re-encoded. SVG files are stored as uploaded. **Images uploaded with an earlier version are not cleaned retroactively**: if they may carry GPS positions, download, clean and re-upload them, or merge them into a cleaned copy from the media library.
### Activity log retention
For security logs, the CNIL generally recommends keeping access logs between six months and a year. The default of 90 days is shorter; choose 365 days in Settings if that suits your purpose. Avoid "Forever": it keeps IP addresses indefinitely, which the storage-limitation principle rarely justifies.
## Cookies and browser storage
- `jwt`: the session cookie. HttpOnly, `SameSite=Lax`, `Secure` in production, 24 hours. Strictly necessary for the back office, so it needs no consent (ePrivacy art. 5(3); in France, Loi Informatique et Libertés art. 82).
- `localStorage` on the user's device holds interface choices only: language (`renewcms-language`), page sizes, open or collapsed panels, dismissed hints and columns. `sessionStorage` holds unsaved article drafts until the tab closes. None of it is sent to the server or to anyone else, and it needs no consent either.
RenewCMS sets no analytics, advertising or third-party cookie, so no consent banner is needed for the back office. Your public site may need one if *it* adds trackers.
## What leaves the server
| Destination | When | What |
|---|---|---|
| Your SMTP provider (`SMTP_HOST`) | Sign-up, invite, password reset | Recipient address, the message (with a one-time link). STARTTLS or implicit TLS is required for any non-loopback host unless you set `SMTP_ALLOW_INSECURE=true`. |
| Your S3 provider, if `STORAGE_DRIVER=s3` | Every upload and image read | The image files. |
| `UPDATE_FEED_URL` (default `https://git.floriansylvain.fr`) | Only when the owner clicks "Check for updates" or downloads one | The server's IP address and a standard HTTP request. No account or content data. |
The back office loads nothing from third parties: fonts, icons and scripts are served by RenewCMS itself, and the Content-Security-Policy forbids any other source. Pick EU-based SMTP and storage providers, or make sure transfer safeguards (art. 44 and following) cover them, and list them as processors.
## Security measures you can cite (art. 32)
- Passwords are hashed with bcrypt (cost 12). One-time codes are random UUIDs, stored hashed, single-use and short-lived. API keys are 256-bit random values stored as SHA-256 hashes.
- Login, password-reset and invite routes are rate-limited per client IP; failed logins are recorded as security events.
- Sessions are revocable: logout ends one session, a password reset ends all of them and revokes the user's API keys.
- Cross-site writes are refused, cookies are `SameSite=Lax`, and a strict Content-Security-Policy, `X-Frame-Options: DENY` and HSTS (in production) are sent.
- The server refuses to start with a short or example `JWT_SECRET`.
- Release binaries are signed (ed25519) and checked before a browser update is installed.
## Answering requests from the people concerned
- **Access and portability (art. 15 and 20)**: there is no self-service export yet. The data of a user is their row in `users`, their author profile, their API keys and the activity events where they are the actor; an owner can export the activity log as CSV from the Activity page and filter it by person.
- **Rectification (art. 16)**: users can change their display name and author profile themselves. Changing an email address currently needs a database edit.
- **Erasure (art. 17)**: an unverified account can cancel its own registration. Deleting a verified user has no button yet; see [Gaps](#gaps).
## Gaps
These are known and tracked; until they are fixed, handle them by hand.
- No way to delete a verified user or remove an admin from the interface.
- No self-service export or email change.
- Soft-deleted articles and images keep their rows indefinitely.
- The username typed at a failed login is stored as typed, so a password typed in the wrong field can end up in the activity log; clean such events by hand if it happens.
- Images uploaded before metadata stripping keep their metadata.
+4
View File
@@ -41,3 +41,7 @@ Each body lives in `docs/releases/<tag>.md`. Publish with `tea releases create -
| `v3.2.1-beta` | Paged media library and remembered page sizes | | `v3.2.1-beta` | Paged media library and remembered page sizes |
| `v3.3.0-beta` | Sites, authors and search and sharing | | `v3.3.0-beta` | Sites, authors and search and sharing |
| `v3.4.0-beta` | Custom content types | | `v3.4.0-beta` | Custom content types |
| `v3.4.1-beta` | Media field and security updates |
| `v3.4.2-beta` | Security and privacy hardening |
| `v3.5.0-beta` | Relation field |
| `v3.5.1-beta` | Relation picker fix |
+59
View File
@@ -0,0 +1,59 @@
This release adds a Media field type to custom content types, shows where each image is used, makes merging duplicate images safe against concurrent edits, and replaces or updates dependencies to close known security advisories.
## New
**Media field**
- A custom content type can now have a Media field that holds one image from the media library. The entry stores the image, not a copy, so the field always shows the current library image.
- A Media field has a label, a key and a required switch. It has no default, unique, minimum, maximum or choices, and its type cannot change after the first save.
- In the schema builder, Media is the seventh field type. Adding a required Media field to a type that already has entries is refused in the review step, because such a field cannot have a default.
- In the entry editor, the field shows a thumbnail with Change image and Remove buttons, opens the library picker on click or keyboard, and can upload a new image from the picker's Upload tab. A required field has no "No image" choice.
- When an image was deleted after an entry was saved, the entry keeps the link and the field shows "This image is no longer in the library". An optional field can still be saved, and a required one asks for a new image.
- The entry list gets a Thumbnail column and a thumbnail on mobile cards. It can be added from the Columns menu or shown as the first column.
**Image usage in the media library**
- Entries now count as uses of an image, together with articles, authors and sites. The usage badge, the Unused filter and the unused count all include them.
- Hovering or focusing a usage badge on a card shows how many articles and entries use the image.
- The image detail panel has a "Used in entries" section listing each entry with its content type and title, as a link to the entry.
- Deleting, bulk deleting and merging images now warn with counts of uses, and say what happens to entries that point at the image. Deleting a used image is still allowed and leaves the entries' data untouched.
## Improvements and fixes
- Merging duplicate images is now all-or-nothing. If any step fails, articles, entries and the library are left exactly as they were.
- Stored files are removed only after the merge is committed. A file that cannot be removed afterwards is logged and does not undo the merge.
- A merge no longer overwrites an article or entry edited while it was running. Articles and entries are re-read before they are rewritten, and ones deleted in the meantime are skipped.
- A duplicate purge scans entries once instead of once per group, commits one group at a time, so one failing group no longer undoes the others, and stops cleanly when the request is cancelled.
- Sessions now expire. New sign-in tokens carry a 24 hour expiry, matching the cookie. Sessions created before this release keep working until you sign out.
## API
- Changed: an entry response now has eight keys, the seven existing ones plus `media`. It is an object keyed by Media field key, `{}` when the type has no Media field. Each value is `{ "id", "filename", "width", "height", "size", "thumbnail_url" }` for an existing image, or `{ "id", "missing": true }` when the image is gone. `data` keeps the image id, or `null`, as the field's value. It is on `POST` (201), `PUT` (200), `GET` one and every item of the list.
- `POST /v1/content-type` and `PUT /v1/content-type/{key}` accept fields of type `media`. A Media field with `unique`, `default`, `min`, `max` or `options` answers `422` `invalid_field`.
- `POST` and `PUT` on `/v1/content-type/{key}/entry` check that a new or changed image id exists in the library, otherwise `422` `invalid_entry: <key>: type`. A required Media field that is empty, or whose stored image is gone, answers `422` `invalid_entry: <key>: required`.
- Changed: `used_in` on `GET /v1/media/` and `GET /v1/media/{id}` now includes entries, and `filter=unused` and `counts.unused` treat an image used by an entry as used.
- Changed: `GET /v1/media/{id}/usage` also returns items of type `entry`, with `id`, `fields`, `content_type_key`, `content_type_name` and `first_field` (`key`, `type` and the raw stored `value`). They follow the article, author and site items, ordered by content type name and then id. Existing item shapes are unchanged.
- Merging duplicates, by hand or through the purge, now repoints entry Media values to the kept image.
## Under the hood
- Seven direct and twelve indirect Go modules are gone. Sign-in tokens, SMTP delivery, `.env` loading, CORS, request logging and the image-variant single-flight group are now small in-repo implementations on the standard library, with tests. The removed modules are `jwtauth`, `lestrrat-go/jwx`, `gomail`, `httplog`, `godotenv`, `go-chi/cors` and `x/sync/singleflight`, and the dependencies they pulled in.
- Every remaining Go module is updated, and the Go toolchain moves to 1.27.3. `govulncheck` reports no vulnerability reachable from the code, where it found thirteen in the standard library and several in `golang.org/x/net` and `chi` before.
- Web dependencies are updated, which clears all but three dev-only audit findings. `npm-run-all2` is removed, and `bun run build` now runs the type check and then the build.
- A transaction port in the domain lets use cases commit several writes together, with a GORM adapter that works on SQLite, MySQL, MariaDB and PostgreSQL.
- Feature specs and QA procedures for each slice are in `features/`.
## Upgrading
- Replace the binary, or pull the new image. Back up the database first as usual.
- No schema change and no new environment variable. A Media field is stored in the existing content type and entry tables.
- `.env` files no longer expand `$VARIABLES` and do not support multi-line values. A malformed line now makes the file ignored, and the server logs the line number. Real environment variables still take precedence.
- If you build the image yourself, the Go base image is now `golang:1.27.3-alpine`.
- SMTP now fails with a clear error when a login is set but the server offers no authentication, where it used to continue without logging in. Credentials are never sent in clear text to a host other than localhost.
- `CORS_ALLOWED_ORIGINS` also accepts one `*` per entry, for example `https://*.preview.example.com`, and a lone `*` for any origin. Credentials are never allowed cross-origin.
## Known limitations
- A Media field holds one image. Galleries are not supported.
- Entries still cannot be filtered or searched by their field values, and there are no relations between types.
- The editor preview of a Media field uses the original image, with no variant choice.
+39
View File
@@ -0,0 +1,39 @@
This release hardens sign-in, sessions and mail against common attacks, and reduces the personal data RenewCMS keeps or shares, following a security, GDPR and CNIL review.
## Improvements and fixes
- Signing out now ends the session on the server. A copied session cookie stops working at once, while the same user's other sessions keep working.
- The limit on login, password reset and invitation attempts now applies per client address. Before, opening a new connection reset the count, so the limit could be bypassed.
- Requests that change data and come from another website are refused, and the session cookie is now `SameSite=Lax`. A malicious page can no longer act on behalf of a signed-in user.
- A session made stale by a password reset can no longer read draft articles.
- Signing in with an unknown username now takes as long as signing in with a wrong password, so response times no longer reveal which usernames exist.
- A password longer than 72 bytes is refused with a clear message, where it used to cause a server error.
- Uploaded JPEG, PNG and WebP images lose their hidden metadata (GPS position, camera serial number, dates, comments) before they are stored. Pixels and colour profiles are untouched, and rotated photos keep their orientation.
- The back office no longer loads its fonts from Google. The fonts ship with RenewCMS, so no visitor IP address is sent to a third party.
- Unverified sign-ups are deleted 7 days after their verification code expired, and invitations 30 days after they expired or were accepted.
- Exported activity CSV files also neutralise cells starting with a tab or a carriage return, which spreadsheets could otherwise treat as formulas.
## API
- Changed: `POST`, `PUT`, `PATCH` and `DELETE` requests sent by a browser from another origin without an `Authorization` header answer `403` "Cross-origin requests are not allowed." Scripts on other origins must send their API key.
- Changed: `POST /v1/auth/logout` revokes the presented session. It answers `500` only when the revocation cannot be stored, and clears the cookie either way.
- `POST /v1/auth/register`, `POST /v1/auth/password-reset/confirm` and `POST /v1/auth/invite/accept` answer `400` "The password must be 72 bytes or fewer." for longer passwords.
## Under the hood
- A new `docs/privacy.md` lists the personal data RenewCMS stores, how long it is kept, the cookies, what leaves the server and how to answer access or erasure requests. It is meant to help operators with their record of processing and privacy notice.
- Cross-origin protection uses the Go standard library, so no dependency was added.
- New feature specs and tests cover the hardening, in `features/security_privacy_hardening.feature`.
## Upgrading
- Replace the binary, or pull the new image. Back up the database first as usual.
- A new `revoked_sessions` table is created automatically at startup.
- The server now refuses to start when `JWT_SECRET` is shorter than 32 bytes or is still an example value. Generate one with `openssl rand -hex 32`. Changing it signs everyone out.
- Mail to an SMTP server on another host now requires encryption (STARTTLS, or port 465). If your relay offers neither, set the new `SMTP_ALLOW_INSECURE=true`. Credentials are still never sent unencrypted.
- Sessions created before v3.4.1-beta, which carry no expiry, are refused. Those users sign in once more.
## Known limitations
- Images uploaded before this release keep their metadata. Re-upload them if they may contain GPS positions.
- Verified users still cannot be deleted from the interface, and there is no self-service data export yet.
+40
View File
@@ -0,0 +1,40 @@
This release adds a Relation field to custom content types, so an entry can point at entries of another type.
## New
**Relation field**
- A content type can now have a Relation field that links to another content type. Three kinds are available: one to one (a target can be used by only one entry), one to many (one target per entry) and many to many (up to 50 targets per entry).
- Entries are linked through a searchable picker in the entry form. Chosen targets appear as chips labelled with the first field of the target entry, or "Entry N" when that field is empty.
- Entry lists and cards show the linked entries of each relation column.
- When a linked entry is deleted afterwards, the relation is shown as missing instead of breaking the page. A required relation with a missing target must be fixed before the entry can be saved.
- The schema builder previews the inverse side of a relation, and the schema review dialog explains the impact of adding or removing one.
## Improvements and fixes
- Deleting a content type that another type points at is refused, and the delete dialog tells you which types depend on it.
- Adding a required relation to a type that already has entries is refused with the usual schema incompatibility message.
- The right side panel of the article editor no longer overflows vertically on short screens.
- The web app is split into smaller chunks, so the first page load transfers less code.
## API
- Changed: every entry answer (`POST`, `PUT` and `GET` of one entry, and each item of a list) carries a top-level `relations` object keyed by relation field key. Each value holds `id`, `content_type` and `first_field` for an existing target, or `id` and `missing: true` for a deleted one. Many to many fields return an array.
- `GET /v1/content-type/{key}/entry` accepts `q`, a text search over the entries of the type, applied before pagination. `total` reflects the filtered count.
- `POST /v1/content-type` and `PUT /v1/content-type/{key}` accept `type: "relation"` fields with `relation: {"content_type", "kind"}`. A bad definition answers `422` `invalid_field`.
- Entry writes answer `422` `invalid_entry: <key>: required` or `invalid_entry: <key>: type`, and `409` `invalid_entry: <key>: unique` for a one to one target already taken.
- `DELETE /v1/content-type/{key}` answers `409` `content_type_referenced` while another type has a relation to it.
## Under the hood
- New feature specs and tests cover the backend and the web app, in `features/relation_field_type.feature` and `features/relation_field_spa.feature`.
- Vendor chunk splitting is configured in `web/vite/vendorChunks.ts` and covered by a spec.
## Upgrading
- Replace the binary, or pull the new image. Back up the database first as usual.
- No schema migration and no new environment variable. Existing content types and entries are unchanged.
## Known limitations
- Relation search filters entries in memory, so it is meant for types with a moderate number of entries.
- The inverse side of a relation is only shown in the builder preview. The target type's form, list and API do not list the entries pointing at it.
+9
View File
@@ -0,0 +1,9 @@
This release fixes the Relation field picker, which could not load any entries.
## Improvements and fixes
- Choosing a target for a Relation field no longer fails with "Couldn't load" and a `400` error. The picker asked for pages of 10 entries, a size the entry list refuses, and now asks for 25.
## Upgrading
- Replace the binary, or pull the new image. No schema migration and no new environment variable.
+2
View File
@@ -358,6 +358,8 @@ Feature: The back-office keeps an append-only activity log that owners can read
| target | +1+1 | '+1+1 | | target | +1+1 | '+1+1 |
| target | -2 | '-2 | | target | -2 | '-2 |
| actor | @SUM(A1) | '@SUM(A1) | | actor | @SUM(A1) | '@SUM(A1) |
| target | \t=cmd | '\t=cmd |
| target | \r=cmd | '\r=cmd |
| target | Spring release | Spring release | | target | Spring release | Spring release |
| target | a=b | a=b | | target | a=b | a=b |
+2 -2
View File
@@ -39,7 +39,7 @@ Feature: Owners and admins define custom content types, and users manage entries
And a field response has exactly the keys key, label, type, required, unique, default, min, max, And a field response has exactly the keys key, label, type, required, unique, default, min, max,
options, with null for an unset default, min and max and [] for no options options, with null for an unset default, min and max and [] for no options
And an entry response has exactly the keys id, content_type, data, created_by, updated_by, And an entry response has exactly the keys id, content_type, data, created_by, updated_by,
created_at, updated_at, where content_type is the type's key created_at, updated_at, media, where content_type is the type's key
And errors are plain text from http.Error, and the new apperr strings are And errors are plain text from http.Error, and the new apperr strings are
content_type_not_found, content_type_key_taken, content_type_has_entries, content_type_not_found, content_type_key_taken, content_type_has_entries,
invalid_content_type_key, invalid_field, schema_incompatible, entry_not_found and invalid_entry invalid_content_type_key, invalid_field, schema_incompatible, entry_not_found and invalid_entry
@@ -201,7 +201,7 @@ Feature: Owners and admins define custom content types, and users manage entries
When the client sends POST /v1/content-type/recipe/entry with body When the client sends POST /v1/content-type/recipe/entry with body
{"data": {"title": "Pad thai", "difficulty": "easy"}} {"data": {"title": "Pad thai", "difficulty": "easy"}}
Then the response status is 201 Then the response status is 201
And the body has exactly the keys id, content_type, data, created_by, updated_by, created_at, updated_at And the body has exactly the keys id, content_type, data, created_by, updated_by, created_at, updated_at, media
And content_type is "recipe", created_by and updated_by are 2 And content_type is "recipe", created_by and updated_by are 2
And data is {"title": "Pad thai", "difficulty": "easy", "servings": 4, "vegetarian": false} And data is {"title": "Pad thai", "difficulty": "easy", "servings": 4, "vegetarian": false}
And data has no "published_on" and no "notes" key And data has no "published_on" and no "notes" key
+6 -4
View File
@@ -53,12 +53,14 @@ Feature: Password and code hashing go through a domain Hasher interface
Then the result is the error user.ErrInvalidCredentials Then the result is the error user.ErrInvalidCredentials
And errors.Is(err, user.ErrInvalidCredentials) is true And errors.Is(err, user.ErrInvalidCredentials) is true
Scenario: Authenticating an unknown username never calls the hasher Scenario: Authenticating an unknown username spends the same hashing work as a wrong password
Given a user repository with no user "bob" Given a user repository with no user "bob"
When AuthenticateUserUseCase.Authenticate is called with username "bob" and password When AuthenticateUserUseCase.Authenticate is called twice with username "bob" and password
"hunter2example" "hunter2example"
Then the result is the error user.ErrUserNotFound Then each result is the error user.ErrUserNotFound
And the hasher's Compare is never called And the hasher's Compare is called once per attempt, against a decoy hash of a random value
that no password can match, so response time does not reveal whether a username exists
And the decoy is hashed once and reused for every later unknown username
Scenario Outline: Login over HTTP still can't distinguish a bad password from an unknown username Scenario Outline: Login over HTTP still can't distinguish a bad password from an unknown username
Given a user repository containing a user "alice" with stored password "hashed:hunter2example" Given a user repository containing a user "alice" with stored password "hashed:hunter2example"
+4 -3
View File
@@ -29,9 +29,10 @@ Package: `test` (black-box, alongside the existing `article_test.go` / `user_tes
assert the returned user matches and `err` is `nil`. assert the returned user matches and `err` is `nil`.
- `Authenticate("alice", "wrongpassword12")` with `fakeHasher.Compare` returning an error - `Authenticate("alice", "wrongpassword12")` with `fakeHasher.Compare` returning an error
→ assert `errors.Is(err, user.ErrInvalidCredentials)` is `true`. → assert `errors.Is(err, user.ErrInvalidCredentials)` is `true`.
- `Authenticate("bob", "hunter2example")` with no "bob" in the repo → assert - `Authenticate("bob", "hunter2example")` twice with no "bob" in the repo → assert
`errors.Is(err, user.ErrUserNotFound)` is `true` and `fakeHasher`'s `Compare` was never `errors.Is(err, user.ErrUserNotFound)` is `true` each time, that `fakeHasher`'s `Compare`
invoked (record a `compareCalled` flag). ran once per attempt (against the decoy hash), and that `Hash` ran exactly once overall
(the decoy is computed lazily and reused).
## HTTP checks (real BcryptHasher, in-memory fake repo, mirroring api/router.go) ## HTTP checks (real BcryptHasher, in-memory fake repo, mirroring api/router.go)
8. Call `validator.InitValidator()`. 8. Call `validator.InitValidator()`.
@@ -16,7 +16,8 @@ Feature: Login and password-reset requests are rate-limited per client IP
(github.com/go-chi/chi/v5/middleware) runs first and rewrites r.RemoteAddr from (github.com/go-chi/chi/v5/middleware) runs first and rewrites r.RemoteAddr from
X-Forwarded-For/X-Real-IP when present (matching the nginx reverse proxy setup in X-Forwarded-For/X-Real-IP when present (matching the nginx reverse proxy setup in
docs/deployment.md that already sets X-Forwarded-For), falling back to the raw RemoteAddr docs/deployment.md that already sets X-Forwarded-For), falling back to the raw RemoteAddr
otherwise; RateLimiter keys its counters on r.RemoteAddr otherwise; RateLimiter keys its counters on the host portion of r.RemoteAddr (the source
port is ignored, so opening a new connection never yields a fresh counter)
And RateLimiter(maxAttempts int, window time.Duration) func(http.Handler) http.Handler keeps And RateLimiter(maxAttempts int, window time.Duration) func(http.Handler) http.Handler keeps
an in-memory, mutex-guarded fixed-window counter per (route, client IP) pair: the first an in-memory, mutex-guarded fixed-window counter per (route, client IP) pair: the first
request from a client opens a window starting now; each subsequent request from the same request from a client opens a window starting now; each subsequent request from the same
+296
View File
@@ -0,0 +1,296 @@
Feature: Media field usage in the Media library
As an owner, admin or verified user managing the media library
I want to see which entries use an image and be warned before deleting it
So that I know what an image is used for and what a delete will break
Background:
Given the SPA calls the API with relative URLs under /v1 and the "jwt" HttpOnly cookie
And API errors are plain text
And this slice changes only web/ (and web/visual); the backend of features/media_field_type.feature is done and not touched
And the design is docs/design/media-field-changes.md section 3.8 and section 4, with the board group "11 Media library: usage" (4 states) of "RenewCMS Screens Schema.dc.html", which draws MediaFrame.dc.html with entries counted as uses
And GET /v1/media/ items carry "used_in", which counts articles, authors, sites and entries together, and no split
And GET /v1/media/{id}/usage answers an array ordered articles, authors, sites, then entries by content type name then entry id, with no total and no "first few" wrapper
And an article item is {"type":"article","id","title","published","fields"}
And an entry item is {"type":"entry","id","fields","content_type_key","content_type_name","first_field":{"key","type","value"}} with no title and no published, and first_field absent when the type has no first field
And the SPA keeps the first 3 entry items, counts the rest, and derives the entry title from first_field with the title rules of the entry list (see "Entry title in the usage lists")
And deleting a used image stays allowed; entries keep the id and show "This image is no longer in the library"
And the usage badge, panel and dialog never branch on the role; the Media page is the same for every user who reaches it
And sentence case, "image" and never "asset", buttons are verbs
And every string goes through t() and has a French entry in i18n/messages.ts
And a copy tagged "(proposed copy)" is not in the design and is the coder's single point of change
And decisions D1 to D12 of this slice are listed in the QA procedure header and in the conversation
And out of scope: filtering the library by media-field use, the read-only view of a custom type, any change to the Go API
Scenario Outline: The label of the usage badge
Given an image with used_in <used_in>
Then the badge reads "<badge>"
Examples:
| used_in | badge |
| 0 | Unused |
| 1 | Used in 1 |
| 3 | Used in 3 |
| 7 | Used in 7 |
Scenario: The badge counts articles and entries together
Given bathroom-tiles.png has used_in 3 (0 articles, 3 entries) and lime-plaster.jpg has used_in 7 (2 articles, 5 entries)
Then the grid card, the list row and the mobile card of bathroom-tiles.png read "Used in 3" and those of lime-plaster.jpg read "Used in 7"
And the badge is the outline kind of MediaBadge, without an icon, as today
Scenario: Tooltip for entries only (design "Grid: usage badge tooltip")
Given bathroom-tiles.png has 0 articles and 3 entries, and a desktop viewport
When the pointer rests on the badge "Used in 3"
Then GET /v1/media/10/usage is sent once
And a tooltip (--ui-bg-inverted, --ui-text-inverted, 12/18, 6 px 8 px padding, below the badge, left aligned) reads on one line "Used in entries: 3"
Scenario: Tooltip for articles and entries
Given lime-plaster.jpg has 2 articles and 5 entries, and a desktop viewport
When the pointer rests on the badge "Used in 7"
Then the tooltip reads "Used in articles: 2" on the first line and "Used in entries: 5" on the second
Scenario: Tooltip for articles only
Given north-wall.jpg has 2 articles and 0 entries, and a desktop viewport
When the pointer rests on the badge "Used in 2"
Then the tooltip reads "Used in articles: 2" and no "Used in entries" line shows
Scenario: Tooltip opens on keyboard focus
Given a desktop viewport
When the keyboard focus reaches the card (grid) of an image that is used
Then the same tooltip opens, and it closes on blur or Escape without closing anything else
And the focus ring of the card is unchanged
Scenario: The usage is fetched once per image
Given the tooltip of image 10 was opened once
When the user hovers it again, or opens its detail panel
Then no second GET /v1/media/10/usage is sent while the list is not reloaded
And a reload of the list (search, filter, sort, page, retry) clears the cached usage
Scenario: The tooltip waits for the usage
Given GET /v1/media/10/usage has not answered
Then no tooltip shows and the badge keeps its label
When it answers and the pointer or focus is still on the badge
Then the tooltip opens
Scenario Outline: The tooltip never shows without a useful split
Given the pointer rests on the badge of an image and GET /v1/media/{id}/usage <outcome>
Then no tooltip shows and nothing else changes
Examples:
| outcome |
| answers 500 |
| fails on the network |
| answers 404 |
| answers only authors and sites |
Scenario: No tooltip on mobile
Given a 390 px viewport
Then no tooltip opens on tap and the badge is read inside the card as "Used in 3"
Scenario: No tooltip on an unused image
Given an image with used_in 0
Then the badge "Unused" has no tooltip and no usage request is sent for it
Scenario Outline: The accessible name of a card (proposed copy)
Given an image "north-wall.jpg", 3.9 MB, with used_in <used_in>
Then the card button is named "<name>"
Examples:
| used_in | name |
| 0 | north-wall.jpg, 3.9 MB, unused |
| 1 | north-wall.jpg, 3.9 MB, used in 1 place |
| 7 | north-wall.jpg, 3.9 MB, used in 7 places |
Scenario: The list table column (design "List view: usage badge", written spec 3.8)
Given a desktop viewport and the list view
Then the "Used in" column of a used image is the underlined button "Used in 3" that opens the detail panel, as the "N articles" button does today
And an image with used_in 0 shows the "Unused" badge
And the mobile card shows the "Used in 3" badge and the existing meta line
Scenario: Panel for an image used by articles and entries (design "Detail panel: used in entries")
Given lime-plaster.jpg has 2 articles and 5 entries, whose first three entries are Events "Lime plaster workshop", Events "Heritage stone walk" and Events "Winter open day"
When the user opens its panel
Then the preview is 16:10 on desktop and 16:3.6 on mobile only when usage holds at least one entry, and 16:10 and 4:3 otherwise
And the section "Used in 2 articles" lists the two articles with title, Online or Draft and the arrow-up-right icon, as today, with the note "Counted from the text of your articles each time you open this page."
And below it the section "Used in entries" (600 14/22, 8 px gap) holds a bordered list of 3 rows, then the row "and 2 more" in the muted colour, with a muted top border and no link
And each entry row is 36 px high on desktop and 48 px on mobile and holds, left to right, the content type name in 12 px muted (52 px wide, one line, ellipsis), the entry title as a link in weight 500 underlined (one line, ellipsis) and the arrow-up-right icon (14 px, muted)
And the link of a row goes to /content/events/<id> in the same tab
Scenario Outline: Counts in the "Used in entries" section
Given an image whose usage holds <entries> entry items
Then the section shows <rows> rows and <more>
Examples:
| entries | rows | more |
| 1 | 1 | no "and N more" row |
| 3 | 3 | no "and N more" row |
| 4 | 3 | the row "and 1 more" |
| 5 | 3 | the row "and 2 more" |
| 120 | 3 | the row "and 117 more" |
Scenario: Entries only, no article
Given bathroom-tiles.png has 3 entries and 0 articles
When the user opens its panel
Then the articles heading reads "Not used in any article"
And the line under it reads "No article shows it." and never "This image is safe to delete."
And the section "Used in entries" follows
Scenario: Articles only
Given north-wall.jpg has 2 articles and 0 entries
Then the panel is unchanged from before this slice and shows no "Used in entries" section
Scenario: Nothing uses the image
Given window-frame.jpg has used_in 0
Then the panel reads "Not used in any article" and "This image is safe to delete. No article shows it."
And no usage request is sent
Scenario: Authors and sites only (decision D7)
Given an image with used_in 2 and a usage that holds one author and one site
Then the articles heading reads "Not used in any article"
And the line reads "No article shows it." and no "safe to delete" claim is made
And no authors or sites are listed
Scenario: The articles heading counts articles only
Given lime-plaster.jpg has used_in 7 (2 articles, 5 entries)
Then the heading reads "Used in 2 articles" and never "Used in 7 articles"
Scenario: Entry link keyboard and focus
Given the panel of lime-plaster.jpg is open
Then Tab reaches the articles links, then the entry links, in reading order
And an entry link has the 2 px --ui-primary focus ring with a 2 px offset
And "and 2 more" is not a stop
Scenario: Usage loading in the panel (decision D6)
Given GET /v1/media/11/usage has not answered
Then after 150 ms a skeleton of three rows shows under the heading "Used in" (proposed copy)
And before 150 ms nothing shows in the section
And Copy URL, Rename and Delete stay enabled
When it answers
Then the real sections replace the skeleton
Scenario Outline: Usage failure in the panel (decision D5)
Given the panel of an image with used_in 7 is opened
When GET /v1/media/{id}/usage <outcome>
Then <result>
Examples:
| outcome | result |
| answers 500 | the section reads "Couldn't load where this image is used." (proposed copy) with the ghost button "Try again", and Delete stays enabled |
| fails on the network | the same |
| answers 429 | the same |
| answers 404 | the existing gone flow: the panel closes and "That image no longer exists" shows |
| answers 401 | the global redirect, no local copy |
Scenario: Try again in the panel
Given the usage failure is shown
When the user activates "Try again"
Then only GET /v1/media/{id}/usage is sent again and the sections replace the message
Scenario: Switching images while the usage is loading
Given the panel of image 10 is waiting for its usage
When the user opens image 11
Then the answer of image 10 is ignored and the panel shows only image 11 data
Scenario Outline: Entry title from first_field
Given an entry item with id 42 and first_field {"key":"title","type":"<type>","value":<value>}
Then the row title reads "<title>"
Examples:
| type | value | title |
| text | "Lime plaster workshop" | Lime plaster workshop |
| text | "" | Entry 42 |
| text | null | Entry 42 |
| richtext | "## Heritage walk\n\nMeet at 9" | the first line as richTextFirstLine gives it (not the Markdown marks of the whole body) |
| richtext | "" | Entry 42 |
| number | 1500 | 1,500 (as the entry list formats a number) |
| number | 0 | 0 |
| boolean | true | Yes |
| boolean | false | No |
| date | "2026-11-21" | the entry list date format of 2026-11-21 |
| select | "Workshop" | Workshop |
| media | 7 | Entry 42 |
| media | null | Entry 42 |
Scenario: first_field is absent or unknown
Given an entry item with id 42 and no first_field, or a first_field of an unknown type
Then the row title reads "Entry 42" for no first_field and the String of the value for an unknown type, as describeCell does for the default case
Scenario: Long titles and long type names (decision D4)
Given an entry title of 120 characters and the type name "Press mentions and partner coverage"
Then both stay on one line with an ellipsis, the row height does not change, the title link keeps the full title as its accessible name and a native title attribute, and "and N more" is unaffected
Scenario: The order of the three rows
Given the API returns entries ordered by content type name then entry id
Then the three kept rows keep that order and the SPA does not sort again
Scenario: Delete an image used by entries and articles (design "Delete: image used by entries")
Given lime-plaster.jpg has 2 articles and 5 entries and the user activates Delete in its panel
Then the confirm dialog (ConfirmDialog, tone danger) titled "Delete an image that's in use?" opens
And its description reads "\"lime-plaster.jpg\" is used in 5 entries and 2 articles. Those entry fields will show \"This image is no longer in the library\", and the articles will show a broken image. This can't be undone."
And the body holds, in this order, the bordered "Used in entries" list (heading "Used in entries", 3 rows, then "and 2 more") and the bordered list of the 2 articles with title and Online or Draft
And the buttons are "Cancel" and the destructive "Delete image"
And the entry rows show the type name and the title and are not links in the dialog (decision D10)
Scenario Outline: The wording by what uses the image
Given an image "lime-plaster.jpg" with <articles> articles and <entries> entries in its loaded usage
Then the title is "<title>"
And the description reads <description>
Examples:
| articles | entries | title | description |
| 2 | 5 | Delete an image that's in use? | "lime-plaster.jpg" is used in 5 entries and 2 articles. Those entry fields will show "This image is no longer in the library", and the articles will show a broken image. This can't be undone. |
| 1 | 1 | Delete an image that's in use? | "lime-plaster.jpg" is used in 1 entry and 1 article. Those entry fields will show "This image is no longer in the library", and the articles will show a broken image. This can't be undone. |
| 2 | 0 | Delete an image that's in use? | "lime-plaster.jpg" is used in 2 articles. If you delete it, they will show a broken image. This can't be undone. |
| 0 | 3 | Delete an image that's in use? | "lime-plaster.jpg" is used in 3 entries. Those entry fields will show "This image is no longer in the library". This can't be undone. (proposed copy) |
| 0 | 0 | Delete this image? | "lime-plaster.jpg" will be deleted from your library. No article uses it. This can't be undone. (used_in is 0) |
Scenario: Delete an unused image
Given window-frame.jpg has used_in 0
Then the dialog is titled "Delete this image?" with the unchanged copy, no lists and no usage request
Scenario: Delete an image used only by authors or sites
Given used_in 2 and a usage with no article and no entry
Then the existing in-use title shows with the generic fallback description of the next scenario
Scenario: The usage is not ready when the dialog opens (decision D6)
Given the user activates Delete before GET /v1/media/{id}/usage answered, or after it failed
Then the dialog is titled "Delete an image that's in use?" because used_in is above 0
And the description reads "\"lime-plaster.jpg\" is in use. Articles will show a broken image and entry fields will show \"This image is no longer in the library\". This can't be undone." (proposed copy)
And no lists show, "Delete image" is enabled, and when the usage answers while the dialog is open the dialog switches to the full copy and lists without moving the focus
Scenario: Confirm and results
Given the delete dialog is open
When the user activates "Delete image"
Then DELETE /v1/media/<id> is sent and the existing in-progress, failed, done and 404 states run unchanged
And on 204 the toast "Image deleted" / "\"lime-plaster.jpg\" is gone from your library." shows and the focus moves to the next item
Scenario: Cancel and Escape
When the user activates "Cancel" or presses Esc
Then nothing is deleted and the focus returns to the Delete button of the panel
Scenario: The variants note is kept
Given an image with cached variants and used by entries
Then the existing variant removal note still shows under the lists
Scenario: Mobile dialog
Given a 390 px viewport
Then the dialog is a bottom sheet, the entry rows are 48 px high and the buttons are 44 px high
Scenario: Bulk delete counts uses, not articles (proposed copy)
Given 3 images are selected, 2 of them used for 7 places in total (articles and entries)
Then each row keeps its badge "Used in N" or "Unused"
And the description counts "7 places" in the sentence where it said "7 articles" and reads "which will show a broken image or a missing-image notice." instead of "which will show a broken image."
And no usage request is sent for the bulk dialog
Scenario: Merge counts uses, not articles (proposed copy)
Given a merge group whose other copies have used_in 5 and 2
Then the dialog says "7 places will be updated" and "Kept · used in N places now"
And the toast after the merge keeps "N copies merged. M articles updated." from articles_updated
Scenario: Accessibility of the usage UI
Then the tooltip is exposed with aria-describedby on its trigger and uses role "tooltip"
And the entry title link is named "<title>, <content type name>" (proposed)
And "and 2 more" is plain text read in order
And the arrow-up-right icon is aria-hidden
And a skeleton or error line in the panel is inside the section so a screen reader reads it after the heading
And the delete dialog moves focus to "Cancel" as it does today, and its lists are read after the description
And mobile targets are 44 px, with rows of 48 px, and there is no hover on mobile
+101
View File
@@ -0,0 +1,101 @@
# QA: Media field usage in the Media library (slice C)
Runner: Vitest + Vue Test Utils (`task test:web`). No Go test and no Go change: the usage API is covered by features/media_field_type.qa.md. Kit: extend the Media view test kit with
- the library list (`GET /v1/media/?page=&size=&q=&filter=` with `items`, `total`, `counts`);
- `GET /v1/media/{id}/usage` fixtures:
- image 10 `bathroom-tiles.png`: 3 entries (Events), `used_in` 3;
- image 11 `lime-plaster.jpg`: 2 articles ("Open day at the workshop" online, "Restoring lime plaster" draft) plus 5 Events entries (first three: first_field text "Lime plaster workshop", "Heritage stone walk", "Winter open day"), `used_in` 7;
- image 1 `north-wall.jpg`: 2 articles, `used_in` 2;
- image 8 `window-frame.jpg`: `used_in` 0;
- an author-and-site-only image, `used_in` 2;
- entry items of every `first_field.type`, plus items with no `first_field`;
- failures: 500, network, 429, 404, 401.
Pin the time zone; never freeze the system date. No state of this slice depends on the clock.
Decisions accepted by the user (all as the feature draft assumes):
- D1 split source for the tooltip: lazy `/usage` fetch, SPA-only.
- D2 wording of the card name and the table column: "used in N places", underlined "Used in N" button.
- D3 title derivation: reuse `describeCell` and `plainCellText`.
- D4 truncation: one line, ellipsis, native title.
- D5 usage failure: inline message with "Try again" in the panel, silent tooltip.
- D6 usage loading: skeleton after 150 ms, delete dialog opens at once with a generic description.
- D7 authors and sites in the usage: filtered out, heading counts articles only.
- D8 bulk delete: "N places".
- D9 merge: "N places".
- D10 entry rows in the delete dialog are not links.
- D11 mobile panel as drawn.
- D12 visual gate setup.
## Automated
Pure logic (lib/__tests__, it.each over the feature's Examples):
1. `splitUsage(items)`: articles are those with `type === 'article'`, entries those with `type === 'entry'`, authors and sites are counted by neither. Entry rows keep API order, the first 3 are kept, `more` is the rest (0, 1, 2, 117). An absent array gives zeros.
2. `usageEntryTitle(item)`: the table "Entry title from first_field" for text, richtext (empty and Markdown), number (0 and 1500), boolean, date, select, media and null, empty string, absent first_field and an unknown type (falls to the default case of `describeCell`). It reuses `describeCell` and `plainCellText`; no second title rule exists. `entryTitle` itself is unchanged and its existing specs pass untouched.
3. Wording helpers: pluralEntries ("1 entry", "5 entries"), usage description by case (articles+entries, singular forms, articles only unchanged, entries only, usage unavailable fallback), `usedInLabel` for the card name ("used in 1 place", "used in 7 places", "unused").
4. Tooltip lines: entries only gives one line, both gives articles first, articles only gives one line, authors or sites only gives none.
MediaCardBadges, MediaTable, MediaGrid, MediaCardList (components/__tests__):
5. Badge label for used_in 0, 1, 3, 7. Outline kind, no icon. Same label in the grid card, the list row (underlined button in the table, badge in the mobile card) and the mobile card.
6. Tooltip: hover on the badge (`pointerenter`) fetches `/usage` once and opens with the right lines for the three splits; focus on the grid card opens it; Escape and blur close it without closing the panel; no fetch for `used_in` 0; no tooltip on mobile (viewport helper 390); nothing opens while the request is pending, and it opens on answer if the pointer is still there; failures (500, network, 404, authors-only) leave no tooltip; the usage is cached per image and cleared on reload of the list.
7. Card `aria-label`: the three names of the feature, replacing the "used in 2 articles" assertions in the existing specs; update those specs and change nothing else in them.
8. Table: the "Used in" cell is the underlined button "Used in N" (`data-testid="media-used-in"` kept) that opens the panel; "Unused" badge at 0.
MediaDetailPanel (components/__tests__/MediaDetailPanel.spec.ts, views/__tests__/MediaView*.spec.ts):
9. Articles and entries: heading "Used in 2 articles" built from the articles of the usage, not from `used_in`; article rows unchanged; "Used in entries" heading and 3 rows with type name, title link to `/content/<key>/<id>` and the arrow icon; "and 2 more" as plain text; the counts table (1, 3, 4, 5, 120 entries); row heights 36 px (desktop) and 48 px (mobile) as classes.
10. Entries only: heading "Not used in any article" with "No article shows it."; articles only: no entries section and the panel as before; unused: "safe to delete" line and no `/usage` request; authors and sites only: "No article shows it." and no list.
11. Preview aspect: 16:10 desktop and 4:3 mobile without entries, 16:6 desktop and 16:3.6 mobile with entries (classes, after the usage answers).
12. Loading: nothing before 150 ms, the three-row skeleton after, the real sections after the answer; fake timers only for the 150 ms delay, never the date. Failure: 500, network and 429 show "Couldn't load where this image is used." with "Try again" that repeats only `/usage`; 404 runs the existing gone flow; 401 is left to the global redirect; Delete stays enabled; switching images ignores the late answer.
13. Long title and long type name: one line, ellipsis classes, native title attribute on the link, row height unchanged.
14. Focus and tab order: article links, then entry links; the ring classes on a link; "and 2 more" not focusable.
DeleteMediaDialog (components/__tests__/DeleteMediaDialog.spec.ts):
15. The description table (2/5, 1/1, 2/0, 0/3, 0/0), the title for in use vs unused, the body order (entries list with heading and "and 2 more", then the articles list), the buttons, the variants note kept, no link in the entry rows.
16. Usage not ready (pending, failed): the generic description, no lists, "Delete image" enabled; when the usage answers while open the copy and lists switch and the focus stays.
17. Delete flow (confirm, in progress, failed, done, 404) runs unchanged; Cancel and Esc return focus to the Delete button of the panel.
BulkDeleteMediaDialog and MergeMediaDialog:
18. Bulk description counts "places" and uses "which will show a broken image or a missing-image notice."; rows and badges unchanged; no `/usage` request.
19. Merge dialog says "N places will be updated" and "Kept · used in N places now"; the toast stays "N copies merged. M articles updated.".
Cross-cutting:
20. French: every new string has an entry (the i18n completeness spec passes).
21. Regression: the existing Media view specs pass unchanged except the assertions named in 7, 18 and 19; if any other spec needs an edit, stop and report.
## Visual (task visual:check -- media)
In scope: the 4 states of the board group "11 Media library: usage" of RenewCMS Screens Schema.dc.html (they draw MediaFrame, and the copy list gives them the sample data). Every capture must be within 10 %, desktop and mobile, light and dark. Out of scope: states whose setups exist already and whose data does not change (they must keep passing untouched), and the picker states of slice B.
Prerequisites in web/visual, no change under docs/design (decision D12):
- `check.ts`: add the source `{ board: 'RenewCMS Screens Schema.dc.html', group: '11 Media library: usage', states: [the four below] }` to `extraSources.media`. The group differs from the screen's primary group ("Media"), so no merge change is needed.
- `states.ts`: the four setups, with the media API mock extended by `GET /v1/media/10/usage` and `GET /v1/media/11/usage` (shapes above). Existing media states keep their data, so `used_in` stays articles-only there.
- Board data:
- image 10 bathroom-tiles.png, 3 entries, `used_in` 3;
- image 11 lime-plaster.jpg, 2 articles and 5 entries, `used_in` 7;
- the grid also holds an unused image, so "Unused" shows in the captures.
| Board state | Setup in web/visual/states.ts | Board sample data |
|---|---|---|
| Grid: usage badge tooltip | /media with ent counts; step: hover the badge of image 10 (desktop), wait for the tooltip; mobile shows the grid with no tooltip | "Used in 3", tooltip "Used in entries: 3", "Unused" |
| List view: usage badge | /media?view=list; desktop table, mobile cards | "Used in 3", "Used in 7", "Unused" |
| Detail panel: used in entries | step: open image 11; wait for the entries list | "Used in 2 articles", "Used in entries", Events + "Lime plaster workshop", "Heritage stone walk", "Winter open day", "and 2 more" |
| Delete: image used by entries | step: open image 11, activate Delete; wait for the lists | the title, the description of 5 entries and 2 articles, both lists, "Cancel", "Delete image" |
Board caveats to report, never hide:
- The desktop table of the board draws `usedLink` with `pl(im.used)` (articles only). It shows "N articles" for lime-plaster.jpg and "Unused" for bathroom-tiles.png, while the written spec 3.8 says the list row carries the same badge. The spec follows the written text (D2); if the desktop capture of "List view: usage badge" exceeds 10 % the exception needs the user's explicit approval (`approvedBy`).
- The board draws the entry rows in the delete dialog as underlined links with the arrow icon; the spec renders plain rows (D10). If a capture exceeds 10 %, report it before changing the choice.
- The tooltip is drawn at a fixed place (left aligned, 26 px below the badge); a Nuxt UI tooltip may centre it. Use the `align` and offset that match the frame.
- The board titles ("Lime plaster workshop") come from the setup's `first_field` values, not from a title field.
- Clock-sensitive: none of the four states shows a relative date.
## Manual
- Real backend, owner and a second verified user: upload an image, use it in an article and in two entries through a Media field, and read "Used in 3" in the grid, list and mobile card. Hover and focus the badge for the tooltip, and check that a card with no entries shows "Used in articles: N" only.
- Open the panel: the entries link opens /content/<key>/<id> and shows the right entry. Add a fourth entry and read "and 1 more". Delete the entry and reload: counts fall.
- Delete the image from the panel with the dialog open: read the real counts, confirm, then open one of the entries and see "This image is no longer in the library" with the id kept.
- Throttle or kill the network while opening the panel and the dialog: the error line, "Try again" and the generic delete description.
- An image used only by an author or a site: no "safe to delete" claim anywhere.
- Keyboard: tab order across card, badge tooltip (focus), panel links and dialog buttons; Escape closes the tooltip first, then the panel; the focus return after Cancel; screen reader reads the card name, the tooltip and the lists.
- Motion and hover: the tooltip opening and closing, the skeleton fade at 150 ms, no layout jump larger than the preview change when the usage answers.
- Mobile: the full-screen panel, 48 px rows, the bottom-sheet dialog, 44 px targets, no tooltip.
- Contrast of the tooltip pair and of the muted type name in light and dark.
+492
View File
@@ -0,0 +1,492 @@
Feature: Media field type in the SPA
As an owner or admin building a content type, and as a verified user filling an entry
I want a Media field that holds one image from the media library
So that entries link to a library image and always show its current version
Background:
Given the SPA calls the API with relative URLs under /v1 and the "jwt" HttpOnly cookie
And API errors are plain text
And this slice changes only web/ (and web/visual); the backend of features/media_field_type.feature is done
And the design is docs/design/media-field-changes.md sections 1, 2, 3.2 to 3.7, 4, 6 and 7, with the board groups 2 Schema builder, 3 Review and delete, 4 Field types, 5 Content and entry list, 6 Entry editor and 10 Media picker for fields of "RenewCMS Screens Schema.dc.html"
And the registry is lib/fieldTypes with lib/entryEditors, the single source for the builder, the list cells and the entry form; no screen branches on the type name "media" where a registry property can say it
And a media value is the id of a library image (a uint32 of at least 1) or null
And every entry answer (POST 201, PUT 200, GET one, each list item) carries a top-level "media" object keyed by media field key: {"id","filename","width","height","size","thumbnail_url"} for an existing image, or {"id","missing":true} when the image is gone; a null value has no key
And the API refuses with 422 "invalid_entry: <key>: required" or "invalid_entry: <key>: type", 409 "schema_incompatible" for a new required media field on a type with entries, and 422 "invalid_field" for forbidden options
And the picker is the existing ImageUploader with MediaPicker, loading GET /v1/media/?page=&size=&q= with the total in the "counts" and "total" fields as the article picker does; the Sites, Authors, SEO and article pickers are unchanged
And the picker in field mode never requests /v1/image-variants and never shows the variant select or the alt text
And the form dimming stays the entry form's 70 % (design conflict 12, existing rule kept); inside the control the thumbnail drops to 60 % and the buttons take the disabled look
And sentence case, "image" and never "asset", buttons are verbs
And every string goes through t() and has a French entry in i18n/messages.ts
And a copy tagged "(proposed copy)" is not in the design and is the coder's single point of change
And user decisions already taken: Apply is disabled for the certain refusal; thumbnail after Description in schema order; "Clear"; "1600 × 900 · 240 KB"; "Use this image" and "Remove image"; "Pick an image" on optional fields; row heights 48 and 68
And out of scope (slice C): "Used in" badge, usage panel and delete warning of the Media library, the read-only view of a custom type, filtering by media
Scenario Outline: Media in the registry
Given the registry entry for "media"
Then <property> is <value>
Examples:
| property | value |
| type name in the API | media (the seventh entry, after select) |
| label | Media |
| description | One image from your media library |
| icon | lucide:image |
| control | MediaFieldControl |
| pairs with a neighbour | no, full width (as text, richtext and select) |
| empty value | null |
| initial on create | null; a media field has no default, so no "Default" tag ever shows |
| initial on edit | the stored id, or null |
| supports unique | no |
| supports limits | no |
| supports default | no |
| supports choices | no |
| counter | none |
| help | One image from your library. |
| list cell | thumbnail, column 80 px, not right-aligned, not sortable |
| sample in the API preview | null |
Scenario Outline: Client validation of a media value
Given a media field "Thumbnail" that is <required>
When the value is <value>
Then the rule is <rule>
Examples:
| required | value | rule |
| required | null | required |
| required | undefined | required |
| optional | null | none |
| optional | 7 | none |
| required | 7 | none |
| optional | 0 | type |
| optional | -1 | type |
| optional | 7.5 | type |
| optional | "7" | type |
| optional | true | type |
| optional | 4294967296 | type |
Scenario Outline: Messages of a media field
Given a media field labelled "Thumbnail"
Then the message of the rule <rule> reads <message>
Examples:
| rule | message |
| required | Pick an image for Thumbnail. |
| type | Thumbnail must be an image from the library. |
| min | not produced for media |
| max | not produced for media |
| options | not produced for media |
| unique | not produced for media |
Scenario: A loaded media field is not shown as Text
Given GET /v1/content-type/events returns a field {"key":"thumbnail","label":"Thumbnail","type":"media","required":false,"unique":false,"default":null,"min":null,"max":null,"options":[]}
Then the builder, the entry form and the list resolve it to the media entry of the registry, never to the fallback type "text"
# ---------- Schema builder (groups 2 and 4)
Scenario: Seven type tiles
Given the inspector of a field that can still change type
Then seven radio tiles are shown in this order, each with its icon, name and description
| tile | icon | description |
| Text | type | Short text, like a title or a name |
| Rich text | pilcrow | Long text with formatting, written in Markdown |
| Number | hash | Whole or decimal numbers |
| Yes or no | toggle-left | An on or off switch |
| Date | calendar | A calendar day, without a time |
| Choice | list | One option from a list you define |
| Media | image | One image from your media library |
And the grid has 3 columns in the desktop inspector and 2 in the mobile sheet
Scenario: Adding a media field (design "New media field, seven types")
Given Events with 7 saved fields and 37 entries
When the user activates "Add field", types the label "Thumbnail" and chooses the tile "Media"
Then the new row shows the badge "New", the key "thumbnail" (Auto, editable) with the help "The name used in the API. Starts with a letter. Lowercase letters, digits and underscores."
And the seven tiles are all enabled with Media selected and the legend "Type" has no lock
And the chip reads "Unsaved changes"
And the row is: grip, a 28 px square holding the image icon, the label, the key in mono and the badge "New"
Scenario: The inspector of a media field shows only what applies (design "Media field selected")
Given Events with a saved optional media field "Thumbnail" as its eighth field
When the user selects the row "Thumbnail"
Then the inspector reads "Field: Thumbnail" and holds, in this order, the Label input, the locked Key "thumbnail" with "Used in the API, so it can't change.", the Type tiles, the switch "Required" with "An entry can't be saved with this field empty." and the hint block
And the legend of the tiles reads "Type" with a lock and "Can't change after saving", Media is selected and the six other tiles are dimmed to 40 % and not selectable
And the hint block is info-soft with an info icon and reads "Holds one image from the media library. Entries link to the image instead of keeping a copy, so they always show its current version."
And "Unique values", "Default value", the limit inputs, the "Limits" heading and the choice list are not rendered at all
Scenario: Changing a new row to and from Media
Given a new row of type Text, required, with a Longest of 80
When the user chooses the tile "Media"
Then the label, the key and Required are kept and unique, default, limits and choices are reset
When the user then chooses the tile "Number"
Then the media hint is gone and the number controls show with no stale value
Scenario: A required media field (design "Media field, required")
Given a saved media field "Thumbnail" that is required
Then its row carries the existing Required marker "R" (accessible name "Required") next to the key
And its inspector shows Required switched on
Scenario: The PUT and POST body of a media field
Given a media field with the label "Thumbnail", the key "thumbnail" and Required off
When the type is saved
Then the field is sent as {"key":"thumbnail","label":"Thumbnail","type":"media","required":false,"unique":false,"default":null,"min":null,"max":null,"options":[]}
And a round trip of the loaded field to the payload produces no change
Scenario: Media in the API preview
Given the builder holds a media field "Thumbnail"
Then the sample entry shows "thumbnail": null and no "Example text"
Scenario: The mobile sheet of a media field
Given a 390 px viewport
When the user selects the row "Thumbnail"
Then the 92 % sheet titled "Field: Thumbnail" shows the same inspector in one column with the type tiles in 2 columns and the footer button "Done"
Scenario: The field-type gallery (group 4) has no SPA screen
Then the registry facts above are covered by the registry scenarios and no route renders the gallery frame
# ---------- Review (group 3)
Scenario: A required media field added to a type with entries is refused first (design "Review: required media field refused")
Given Events with 12 entries and a new media field "Thumbnail" that is required
When the user activates Save
Then no PUT is sent
And the dialog "Review changes to Events" with "Apply them to save the content type." opens (a bottom sheet on mobile)
And the summary reads "Add 1 field" and "Events has 12 entries. Each one is checked against the new fields when you apply."
And the row "Add Thumbnail" has the warning badge "Can't be applied" and the text "Media, required. A media field can't have a default, so the 12 existing entries would have no image. Make Thumbnail optional to add it."
And the note "Back to editing keeps your other changes." shows instead of the "Flagged changes can be refused..." note
And "Back to editing" is enabled and "Apply changes" is disabled (aria-disabled), so pressing it sends nothing
Scenario: The refusal is only for a new required media field with entries
Given Events with <entries> entries and the edit <edit>
When the user activates Save
Then <result>
Examples:
| entries | edit | result |
| 12 | adds Thumbnail, Media, optional | the review opens, "Apply changes" is enabled |
| 12 | adds Thumbnail, Media, required | the review opens, "Apply changes" is disabled |
| 0 | adds Thumbnail, Media, required | no review, the PUT is sent at once |
| 12 | makes the saved optional media field Thumbnail required | the review opens, row "Change Thumbnail" "Now required." flagged "Entries may not fit", Apply enabled; the server decides |
| 12 | adds Thumbnail required and changes Capacity | both rows listed, Apply disabled |
Scenario Outline: The clean row (design "Review: optional media field")
Given Events with <entries> entries and a new optional media field "Thumbnail"
Then the row "Add Thumbnail" reads "<text>" with no flag
And "Apply changes" is enabled
Examples:
| entries | text |
| 12 | Media, optional. 12 entries are unaffected. |
| 1 | Media, optional. 1 entry is unaffected. (proposed copy) |
Scenario: Back to editing after the refusal
Given the refused review is open
When the user chooses "Back to editing" (or presses Esc or the close icon)
Then the dialog closes, every edit is kept and no request was sent
When the user turns Required off on the new row and activates Save
Then the review opens with the clean row and "Apply changes" enabled
Scenario: The refusal follows offline and applying
Given the refused review is open
Then "Apply changes" stays disabled whatever the connection
And with a clean review, "Apply changes" is still disabled while offline, as before
Scenario: The server refuses anyway
Given the entry count was stale and the client opened no refusal
When the PUT answers 409 "schema_incompatible"
Then the existing "Nothing was changed" refusal flow of features/schema_builder_edit.feature runs unchanged
Scenario: 422 invalid_field on a media field
Given the PUT answers 422 "invalid_field"
Then the existing invalid-field failure of the builder is shown and the edits stay
# ---------- MediaFieldControl in the entry editor (group 6)
Scenario: Where the control sits
Given Events with the fields Title, Starts on, Ends on, Online, Capacity, Category, Description and Thumbnail
Then the control for Thumbnail is the eighth, after Description, full width in the 760 px column, and the footer lines come after it
Scenario: Empty, optional (design "Media control: empty, optional")
Given /content/events/new, or an entry whose thumbnail is null
Then the label reads "Thumbnail"
And a dashed box (1 px, border-accented, padding 12) holds a 40 px square with the image icon, the text "No image selected." and the outline button "Pick an image" with the image-plus icon
And the help line reads "One image from your library."
And on mobile the box stacks and the button is 44 px high
Scenario: Empty, required (design "Media control: empty, required")
Given the field is required
Then the label reads "Thumbnail *" with the asterisk hidden from assistive technology, and the rest is as the empty state
Scenario: Filled (design "Media control: filled")
Given an entry whose thumbnail is 7 and media.thumbnail is {"id":7,"filename":"lime-plaster-workshop.jpg","width":1600,"height":900,"size":245760,"thumbnail_url":"/media/lime-plaster-workshop.jpg"}
Then a solid 1 px box (border-accented, padding 12) holds a 160 × 120 thumbnail button showing thumbnail_url, the filename in weight 500, "1600 × 900 · 240 KB" in 12/18 muted, the outline button "Change image" (image icon) and the ghost button "Remove" (x icon)
And the help line reads "One image from your library."
And on mobile the thumbnail is full width at 16:9 and the two buttons are full width and 44 px high
And a width or height of null (a vector image) reads "Vector · 8 KB"
Scenario: Hover (design "Media control: hover")
Given the filled state on desktop
When the pointer is over the thumbnail
Then the box border takes the --ui-text-muted colour and a 28 px bar at the bottom of the thumbnail (--ui-bg-inverted, --ui-text-inverted) reads "Change image" with the image icon at 14 px
And mobile has no hover state and shows the filled state
Scenario: Focus (design "Media control: focus")
Given the filled state
When the keyboard focus reaches the thumbnail button
Then it has a 2 px --ui-primary outline with a 2 px offset
Scenario: Pointer and keyboard open the picker
Given the filled state
When the user activates the thumbnail, "Change image", or on an empty control "Pick an image"
Then the picker opens in field mode and nothing else changes
Scenario: Remove
Given the filled state
When the user activates "Remove"
Then the value becomes null, the control shows the empty state and the chip reads "Unsaved changes"
And the live region says "Image removed from Thumbnail." and the focus is on "Pick an image"
Scenario: Missing image, optional (design "Media control: image no longer in the library")
Given media.thumbnail is {"id":7,"missing":true} and the field is optional
Then the box is solid with a dashed 160 × 120 placeholder (16:9 on mobile) holding image-off at 24 px, with role "img" and the name "Image no longer in the library"
And beside it "This image is no longer in the library" in weight 500, the help "You can still save. The entry keeps the link until you change it." in 12/18 muted, the outline button "Choose another image" and the ghost button "Clear"
And there is no help line under the box
And "Save" is allowed and the data sent keeps thumbnail 7
Scenario: Clear
Given the missing state
When the user activates "Clear"
Then the value becomes null, the live region says "Thumbnail cleared." and the focus is on "Pick an image"
Scenario: Missing image, required (design "Media control: missing image, required")
Given media.thumbnail is {"id":7,"missing":true} and the field is required
Then the in-box help reads "Thumbnail is required. Choose another image to save."
And when the user saves, no request is sent, the box takes the error border, the line "Pick an image for Thumbnail." shows with a circle-alert icon, the chip reads "Not saved" and the focus is on "Choose another image"
Scenario: Validation error on an empty required field (design "Media control: validation error")
Given an empty required media field
When the user activates "Save"
Then no request is sent
And the box border is --ui-error with an inset 1 px --ui-error, the error line "Pick an image for Thumbnail." with circle-alert at 14 px replaces the help line, and the chip reads "Not saved"
And the focus moves to "Pick an image" and the page scrolls to it
And only the first field in schema order with an error takes the focus
Scenario: Picking clears the error
Given the validation error is shown
When the user picks an image
Then the error and the error border go, the chip reads "Unsaved changes" and nothing else is validated
Scenario: Saving (design "Media control: saving")
Given the PUT has not answered
Then the form is dimmed to 70 %, the thumbnail is at 60 %, the buttons take the disabled look, the thumbnail button and the buttons are not operable and the picker cannot open
And Save reads "Saving…"
Scenario: Read-only after a schema change (design "Media control: read-only, type changed")
Given the PUT answers 422 "invalid_entry: thumbnail: unknown_field" and thumbnail is a media field of the loaded type
Then a warning alert "The fields of Events changed" reads "The Thumbnail field was changed after you opened this form. Reload the form to continue. What you typed here can't be saved against the old fields." with the action "Reload form"
And the control looks as in Saving and cannot be operated
And "Reload form" fetches the type and the entry again and rebuilds the form with the control from the answered media map
And any other key keeps the copy of features/content_entry_editor.feature state 12
Scenario Outline: What the control shows and sends
Given the loaded value <loaded> with media <media>
When the user <action> and activates "Save"
Then the control shows <shown>
And the data holds "thumbnail": <sent>
Examples:
| loaded | media | action | shown | sent |
| null | none | saves with nothing changed | the empty state | null |
| 7 | existing image 7 | saves with nothing changed | the filled state | 7 |
| 7 | missing image 7 (optional) | saves with nothing changed | the missing state | 7 |
| 7 | existing image 7 | picks image 8 | image 8 (its own library data) | 8 |
| 7 | existing image 7 | activates Remove | the empty state | null |
| 7 | missing image 7 | activates Clear | the empty state | null |
| null | none | picks image 8 | image 8 | 8 |
Scenario: Right after a pick the control uses the picked library item
Given the user picks "bathroom-tiles.png" (id 8, 800 × 600, 51200 bytes) from the library
Then before any save the control shows its filename, "800 × 600 · 50 KB" and its url as the thumbnail
And no request is made for it
When the PUT answers 200 with media.thumbnail for image 8
Then the control is rebuilt from the answered media map
Scenario: Dirty tracking of a media value
Given an entry whose thumbnail is 7
When the user picks image 8 then picks image 7 again
Then the chip reads "Saved", "Save" is disabled and the leave guard does not prompt
When the user picks image 8
Then the chip reads "Unsaved changes" and the leave guard prompts
Scenario Outline: Server answers for a media field
Given the client found no error and the PUT or POST is sent
When the server answers <status> "<body>"
Then <result>
Examples:
| status | body | result |
| 422 | invalid_entry: thumbnail: required| "Pick an image for Thumbnail." under the control, error border, chip "Not saved", focus on the first button |
| 422 | invalid_entry: thumbnail: type | "Thumbnail must be an image from the library." under the control, chip "Not saved", focus on "Change image" or "Pick an image" (the image was deleted between the pick and the save) |
| 409 | schema_incompatible | not an entry answer; never produced by the entry routes |
Scenario: Create payload with a media field
Given /content/events/new with Title "Open day", Starts on 2026-11-21 and the media field left empty
When the user activates "Save"
Then POST /v1/content-type/events/entry is sent once with "thumbnail": null among the other keys, never absent
And with image 8 picked it holds "thumbnail": 8, a JSON number
Scenario: The title of an entry whose first field is media
Given a type whose first field is a media field
Then the page title, the breadcrumb and the saved toast read "Entry 42" (an id is not a title) and the list card title reads the same (proposed)
Scenario: Layout of the generated form with a media field
Given a boolean, a number or a date field before the media field
Then the media field never pairs and is full width at every viewport
# ---------- Picker in field mode (group 10)
Scenario: Opening the picker from an optional field (design "Library: nothing chosen")
Given the control holds image 1 "north-wall.jpg" and the field is optional
When the user activates "Change image"
Then the dialog (640 px wide on desktop, a bottom sheet on mobile) is titled "Choose an image" and has the tabs "Upload" and "Library", opening on Library
And the search reads "Search by filename"
And the first row of the Library tab is "No image" with "Leave this field empty."
And the summary reads "Newest first · 48 images", the tiles are square, 4 columns on desktop and 3 on mobile, and "Load more" shows
And the tile of image 1 carries the badge "Current" (sand fill, --rc-on-sand text, 18 px high, bottom left)
And "Cancel" is enabled and "Use this image" is disabled (aria-disabled)
And there is no alt text field, no variant select, and no request to /v1/image-variants
Scenario: Choosing an image (design "Library: image chosen")
When the user selects a tile
Then it gets the primary outline with a check at top right, aria-pressed is true, and a strip appears below the grid with a 56 px thumbnail, the filename and "dimensions · size"
And the grid shrinks and "Load more" is hidden while a tile is selected, as in the article picker
And "Use this image" is enabled
When the user activates it
Then the dialog closes, the value becomes that image's id, the control shows its data, the live region says "Image selected: <filename>" and the focus is on "Change image"
Scenario: Choosing "No image" (design "Library: No image chosen")
When the user selects the row "No image"
Then it takes the sand fill, the primary border and a check, with aria-pressed true, and any selected tile is released
And the primary button reads "Remove image"
When the user activates it
Then the value becomes null, the live region says "Image removed from Thumbnail." and the focus is on "Pick an image"
Scenario: A required field has no "No image" row (design "Library: required field")
Given the field is required
Then the Library tab shows no "No image" row and the title is still "Choose an image"
Scenario: Choosing the current image again
Given the control holds image 1
When the user selects the tile "Current" and activates "Use this image"
Then the dialog closes, the value does not change, the chip stays as it was, and no announcement is made (proposed)
Scenario: Empty library (design "Library: empty")
Given GET /v1/media/ returns no image
Then the picker opens on the Upload tab unless the user already chose a tab, and the Library tab reads "Your library is empty" / "Images you upload appear here, ready to use in any article or entry." with "Upload an image"
And "Upload an image" switches to the Upload tab
And the article picker keeps "Images you upload appear here, ready to use in any article."
Scenario Outline: Library failures (design "Library: failed to load")
Given GET /v1/media/ answers <outcome>
Then <result>
Examples:
| outcome | result |
| 500 | the error alert "Couldn't load your library" / "Check your connection and try again." with "Try again", no "No image" row |
| a network error | the same |
| 429 | the countdown alert of the Media page |
| 401 | the global redirect, no local copy |
Scenario: Try again
Given the failed state
When the user activates "Try again"
Then only GET /v1/media/ is sent again and the grid replaces the alert
Scenario: Loading (design "Library: loading")
Given GET /v1/media/ has not answered
Then after 150 ms skeleton tiles show (8 on desktop, 9 on mobile), no "No image" row shows and "Use this image" is disabled
Scenario: Search and no results
When the user types "wall"
Then the search is trimmed and debounced, the selection is released and the grid reloads
And an empty match reads "No images match \"wall\"" with "Clear search", as in the article picker
Scenario: Load more
When the user activates "Load more"
Then the next page loads, the focus stays on the button until the new tiles arrive and then moves to the first new tile
Scenario: Upload tab (design "Upload tab")
When the user opens the Upload tab
Then the existing flow runs unchanged: "Drop an image here, or choose a file", "PNG, JPEG, WEBP, SVG · max 10 MB", crop and resize, the duplicate check "Already in your library" with "Use existing" and "Upload anyway"
And a finished upload lands in the library and becomes the value of the field, as in the Sites and Authors pickers, then the dialog closes and the live region says "Image selected: <filename>" (to confirm, decision D5)
Scenario Outline: Upload failures keep the existing copy
Given the POST /v1/media/ answers <outcome>
Then <copy> shows and nothing is chosen
Examples:
| outcome | copy |
| 413 | That file is too large. |
| 400 | That request wasn't valid. Check the fields and try again. |
| 429 | Too many requests. Try again in a few minutes. |
| 500 | Something went wrong on our side. Nothing was changed. Try again in a moment. |
Scenario: Cancel and Escape
When the user activates "Cancel" or presses Esc or the close icon
Then nothing changes and the focus returns to the button that opened the picker
Scenario: Tile names in field mode
Then each tile is a button named "stone-steps.jpg, 310 KB" and "stone-steps.jpg, 310 KB, Current" for the current image, with aria-pressed, and no "used in" part
And "No image" is a button with aria-pressed and "Use this image" uses aria-disabled while nothing is chosen
Scenario: The other pickers are unchanged
Then the article picker still reads "Add an image", "Insert image", "In this article", the alt text and the variant select
And the Sites, Authors and SEO pickers still read "Use image" with no strip and no "No image" row
# ---------- Entry list (group 5), minimal safe cell
Scenario: The Thumbnail column (design "Thumbnail column")
Given Events with a Thumbnail media field, the columns Title, Thumbnail, Starts on and Category chosen, and the items 42 and 41 with an existing image, 40 and 37 with null, 39 with a missing image
Then the header reads "Thumbnail" with no sort icon and no aria-sort, in a column 80 px wide
And an existing image shows a 40 px square thumbnail from media.thumbnail_url, with 4 px above and below, so the row stays 48 px
And a null value shows "–" in the muted colour
And a missing image shows a dashed 40 px square with the unlink icon, role "img" and the name "Image no longer in the library"
And the thumbnail is read from the item's own "media" object, with no extra request
Scenario: Tooltip of the missing placeholder
Given a missing image in the list on desktop
When the pointer or the focus reaches the dashed square
Then a tooltip reads "Image no longer in the library"
And mobile has no tooltip
Scenario: The mobile card (design "Thumbnail column", mobile)
Given a 390 px viewport and the Thumbnail column chosen
Then a 32 px thumbnail leads each card, "–" stands for none, a dashed 32 px square for a missing image, and the card keeps its 68 px minimum height
And when no media field is among the chosen columns the card is unchanged
Scenario: Columns menu (design "Columns menu with Thumbnail")
When the user opens "Columns"
Then "Thumbnail" is listed with the image icon, its key "thumbnail", and a checkbox like the other fields
And the summary reads "4 of 6" and on mobile "Choose up to 6 fields to show. 4 selected."
And the cap of 6, Reset and the stored choice work as for any field
Scenario: Thumbnail as the first column
Given a type whose first field is a media field
Then the first column still links to the editor and the thumbnail is the link content
Scenario: Plain text of a media cell
Given the card or a title needs the text of a media cell
Then it reads "–" for none and never the numeric id
# ---------- Accessibility (media-field-changes.md section 6)
Scenario: Accessibility of the control
Then the control is role="group" labelled by the field label
And the main button (Pick an image, or Change image) carries aria-required when the field is required
And the accessible names are "Pick an image for Thumbnail", "Change image, lime-plaster-workshop.jpg, 1600 by 900, 240 KB" (the thumbnail), "Remove image from Thumbnail", "Clear Thumbnail" and, for the placeholder, role "img" "Image no longer in the library"
And the error text has an id, and the main button gets aria-invalid="true" and aria-describedby with the error id then the help id
And the tab order is label, thumbnail, Change image, Remove, then help or error (two stops open the same picker, as drawn; decision D8)
And one polite live region announces "Image selected: lime-plaster-workshop.jpg", "Image removed from Thumbnail." and "Thumbnail cleared."; nothing is announced when the picker opens
And focus goes to the first invalid control on a refused save and, after the picker, to the places of the picker scenarios
And mobile targets are 44 px and there is no hover on mobile
Scenario: Accessibility of the builder and the review
Then the Media tile is a radio in the existing radio group, the dimmed tiles are disabled, "Can't be applied" is a text badge and not only a colour, and the disabled "Apply changes" is announced as disabled
+114
View File
@@ -0,0 +1,114 @@
# QA: Media field type in the SPA (slice B)
Runner: Vitest + Vue Test Utils (`task test:web`). No Go test: the backend is covered by features/media_field_type.qa.md and nothing changes in it. Kit: extend `views/__tests__/schemaTestKit.ts` with the Events type (7 fields, plus Thumbnail as the 8th, optional or required, saved or new), entries whose `data.thumbnail` and top-level `media` vary, the library list (`GET /v1/media/?page=&size=&q=` with `items`, `total`, `counts`), and the plain-text bodies `invalid_entry: thumbnail: required`, `invalid_entry: thumbnail: type`, `invalid_entry: thumbnail: unknown_field`, `schema_incompatible`, `invalid_field`. Library fixtures: 1 "north-wall.jpg", 7 "lime-plaster-workshop.jpg" (1600 × 900, 245760 bytes, shown "240 KB"), 8 "bathroom-tiles.png" (800 × 600, 51200 bytes, "50 KB"), a vector image with null width and height. Pin the time zone; never freeze the system date. No state of this slice depends on the clock.
## Automated
Registry and pure logic (lib/__tests__, it.each over the feature's Examples):
1. Registry `media`: label, description, icon, control, no pairing, empty value, initial on create and edit, no unique, limits, default or choices, counter none, help, cell, API preview sample null. A loaded field of type `media` never resolves to the `text` fallback in the builder, the form or the list. The six existing types still pass every existing registry assertion unchanged (update the count assertions from six to seven).
2. Validation table: required and optional with null, undefined, 7, 0, -1, 7.5, "7", true, 4294967296. A required field whose image is missing is `required` (registry takes the image summary, or the form passes it).
3. Messages for required and type with the label "Thumbnail"; min, max, options and unique are never produced.
4. Payload: id to id, null to null, an optional missing stored id is sent unchanged, never absent. The builder payload of a media field equals `{key,label,type:'media',required,unique:false,default:null,min:null,max:null,options:[]}`; a loaded media field round-trips with no diff.
5. Builder model: `changeFieldType` to and from media resets unique, default, limits and options and keeps label, key and required. Sample preview value is null.
6. Review diff: the add row of a media field, required with total > 0 is flagged "Can't be applied" with the exact text; optional reads "Media, optional. N entries are unaffected." (plural rule for 1); total 0 gives no review; making a saved media field required stays "Now required." with "Entries may not fit". Summary line is unchanged.
7. Entry helpers: `entryTitle` with a media first field gives "Entry N"; `describeCell` and `plainCellText` give "–" for none and never the id; media summary parsing for existing, missing and absent keys; `formatDimensions` and `formatSize` give "1600 × 900" and "240 KB" for 245760 bytes and "Vector" for null dimensions.
Schema builder (views/__tests__/SchemaBuilderMedia*.spec.ts):
8. Seven tiles in order with icon, name and description; 3 columns in the desktop inspector, 2 in the sheet.
9. New media field: "New" badge, key editable with its help, seven tiles enabled, chip "Unsaved changes".
10. Saved media field: key locked with its help, legend lock and "Can't change after saving", six tiles dimmed and unselectable, hint block copy, Required switch and copy, and that "Unique values", "Default value", limit inputs, "Limits" heading and choice list are absent from the DOM.
11. Required marker on the row; row anatomy (28 px image square, label, key, badges).
12. Mobile sheet: title "Field: Thumbnail", footer "Done", one column.
13. Save paths: PUT and POST bodies; 422 invalid_field and 409 schema_incompatible keep their existing flows.
Review (views/__tests__/SchemaBuilderMediaReview.spec.ts):
14. Refusal: dialog copy, summary, row, badge, note "Back to editing keeps your other changes.", Apply `aria-disabled` and a click sends no PUT; Back to editing, Esc and close keep the edits and send nothing; turning Required off then Save shows the clean row with Apply enabled.
15. The table of the feature (entries 12 and 0, optional and required, changed to required, mixed with a Capacity change); Apply stays disabled offline in both reviews.
16. A stale count: PUT 409 `schema_incompatible` runs the existing refusal flow.
MediaFieldControl (components/__tests__/MediaFieldControl.spec.ts), one test per state and viewport (components/__tests__/viewport.ts for 1440 and 390):
17. Empty optional and required: structure, copy, " *" hidden from AT, help line, 44 px button on mobile.
18. Filled: thumbnail 160 × 120 (full width 16:9 on mobile), filename, "1600 × 900 · 240 KB", buttons and icons, help line; vector image reads "Vector".
19. Hover bar on desktop only (`pointerenter` on the thumbnail), absent on mobile; focus ring classes on the keyboard-focused thumbnail.
20. Error: border classes, error line replaces help, aria-invalid and aria-describedby order (error id, help id), focus on "Pick an image" or "Choose another image".
21. Missing optional and required: placeholder role img and name, copy, no help line under the box, buttons.
22. Saving and read-only: form 70 %, thumbnail 60 %, buttons disabled, picker cannot open.
23. Events: emits `update:modelValue` with the id or null for pick, "Remove image" choice, Remove and Clear; announcements in one polite live region; focus targets after Use this image (Change image), Remove, Clear and "Remove image" (Pick an image), and after Cancel and Esc (the opener).
24. Names and role: group labelled by the label, the exact accessible names, aria-required on the main button, two tab stops as drawn.
Entry editor (views/__tests__/EntryEditorMedia*.spec.ts):
25. Position after Description, full width, never pairs; form built from the type with Thumbnail.
26. The table "What the control shows and sends" (it.each): loaded value and media map to shown state and PUT body.
27. After a pick the control shows the picked library item's data with no request; after the PUT it is rebuilt from the answered `media`; after "Reload form" from the refetched entry.
28. Dirty tracking: pick 8 then 7 is clean; pick 8 is dirty and the leave guard prompts.
29. Client validation: required empty and required missing give no request, "Not saved" chip, focus and scroll on the first error in schema order; picking clears the error; optional missing saves with the id unchanged.
30. Server answers: 422 required and type map to the control with their messages and focus; 422 `unknown_field` on a media key shows the "The Thumbnail field was changed..." line, other keys keep the state 12 copy of features/content_entry_editor.feature; create payload `thumbnail: null` and `thumbnail: 8`.
31. Title of an entry whose first field is media: "Entry N" in title, breadcrumb, toast and list card.
Picker field mode (components/__tests__/ImageUploaderField.spec.ts, views/__tests__/EntryEditorPicker.spec.ts):
32. Title, tabs, search, "No image" row on optional only and never on required, empty, error and loading states; "Current" badge replaces "In this article"; tile names with and without ", Current"; aria-pressed on tiles and on "No image"; no alt field, no variant select, and no `/v1/image-variants` request.
33. Selection: strip with 56 px thumbnail, filename and "dimensions · size"; Load more hidden while selected; "Use this image" `aria-disabled` until a choice; "Remove image" when No image is chosen; selecting a tile releases No image and the reverse; selecting the Current tile then Use closes with no change and no announcement.
34. Library states: empty (field copy with "or entry", and the article copy unchanged), 500 and network failure with Try again repeating only GET /v1/media/, 429 countdown alert, 401 global, loading skeleton after 150 ms (8 and 9 tiles), search trimmed and debounced, no results, Load more focus move.
35. Upload tab: unchanged flow including the duplicate card; a finished upload becomes the field value (per decision D5) and announces "Image selected: ..."; the four upload failure copies.
36. Dialog 640 px wide on desktop, bottom sheet on mobile; Cancel, Esc and close return focus to the opener.
37. Regression: the article picker and the Sites, Authors and SEO pickers keep their copy and behavior (run their existing specs unchanged; if one needs an edit, stop and report).
Entry list (components/__tests__/FieldCell.spec.ts, EntryTable, EntryCardList, ColumnPicker):
38. Thumbnail, "–" and missing cells: size 40 px, 4 px margins, row height 48 px, role img and name on the placeholder, tooltip on desktop only, `alt` of the thumbnail (proposed: the filename).
39. Header "Thumbnail": no sort icon, no `aria-sort`, 80 px; mobile card with a 32 px leading thumbnail and the 68 px minimum height, unchanged when no media column is chosen.
40. Columns menu: Thumbnail listed with the image icon and its key; "4 of 6" and the cap behaviour; stored choice in localStorage.
41. No extra request for thumbnails; a first media column still links to the editor.
Cross-cutting:
42. French: every new string has an entry (the i18n completeness spec passes, including the files added to the list in `i18n/contentMessages.spec.ts` if any).
43. Existing specs that assert six types or six tiles are updated to seven and nothing else in them changes.
## Visual (task visual:check)
Prerequisites in web/visual, no change under docs/design:
- `check.ts`: states of the board groups 5 and 6 that the design markdown does not list (`Thumbnail column`, `Columns menu with Thumbnail`, `Missing image: tooltip`; the ten `Media control: ...` states) must be added to the screens `content` and `entry`. Today `extraSources` entries whose group equals the screen's primary group are dropped (decision D3), so the runner must be changed to merge them. Groups 2 and 3 (screen `schema`) and group "10 Media picker for fields" (add to `extraSources.entry`, board RenewCMS Screens Schema.dc.html) are plain `extraSources` additions. Group 4 "Media" is a reference gallery with no SPA route: no setup, covered by Vitest. Group 1 "Custom type: read-only view" and group 11 are slice C.
- `states.ts`: Events gets an eighth field Thumbnail (media) in `schemaEventsFields` variants for these states only, so existing states keep their 7 fields. Image URLs (`thumbnail_url`, library `url`) are fulfilled by the setup with an SVG stand-in drawing the board's placeholder (repeating-linear-gradient 135deg between --ui-bg-elevated and --ui-bg-accented, mono label "1600 × 900"), as `stubBoardImage` does for the picker. The media size is 245760 bytes so `formatSize` prints "240 KB". Sidebar calls stay mocked. Every capture within 10 %, desktop and mobile, light and dark.
| Board group, state | Setup in web/visual/states.ts | Board sample data |
|---|---|---|
| 2, Media field selected | /schema/events, Events + saved optional Thumbnail, 37 entries; step: open the row "Thumbnail" | row "Thumbnail", key "thumbnail", "Field: Thumbnail", "Used in the API, so it can't change.", "Can't change after saving", tiles Text to Media, hint "Holds one image from the media library. ..." |
| 2, New media field, seven types | /schema/events (7 saved fields); step: Add field, label "Thumbnail", click tile Media | "New" badge, key "thumbnail" help "The name used in the API. ...", seven tiles, chip "Unsaved changes" |
| 2, Media field, required | /schema/events, saved Thumbnail required; step: open its row | marker "R" on the row, "Required" switch on with "An entry can't be saved with this field empty." |
| 3, Review: required media field refused | 12 entries (`total: 12`); step: add Thumbnail, Media, Required on, Save | "Review changes to Events", "Add 1 field", "Events has 12 entries. ...", "Add Thumbnail", "Can't be applied", "Media, required. A media field can't have a default, so the 12 existing entries would have no image. Make Thumbnail optional to add it.", "Back to editing keeps your other changes.", Apply disabled |
| 3, Review: optional media field | same with Required off | "Add Thumbnail", "Media, optional. 12 entries are unaffected.", Apply enabled |
| 5, Thumbnail column | /content/events; localStorage `renewcms-content-columns-events` = ["title","thumbnail","starts_on","category"]; the 7 standard rows 42, 41, 40, 39, 38, 37, 36 with thumbnail ok, ok, none, missing, ok, none, ok | header "Thumbnail", 40 px thumbnails, "–" on 40 and 37, dashed unlink square on 39; mobile 32 px leading thumbnail |
| 5, Columns menu with Thumbnail | same storage; step: click "Columns" | "Columns", "4 of 6", Thumbnail with the image icon, "Choose up to 6 fields to show. 4 selected." (mobile) |
| 5, Missing image: tooltip | step: hover the dashed square of row 39 (desktop); mobile has no tooltip and shows the list | "Image no longer in the library" |
| 6, Media control: empty, optional | /content/events/42 with thumbnail null; Events with Thumbnail | "Thumbnail", "No image selected.", "Pick an image", "One image from your library." |
| 6, Media control: empty, required | Thumbnail required, thumbnail null | "Thumbnail *", same body |
| 6, Media control: filled | thumbnail 7, media {id 7, "lime-plaster-workshop.jpg", 1600, 900, 245760} | "lime-plaster-workshop.jpg", "1600 × 900 · 240 KB", "Change image", "Remove", help |
| 6, Media control: hover | filled; step: hover the thumbnail (desktop); mobile is the filled frame | bar "Change image" |
| 6, Media control: focus | filled; step: Tab to the thumbnail (keyboard, so :focus-visible) | 2 px primary ring, name "Change image, lime-plaster-workshop.jpg" |
| 6, Media control: validation error | Thumbnail required, thumbnail null; step: click Save | "Pick an image for Thumbnail.", chip "Not saved", focus on "Pick an image" |
| 6, Media control: image no longer in the library | optional, media {id 7, missing true} | "This image is no longer in the library", "You can still save. The entry keeps the link until you change it.", "Choose another image", "Clear" |
| 6, Media control: missing image, required | required, missing; step: click Save | "Thumbnail is required. Choose another image to save.", "Pick an image for Thumbnail.", "Not saved", focus on "Choose another image" |
| 6, Media control: saving | filled; step: edit Title, Save, PUT `hang: true` | "Saving…", thumbnail at 60 % |
| 6, Media control: read-only, type changed | filled; step: edit Capacity, Save, PUT 422 `invalid_entry: thumbnail: unknown_field` | "The fields of Events changed", "The Thumbnail field was changed after you opened this form. Reload the form to continue. What you typed here can't be saved against the old fields.", "Reload form" |
| 10, Library: nothing chosen | /content/events/42 (control holds image 1 "north-wall.jpg", optional); step: click "Change image"; library = the board's 12 images, counts.all 48 | "Choose an image", "Upload", "Library", "Search by filename", "No image", "Leave this field empty.", "Current" on north-wall.jpg, "Newest first · 48 images", "Load more", "Cancel", "Use this image" (disabled) |
| 10, Library: image chosen | step: select the 4th tile (the frame draws id 4 logo-renew.svg, "Vector · 8 KB"; the copy list says kitchen-before.webp, report the mismatch) | strip with filename, "dimensions · size", "Use this image" enabled |
| 10, Library: No image chosen | step: click the row "No image" | sand row with check, "Remove image" |
| 10, Library: required field | Thumbnail required | no "No image" row, "Use this image" disabled |
| 10, Library: empty | `GET /v1/media/` returns no item | "Your library is empty", "Images you upload appear here, ready to use in any article or entry.", "Upload an image" |
| 10, Library: failed to load | `GET /v1/media/` 500 | "Couldn't load your library", "Check your connection and try again.", "Try again" |
| 10, Library: loading | `GET /v1/media/` `hang: true`; wait for the skeleton tile | skeleton tiles, "Use this image" disabled |
| 10, Upload tab | step: click the tab "Upload" | "Drop an image here, or choose a file", "PNG, JPEG, WEBP, SVG · max 10 MB" |
Board caveats to report, never hide:
- The group 6 media states draw the form with a negative margin (-380 px desktop, -560 px mobile) under an intact title row inside an overflow-hidden box. A real page can only scroll as a whole, so the title row and topbar will differ. If a capture exceeds 10 %, an exception needs the user's explicit approval (`approvedBy`), as for existing schema states. Do not call `schemaSettle` after scrolling to the control, since it resets scrollTop.
- Group 10 draws a stand-in entry form behind the dialog (design conflict 13), not the real editor. Expect a possible exception request for the page behind the dialog.
- The frame and the copy list disagree on "Library: image chosen" (see above) and on the list row titles of "Thumbnail column"; the frame wins.
- Group 6 "Saved" is not checked here; the existing entry setups are untouched.
## Manual
- Real backend, owner and a second verified user: create a type with a required Title and an optional Thumbnail; add an entry with an image; the thumbnail shows in the editor and in the list; change the image; remove it; save.
- Delete the image from the Media page, reload the entry: the missing state, then save with the optional field kept (the id is sent unchanged); make the field required through a type with no entries and see "Pick an image for Thumbnail." on save.
- Add a required Thumbnail to a type with entries: the review refuses with Apply disabled; make it optional and apply (real PUT 200). Make an existing optional media field required while an entry has none: real 409, then the existing refusal flow.
- Upload from the Upload tab of the picker with crop and resize, and an already-in-library duplicate; confirm the final selection behaves as decided in D5.
- Keyboard: tab order across the control (thumbnail, Change image, Remove), Enter and Space on a tile, Esc and Cancel return focus to the opener, focus after Use this image, Remove and Clear; screen reader announcements of the live region and of the error; contrast of the Current badge and the hover bar in light and dark.
- Mobile: bottom sheet, 44 px targets, no hover.
+269
View File
@@ -0,0 +1,269 @@
Feature: Media field type for custom content types
As a site owner or admin
I want a content type field that holds one image from the media library
So that entries link to the library image instead of keeping a copy
Background:
Given internal/domain/contenttype adds the field type "media" next to text, richtext, number, boolean, date and select
And a media field accepts only label, key and required; unique, default, min, max and options are refused with ErrInvalidField
And a stored media value is the id of a library image (uint32, at least 1) or null
And the entry rules required and type apply to a media field; min, max, options and unique never apply
And entry.Validate stays pure; the check that an image exists in the library is done by CreateEntry and UpdateEntry through the domain image.Repository
And CreateEntry, UpdateEntry, GetEntry and ListEntries receive image.Repository, wired only in api/dependecyInjection.go
And a changed value means a value that is not equal to the id the entry holds in the stored document for that key; on POST every non-null value is changed; on PUT the value is unchanged only when the id equals the stored one
And a changed or new non-null value must be an existing library image, else 422 "invalid_entry: <key>: type"
And an unchanged stored id whose image was deleted since passes the type check
And a required media field is never saved empty: null or absent gives 422 "invalid_entry: <key>: required", and so does an unchanged stored id whose image no longer exists
And rules are checked in field order for Validate, then library existence in field order, then unique, and the body names one field per answer
And an entry response keeps its seven keys (id, content_type, data, created_by, updated_by, created_at, updated_at) and adds the key "media"
And data keeps the image id (or null) as the value of each media field
And "media" is a JSON object keyed by media field key, always present ({} when the type has no media field or every media value is null)
And "media"[key] is {"id","filename","width","height","size","thumbnail_url"} for an existing image, with width and height null when unknown, or {"id","missing":true} when the image is gone
And thumbnail_url is the image's original path, the same value as the url of a media list item
And the same "media" object is on POST 201, PUT 200, GET one and every item of the list
And usage in the library means distinct articles, authors, sites and entries; one entry counts once however many of its media fields point at the image
And GET /v1/media/ and GET /v1/media/{id} items carry used_in = articles + authors + sites + entries, and the counts.unused filter counts entries as uses
And GET /v1/media/{id}/usage stays a JSON array and gains items of type "entry"
And an entry usage item is {"type":"entry","id":<entry id>,"fields":[<media field keys>],"content_type_key":"event","content_type_name":"Events","first_field":{"key":<key>,"type":<field type>,"value":<raw stored value or null>}}, with no "title" and no "published"
And first_field is the first field of the type in schema order and its value is the raw stored JSON value, never formatted or truncated by the server; the client formats it with the same rule as the entry list and shows "Entry N" for null
And article, author and site usage items are unchanged and keep their "title"
And usage items are ordered articles by id, authors, sites, then entries by content type name then entry id; the array has no cap and the client shows the first few and the total
And the media routes keep their access rules and their plain-text errors (404 image_not_found, 400 uint32 format)
And DELETE /v1/media/{id} stays allowed for an image used by entries and leaves their data untouched
And MergeMedia (including the purge run) repoints entry media values from every merged copy to the kept image and reports it in the existing counts
And no repository method is added: entries that reference an image are found with contenttype.Repository.List and entry.Repository.ListPage (Unpaged), filtered in Go, so the code works on SQLite, MySQL/MariaDB and PostgreSQL with no JSON operators
And schema compatibility does not consult the library
And the key set assertions of the earlier custom content type and entry features and tests are amended from seven keys to eight
And types: the library images are 7 "lime-plaster.jpg" 1600x900 240000 bytes, 8 "bathroom-tiles.png" 800x600 51200 bytes; the type "event" has title (text, required) then thumbnail (media, label "Thumbnail", optional)
And users: admin id 2 (verified) can write types; any verified user can write entries
Scenario: Creating a content type with a media field
Given a valid jwt cookie for admin 2
When the client sends POST /v1/content-type with fields title (text, required) and {"key":"thumbnail","label":"Thumbnail","type":"media","required":false,"unique":false,"default":null,"min":null,"max":null,"options":[]}
Then the response status is 201
And the thumbnail field comes back with type "media", unique false, default null, min null, max null and options []
Scenario Outline: A media field refuses options it can't have
Given a valid jwt cookie for admin 2
When the client sends POST /v1/content-type with a media field that has <option>
Then the response status is 422
And the response body is "invalid_field"
And no content type is stored
Examples:
| option |
| unique true |
| default 7 |
| default "lime" |
| min 1 |
| max 5 |
| options ["a"] |
Scenario: The type of a saved media field never changes
Given the type "event" has an entry and a saved media field "thumbnail"
When admin 2 sends PUT /v1/content-type/event turning "thumbnail" into a text field
Then the response status is 422 with invalid_field and the schema is unchanged
When admin 2 sends PUT turning the text field "title" into a media field
Then the response status is 422 with invalid_field and the schema is unchanged
Scenario Outline: Adding a media field to a type that has entries
Given the type "event" has 12 entries
When admin 2 sends PUT /v1/content-type/event adding a media field "thumbnail" that is <required>
Then the response status is <status>
And the response body is <message>
And the stored schema is <outcome>
Examples:
| required | status | message | outcome |
| required | 409 | schema_incompatible | unchanged |
| optional | 200 | | updated |
Scenario: Making a media field required
Given the type "event" has a saved optional media field "thumbnail", one entry with image 7 and one entry with null
When admin 2 sends PUT making "thumbnail" required
Then the response status is 409 with schema_incompatible
When the entry holding null is deleted and the PUT is sent again
Then the response status is 200
Scenario: Making a media field required while a stored image is gone
Given the type "event" has a saved optional media field "thumbnail" and one entry holding the id of a deleted image
When admin 2 sends PUT making "thumbnail" required
Then the response status is 200
Scenario: Creating an entry with an image
Given a valid jwt cookie for admin 2
When the client sends POST /v1/content-type/event/entry with {"data":{"title":"Lime plaster workshop","thumbnail":7}}
Then the response status is 201
And data.thumbnail is 7
And media is {"thumbnail":{"id":7,"filename":"lime-plaster.jpg","width":1600,"height":900,"size":240000,"thumbnail_url":"<the image path>"}}
Scenario Outline: An empty optional media field
When the client sends POST /v1/content-type/event/entry with <data>
Then the response status is 201
And data.thumbnail is <stored>
And media is {}
Examples:
| data | stored |
| {"data":{"title":"A","thumbnail":null}} | null |
| {"data":{"title":"A"}} | absent |
Scenario Outline: Entry values that break a media field are refused and store nothing
Given the type "event" has a media field "thumbnail" that is <required>
When the client sends POST /v1/content-type/event/entry with <data>
Then the response status is 422
And the response body is <message>
And no entry exists
Examples:
| required | data | message |
| required | {"data":{"title":"A"}} | invalid_entry: thumbnail: required |
| required | {"data":{"title":"A","thumbnail":null}} | invalid_entry: thumbnail: required |
| optional | {"data":{"title":"A","thumbnail":999}} | invalid_entry: thumbnail: type |
| optional | {"data":{"title":"A","thumbnail":"7"}} | invalid_entry: thumbnail: type |
| optional | {"data":{"title":"A","thumbnail":0}} | invalid_entry: thumbnail: type |
| optional | {"data":{"title":"A","thumbnail":-1}} | invalid_entry: thumbnail: type |
| optional | {"data":{"title":"A","thumbnail":7.5}} | invalid_entry: thumbnail: type |
| optional | {"data":{"title":"A","thumbnail":4294967296}} | invalid_entry: thumbnail: type |
| optional | {"data":{"title":"A","thumbnail":true}} | invalid_entry: thumbnail: type |
| optional | {"data":{"title":"A","thumbnail":[7]}} | invalid_entry: thumbnail: type |
Scenario: Replacing the image of an entry
Given the entry 5 of type "event" holds thumbnail 7
When a verified user sends PUT .../entry/5 with {"data":{"title":"Lime plaster workshop","thumbnail":8}}
Then the response status is 200, data.thumbnail is 8 and media.thumbnail.filename is "bathroom-tiles.png"
When the user sends PUT with thumbnail null on an optional field
Then data.thumbnail is null and media is {}
Scenario: An image deleted after the entry was saved
Given the entry 5 holds thumbnail 7
When DELETE /v1/media/7 answers 204
And the client sends GET /v1/content-type/event/entry/5
Then data.thumbnail is still 7
And media is {"thumbnail":{"id":7,"missing":true}}
Scenario: An unchanged id whose image is gone can still be saved when the field is optional
Given the entry 5 holds thumbnail 7 and the image 7 was deleted
When the user sends PUT .../entry/5 with a new title and thumbnail 7
Then the response status is 200 and data.thumbnail is 7
And media.thumbnail is {"id":7,"missing":true}
Scenario Outline: A changed value must exist even when the old one is gone
Given the entry 5 holds thumbnail 7 and the image 7 was deleted
When the user sends PUT .../entry/5 with thumbnail <value>
Then the response status is <status> and the body is <message>
Examples:
| value | status | message |
| 999 | 422 | invalid_entry: thumbnail: type |
| 8 | 200 | |
| null | 200 | |
Scenario Outline: A required media field with a missing image can't be saved as is
Given the entry 5 of a type whose "thumbnail" is required holds thumbnail 7 and the image 7 was deleted
When the user sends PUT .../entry/5 with thumbnail <value>
Then the response status is <status> and the body is <message>
And the stored entry is <outcome>
Examples:
| value | status | message | outcome |
| 7 | 422 | invalid_entry: thumbnail: required | unchanged |
| null | 422 | invalid_entry: thumbnail: required | unchanged |
| 8 | 200 | | updated |
Scenario: A create always treats the value as changed
Given the image 7 was deleted
When the client sends POST with thumbnail 7
Then the response status is 422 with invalid_entry: thumbnail: type
Scenario: Two broken fields name only one
Given a body with a required field left empty and a media field pointing at a missing image
When the client sends POST
Then the response names one field, with the required and type rules of Validate checked before the library existence
Scenario: Entry list responses carry the media object per item
Given 3 entries: one with image 7, one with image 7 deleted, one with null
When the client sends GET /v1/content-type/event/entry
Then each item keeps its seven keys and adds "media"
And the items' media are one existing object, {"thumbnail":{"id":7,"missing":true}} and {}
And items, total, page and size are unchanged
Scenario: Types without a media field are not enriched
Given the type "recipe" has no media field
When the client sends GET on a recipe entry
Then the body has the seven existing keys and "media" is {}
And the image repository is not called
Scenario: Media list items count entries as uses
Given the image 8 is used by 3 entries (one of them through two media fields) and by no article, author or site
And the image 7 is used by 2 articles and 5 entries
When the client sends GET /v1/media/
Then item 8 has used_in 3 and item 7 has used_in 7
And GET /v1/media/8 has used_in 3
And ?filter=unused does not list 8 or 7, and counts.unused does not count them
Scenario: Usage of an image lists articles and entries
Given the image 7 is used by article 12 "Heat pumps" (cover) and by entries 41, 42 and 43 of "event" and entry 9 of "workshop"
When the client sends GET /v1/media/7/usage
Then the response status is 200 and the body is a JSON array
And the article item is {"type":"article","id":12,"title":"Heat pumps","published":true,"fields":["cover"]}
And the entry items follow in the order event 41, 42, 43, then workshop 9 (content type name, then id), each with exactly type, id, fields ["thumbnail"], content_type_key, content_type_name and first_field, and no title and no published
And a client counts the array for the total
Scenario Outline: The raw first field in usage
Given an entry whose first field "<key>" is of type <type> and holds <stored>
When the client reads the usage of an image the entry uses
Then the entry item first_field is {"key":"<key>","type":"<type>","value":<value>}
And no string is built by the server and the item has no "title" key
Examples:
| key | type | stored | value |
| title | text | "Lime plaster workshop" | "Lime plaster workshop" |
| body | richtext | "\n\nFirst line\n\nSecond" | "\n\nFirst line\n\nSecond" |
| seats | number | 18 | 18 |
| category | select | "Talk" | "Talk" |
| online | boolean | false | false |
| starts_on | date | "2026-11-21" | "2026-11-21" |
| title | text | null | null |
| title | text | the key absent | null |
| cover | media | 7 | 7 |
Scenario: Usage of an unused or unknown image
When the client sends GET /v1/media/8/usage with no use
Then the body is []
When the client sends GET /v1/media/999/usage
Then the response status is 404 with apperr.ImageNotFoundErrorMessage
When the client sends GET /v1/media/abc/usage
Then the response status is 400 with apperr.IdUint32ErrorMessage
Scenario: Deleting an image used by entries is allowed
Given the image 7 is used by 5 entries and 2 articles
When the client sends DELETE /v1/media/7
Then the response status is 204
And the 2 articles lose the image reference as today
And the 5 entries still hold data.thumbnail 7 and are not modified (updated_at and updated_by unchanged)
Scenario: Merging duplicates repoints entry media
Given the images 7 and 9 share the same sha256 and entries 41 and 42 point at 9
When the client sends POST /v1/media/merge with keep_id 7 and merge_ids [9]
Then the response status is 200
And entries 41 and 42 hold thumbnail 7, with created_by, updated_by and updated_at unchanged
And image 9 no longer exists
Scenario: A failure while repointing entries stops the merge
Given the entry repository fails on the second Update
When the client sends POST /v1/media/merge
Then the response status is 500, the entries already repointed are restored, and no image is removed
Scenario: The purge plan counts entries as uses
Given the duplicate group 7, 9 where only 9 is used (by 1 entry)
When the purge preview and the purge run
Then 9 is the kept image and 7 is the merged copy
Scenario: Use case level
Given fake contenttype, entry and image repositories
Then entry.Validate returns an error satisfying errors.Is(err, entry.ErrInvalidEntry) with Key "thumbnail" and Rule "required" or "type" for the shapes above
And CreateEntry and UpdateEntry return the same for a missing library image and perform no Create or Update
And UpdateContentType returns contenttype.ErrSchemaIncompatible for a new required media field and does not call Update
And contenttype.ValidateFields returns contenttype.ErrInvalidField for a media field with unique, default, min, max or options
+59
View File
@@ -0,0 +1,59 @@
# QA procedure: media field type (slice A, API only)
Package: `test` (black-box). No live server, no real SQLite file, no real SMTP, no SPA.
## Setup shared by every case
1. Call `validator.InitValidator()` once per test.
2. Reuse the fakes of the custom content type pair (`mockContentTypeRepo`, `mockEntryRepo`) and of the media tests (image, article, site, author, variant file, storage, recorder fakes). Name any new fake uniquely across the package, for example `mockMediaFieldImageRepo`. The image fake must expose `Get`, a `getCalls` counter and a `delete(id)` helper.
3. `mockEntryRepo` needs no new method (no repository method is added). Give it an `updateCalls` counter and a `failUpdateOn(n)` switch for the merge compensation case.
4. Build `NewHandler(...)` for the entry, content type and media handlers over use cases wired to the fakes (the entry use cases now take the image fake). Mount them on a fresh `chi.NewRouter()` mirroring api/router.go: `/v1/content-type` and `/v1/media`, with `jwtauth.Verifier`, `jwtauth.Authenticator` and a test `jwtauth.New("HS256", []byte("test-secret"), nil)`. Add `RequireOwnerOrAdmin` on the content type write routes. If `api.InitBackendRoutes` with a partial `*api.UseCases` works, prefer it.
5. Seed users: admin 2 and a plain verified user. Seed images 7 "lime-plaster.jpg" (1600x900, 240000 bytes) and 8 "bathroom-tiles.png" (800x600, 51200 bytes), with distinct paths. Seed the type "event" (title text required, thumbnail media optional) and a variant with thumbnail required.
6. Inject a fake clock so `updated_at` > `created_at`.
7. Decode entry and list bodies into `map[string]any`; compare numbers as `float64`.
## Schema
8. POST a media field with the allowed shape -> 201; the field has type "media", unique false, default/min/max null, options [].
9. Table of refused options (unique true, default 7, default "lime", min 1, max 5, options ["a"]) -> 422 `invalid_field`, repo empty. Assert separately that `default: null` is accepted.
10. Type change in both directions on a type with entries -> 422 `invalid_field`, schema byte-identical. On a type with no entries the existing free type change still applies.
11. Add a media field to a type with 12 entries: required -> 409 `schema_incompatible`, schema unchanged; optional -> 200, existing entries still readable and `media` is `{}`. Make an optional media field required: 409 while an entry holds null, 200 once none does. Making it required while an entry holds an id of a deleted image -> 200 (compatibility does not consult the library).
## Entry writes
12. POST with image 7 -> 201; `data.thumbnail` is 7 and `media.thumbnail` has exactly `id`, `filename`, `width`, `height`, `size`, `thumbnail_url`; the key set of the entry is the seven existing keys plus `media`.
13. POST with null and with the key absent on an optional field -> 201, `media` is `{}` (assert JSON `{}`, not null).
14. Refusal table (required: absent, null; any: 999, "7", 0, -1, 7.5, 4294967296, true, [7]): status 422, exact body `invalid_entry: thumbnail: <rule>`, `createCalls == 0`.
15. PUT replace 7 -> 8: 200, filename "bathroom-tiles.png". PUT to null on optional: 200, `media` is `{}`.
16. After `delete(7)` on the image fake: GET entry 5 -> `data.thumbnail` 7 and `media.thumbnail` equals `{"id":7,"missing":true}` (no other key). PUT with the same 7 on an optional field -> 200, still 7 and still missing. PUT 999 -> 422 type, PUT 8 or null -> 200.
17. Required field, image 7 deleted: PUT 7 -> 422 `required`, PUT null -> 422 `required`, entry unchanged; PUT 8 -> 200.
18. POST with a deleted id 7 -> 422 `type` (create is always a changed value).
19. Ordering: a body with two bad fields names one only: Validate rules first in field order, then the existence check.
## Reads
20. List: 3 entries (existing image, deleted image, null) -> each item has the seven keys plus `media`; values as in the feature; `total`, `page` and `size` unchanged; `items` is `[]` for an empty type.
21. A type without a media field: `media` is `{}` and `getCalls == 0` on the image fake. A list of 100 entries pointing at the same image calls `Get` at most once for that id.
## Media library counts
22. Seed: image 8 used by 3 entries (one through two media fields) and no other use; image 7 used by 2 articles and 5 entries. `GET /v1/media/` -> `used_in` 3 and 7; `GET /v1/media/8` -> 3; `?filter=unused` omits both; `counts.unused` excludes both; an image with no use is still counted unused.
23. Unchanged existing cases: article, author and site usage counts and the unused counts still pass with no entries in the fake.
## Usage endpoint
24. Image 7 with article 12 (cover), entries 41, 42, 43 of "event" and entry 9 of "workshop": status 200, a JSON array, article item unchanged (keys type, id, title, published, fields). Entry items have exactly the keys `type`, `id`, `fields`, `content_type_key`, `content_type_name`, `first_field`, and no `title` and no `published`. Order: article, then event 41, 42, 43, then workshop 9.
25. Raw first-field table (text, richtext with leading blank lines, number 18, select, boolean false, date, text null, key absent, media 7). Assert `first_field` is exactly `{key, type, value}` with the value byte-equal to the stored JSON (richtext unmodified, number as a JSON number, null as JSON `null`). Assert the entry item JSON has no `title` key.
26. Unused image -> `[]`; unknown -> 404 `image_not_found` text; `abc` -> 400 `apperr.IdUint32ErrorMessage`.
## Delete and merge
27. DELETE /v1/media/7 used by 5 entries and 2 articles -> 204; articles cleared as before; the fake entry repo records no Update; the 5 entries are byte-identical.
28. Merge keep 7, merge [9] with equal sha256 and two entries on 9 -> 200; the entries hold 7; `created_by`, `updated_by` and `updated_at` are unchanged; image 9 is gone. Entries pointing at other images are untouched.
29. Merge with `failUpdateOn(2)` -> 500, the first repointed entry is restored to 9, no image deleted, articles/sites/authors repointing rolled back as today.
30. Purge preview and run on a duplicate group where only the copy is used by an entry: the used copy is the kept one; the fingerprint changes accordingly.
## Use case level (no HTTP)
31. `contenttype.ValidateFields` -> `ErrInvalidField` for each refused option. `entry.Validate` rows -> `errors.Is(err, entry.ErrInvalidEntry)` with the right key and rule. `CreateEntry`/`UpdateEntry` with a missing library image -> same error and no write. `UpdateContentType` with a new required media field -> `ErrSchemaIncompatible`, no `Update`.
## Existing tests to amend
32. Amend the existing key-set assertions from seven to eight keys in the earlier custom content type and entry feature, spec and test files (decision: `media` is always present). The coder owns this.
## Manual verification (not exercised by the Go tests)
- Real SQLite, then MySQL/MariaDB and PostgreSQL via the driver tasks: create a type with a media field, upload an image, save an entry, delete the image, reload the entry and confirm the id stays and `media` is `{missing:true}`.
- Merge duplicates with entries on a copy against real storage and confirm the entries repoint and the file is removed.
- Time `GET /v1/media/` with 1,000 entries across a type with a media field (usage lookup loads the entries of such types).
- The SPA (builder, editor control, picker, list cell, library badge and detail panel) is slices B and C and is not checked here.
+2 -2
View File
@@ -363,11 +363,11 @@ Feature: The media library holds every uploaded image as a library-level asset
And article 1's body is back to its original text, article 2 is unchanged And article 1's body is back to its original text, article 2 is unchanged
And images 2 and 3 still exist And images 2 and 3 still exist
Scenario: A failure deleting a copy after the rewrite is 500 and the bodies stay switched Scenario: A failure deleting a copy after the rewrite is 500 and the bodies are rolled back
Given the image repository's Delete fails for image 3 Given the image repository's Delete fails for image 3
When the client sends POST /v1/media/merge with {"keep_id": 2, "merge_ids": [3]} When the client sends POST /v1/media/merge with {"keep_id": 2, "merge_ids": [3]}
Then the response status is 500 Then the response status is 500
And article 1's and article 2's bodies use image 2's url and image 3 still exists And article 1's and article 2's bodies are back to their original text and image 3 still exists
@manual @manual
Rule: Startup backfill and migration (persistence, verified by hand, see the qa.md) Rule: Startup backfill and migration (persistence, verified by hand, see the qa.md)
+1 -1
View File
@@ -26,7 +26,7 @@ Package: `test` (black-box). New file `test/media_library_http_test.go`. Fake ty
13. Rename: assert 200 with the new filename, the same `url`, the article body unchanged, and every invalid row -> 400 with `"Enter a filename.\n"` for the filename rows; 404 for 9999; 400 with `apperr.IdUint32ErrorMessage` for `abc`. Assert the repository filename is unchanged after each 400. 13. Rename: assert 200 with the new filename, the same `url`, the article body unchanged, and every invalid row -> 400 with `"Enter a filename.\n"` for the filename rows; 404 for 9999; 400 with `apperr.IdUint32ErrorMessage` for `abc`. Assert the repository filename is unchanged after each 400.
14. Delete: in-use image -> 204 with an empty body, article bodies byte-identical, `deleteCalls == [1]`; 404, 400, 500 rows. The "file already gone" case is a persistence behaviour and is a manual item. 14. Delete: in-use image -> 204 with an empty body, article bodies byte-identical, `deleteCalls == [1]`; 404, 400, 500 rows. The "file already gone" case is a persistence behaviour and is a manual item.
15. Usage: assert the exact JSON arrays (raw body compared as JSON), the empty `[]`, the absolute-url article, 404 and 400. 15. Usage: assert the exact JSON arrays (raw body compared as JSON), the empty `[]`, the absolute-url article, 404 and 400.
16. Merge: assert 200 `{articles_updated, merged}`, resulting bodies (both occurrences replaced), unchanged bodies for the other articles, and only image 2 left. Assert the 409 rows and 404 row, with no body change and no `Delete` calls (`deleteCalls` empty). Assert every 400 row with `apperr.MediaMergeRequestErrorMessage`. Assert the two failure rows: `UpdateBody` failing for article 2 leaves article 1 restored and no `Delete` call; `Delete` failing for image 3 leaves bodies switched and returns 500. 16. Merge: assert 200 `{articles_updated, merged}`, resulting bodies (both occurrences replaced), unchanged bodies for the other articles, and only image 2 left. Assert the 409 rows and 404 row, with no body change and no `Delete` calls (`deleteCalls` empty). Assert every 400 row with `apperr.MediaMergeRequestErrorMessage`. Assert the two failure rows: `UpdateBody` failing for article 2 leaves article 1 restored and no `Delete` call; `Delete` failing for image 3 returns 500 and rolls the bodies back to their original text, with image 3 still present.
17. Unit-level asserts (same file, no HTTP) with `errors.Is` on the sentinels `ErrImageUnreadable`, `ErrMergeCopyMissing`, `ErrMergeHashMismatch`, `ErrInvalidFilename`. 17. Unit-level asserts (same file, no HTTP) with `errors.Is` on the sentinels `ErrImageUnreadable`, `ErrMergeCopyMissing`, `ErrMergeHashMismatch`, `ErrInvalidFilename`.
18. Layering guard: `go list -deps` or a grep-style test that `api/handlers/media` imports no `persistence`, `mailer`, `models` or `gorm` package. 18. Layering guard: `go list -deps` or a grep-style test that `api/handlers/media` imports no `persistence`, `mailer`, `models` or `gorm` package.
+274
View File
@@ -0,0 +1,274 @@
Feature: Media merge hardening: atomic merge, no lost entry edits, one entry scan per purge
As a site owner or admin
I want a duplicate merge to either fully happen or not happen at all
So that a failure halfway never leaves articles, sites, authors, entries or the library half merged
Background:
Given this slice is backend only: no route, request body, response body, status code, error text or audit payload changes
And internal/domain gains a unit-of-work port (package transaction): Transactor with Run(ctx, func(Repositories) error) error, and Repositories holding the article, site, author, entry and image repositories bound to the open transaction
And internal/domain/transaction imports only the stdlib and other internal/domain/* packages
And Run commits when the function returns nil and rolls everything back when it returns an error or panics, and returns that error unchanged
And the GORM adapter lives in internal/infrastructure/persistence, asserts var _ transaction.Transactor = &X{}, and is built only in api/dependecyInjection.go
And SQL in the adapter stays portable across SQLite, MySQL/MariaDB and PostgreSQL
And MergeMedia and RunPurge depend on transaction.Transactor and never on persistence, gorm or models
And MergeMedia keeps its order: validate, load copies, plan which articles contain a copy name, then inside one transaction re-read each planned article body, apply the replacement of the copy names by the kept name to that re-read body and UpdateBody it, articles RepointImage, sites RepointImage, authors RepointAvatar, entry repoint and image row delete per copy
And restoreBodies, the entry restore of entryMediaScanner and every logCompensation call of the merge are deleted; nothing compensates by hand any more
And the stored file, the variant cache files and the variant cache rows of a merged copy are removed only after the transaction committed, through image.Storage and the variant file repository
And a failure removing those files after the commit is written to the injected *log.Logger, never rolled back, never changes the response or the audit event
And the audit event media.merge and the audit event media.purge are recorded outside the transaction, with the same params as today
And entries are repointed from candidates found by one scan (contenttype.Repository.List then entry.Repository.ListPage with Unpaged, filtered in Go), and each candidate is re-read with entry.Repository.Get inside the transaction before it is written
And an entry repoint only changes the media values that still point at a merged copy in the re-read data, keeps every other value of the re-read data, and leaves created_by, updated_by, created_at and updated_at untouched
And a candidate that no longer exists at re-read time is skipped
And RunPurge and PreviewPurge scan entries once per run and once per preview into an index of image id to entries, shared by the usage counts and by every duplicate group; the index is built in the use case and no repository method is added
And RunPurge runs one transaction per duplicate group, so a failing group rolls back alone and the other groups still merge
And the replacement of a copy name inside an article body matches whole stored file names only, so a name that is a suffix of another name is not rewritten inside it
And the media-field walks (field-type loops, the required and type rule constants, the entry.InvalidField wrapper) are deduplicated into one place; this is a pure refactor and has no scenario of its own beyond "behaviour unchanged"
And MergeMediaResult, purge.RunResult, the merge response {"articles_updated","merged"} (plus sites_updated and authors_updated where the sites and authors features already report them) and the 409, 404, 400 and 500 answers are unchanged
And fixtures: images 7, 8 and 9 share sha256 A with stored names; image 2 and 3 share sha256 B; the type "event" has title (text, required) then thumbnail (media, optional); users: admin 2 (verified)
Rule: A merge is all-or-nothing
Scenario Outline: Any failing step leaves the library exactly as it was
Given images 7 and 9 share sha256 A and 7 is the kept one
And article 1 and article 2 contain the stored name of image 9 in their bodies, article 3 has image 9 as its cover
And site 1 uses image 9 as its default social image and author 4 uses image 9 as its avatar
And entries 41 and 42 of "event" hold thumbnail 9
And <failing step> is armed to fail
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [9]}
Then the response status is 500 and the body is "Internal server error"
And the bodies of articles 1 and 2 are byte-identical to before
And article 3 still has cover 9, site 1 still uses 9, author 4 still uses avatar 9
And entries 41 and 42 still hold thumbnail 9 with updated_at and updated_by unchanged
And images 7 and 9 both still exist
And image.Storage.Delete and the variant file repository Delete are never called
And one failed media.merge audit event is recorded
Examples:
| failing step |
| the UpdateBody of the first article |
| the UpdateBody of the second article |
| the article repository RepointImage |
| the site repository RepointImage |
| the author repository RepointAvatar |
| the entry repository Get of the second entry |
| the entry repository Update of the second entry |
| the image repository Delete of image 9 |
| the commit of the transaction |
Scenario: The transaction cannot start
Given the transactor fails to begin
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [9]}
Then the response status is 500
And no repository other than the reads of the planning phase was called, and no file was touched
Scenario: Several copies roll back together
Given images 7, 8 and 9 share sha256 A and the image repository Delete fails for image 9 after image 8 was deleted
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [8, 9]}
Then the response status is 500
And image 8 exists again, image 9 exists and no article, site, author or entry changed
Scenario: A successful merge still does everything
Given the Background fixtures of the first scenario and no armed failure
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [9]}
Then the response status is 200 and the body is {"articles_updated": 3, "merged": 1} plus the existing sites_updated and authors_updated keys
And entries 41 and 42 hold thumbnail 7 with created_by, updated_by and updated_at unchanged
And image 9 is gone from the repository and its stored file is removed
Scenario: A validation or lookup error never opens a transaction
Given any of the existing 400, 404 or 409 merge requests
Then the transactor Run is not called
Scenario: A rollback leaves updated_at and updated_by of entries untouched
Given the entries 41 and 42 hold thumbnail 9 with known created_at, updated_at, created_by and updated_by
And the repoint of entry 42 fails
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [9]}
Then the response status is 500
And entries 41 and 42 are byte-identical to before, including updated_at and updated_by
Rule: Stored files are removed only after the commit
Scenario: Files are touched after the commit and never before
Given a merge of image 9 into image 7 that succeeds
Then image.Storage.Delete("<stored name of 9>") is called after the transaction committed
And the variant files of image 9 are removed after the commit
And at no time before the commit is a file or a variant cache row of image 9 removed
Scenario Outline: A file failure after the commit is logged, not rolled back
Given a merge of the copies 8 and 9 into image 7 where <file failure>
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [8, 9]}
Then the response status is 200 and the body is the same as without the failure
And images 8 and 9 are gone from the repository and the articles, sites, authors and entries stay repointed
And the removal of the other copy is still attempted
And the injected logger holds one line naming the stored name and the error
And the media.merge audit event is a success with the usual params
Examples:
| file failure |
| image.Storage.Delete fails for image 9 |
| the variant file purge of image 9 fails |
Scenario: A purge group with a file failure after the commit counts as purged
Given groups A and B are planned and image.Storage.Delete fails for a merged copy of group A
When the client sends POST /v1/media/purge with {}
Then the response status is 200 and the body has groups_purged 2 and failed_groups 0
And the merged count includes the copies of group A
And the injected logger holds the file failure
Rule: A concurrent entry edit survives a merge
Scenario: An edit made after the scan is kept
Given entry 41 of "event" is {"title": "Workshop", "thumbnail": 9}
And the entry repository changes entry 41 to {"title": "Workshop 2026", "thumbnail": 9}, with a new updated_at and updated_by, right after the scan returns it
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [9]}
Then the response status is 200
And entry 41 is {"title": "Workshop 2026", "thumbnail": 7}
And its updated_at and updated_by are the ones of the concurrent edit, not older ones
Scenario: A concurrent edit that moved the entry off the merged copy is not overwritten
Given entry 41 holds thumbnail 9 when scanned
And the entry repository changes entry 41 to thumbnail 8 right after the scan returns it
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [9]}
Then entry 41 still holds thumbnail 8
And the entry repository Update is not called for entry 41
Scenario: An entry deleted after the scan is skipped
Given entry 41 holds thumbnail 9 when scanned
And entry 41 is deleted right after the scan returns it
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [9]}
Then the response status is 200 and image 9 is gone
Scenario: Entries are written from the re-read data
Given entry 41 holds {"title": "A", "thumbnail": 9, "poster": 9} when scanned
When the merge runs
Then entry 41 holds thumbnail 7 and poster 7 and the same title
And the entry repository Update is called once for entry 41
Rule: A concurrent article edit survives a merge
Scenario: A body edited after planning is kept
Given article 1 contains the stored name of image 9 and the planning has read its body
And the article repository changes article 1 to the same text plus a new paragraph, right after the planning read returns it
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [9]}
Then the response status is 200
And article 1's body holds the new paragraph and the stored name of image 7 instead of image 9
Scenario: A body edited so that it no longer holds the copy name is not rewritten
Given article 1 contains the stored name of image 9 when planned
And the article repository changes article 1 to a text without the stored name of image 9 right after the planning read returns it
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [9]}
Then article 1's body is the edited text and the article repository UpdateBody is not called for article 1
And article 1 is not counted in "articles_updated"
Scenario: An article deleted after planning is skipped
Given article 1 contains the stored name of image 9 when planned
And article 1 is deleted right after the planning read returns it
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [9]}
Then the response status is 200 and image 9 is gone
Scenario: Only whole stored names are replaced
Given image 9 has the stored name "a.jpg" and article 1 contains "ba.jpg" and "a.jpg"
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [9]}
Then article 1 still contains "ba.jpg" and no longer contains the standalone "a.jpg"
Rule: A cancelled purge stops cleanly
Scenario: A request cancelled between groups stops the run
Given groups A, B and C are planned and the request context is cancelled after group A committed
When the purge runs
Then group A stays merged and groups B and C are untouched
And the run returns the context error and records no last_purge_* values and no media.purge success event
And failed_groups is not incremented for B and C
Scenario: The scheduler passes its context to the run
Given the scheduler context is cancelled while a scheduled purge is between groups
Then the run stops after the group in progress and records no last_purge_* values
Rule: A purge scans entries once
Scenario: A preview over many groups scans once
Given 6 planned duplicate groups, 40 entries and 2 content types with a media field
When the client sends GET /v1/media/purge-preview
Then contenttype.Repository.List is called once
And entry.Repository.ListPage is called once per content type with a media field, 2 times in all
And the response is the same as before this slice
Scenario: A run over many groups scans once
Given the same 6 groups, 40 entries and 2 content types with a media field
When the client sends POST /v1/media/purge with {}
Then contenttype.Repository.List is called once
And entry.Repository.ListPage is called 2 times in all, not once per group
And the response and the stored last_purge_* values are the same as before this slice
Scenario: The index is stale after a group but the result is right
Given entry 41 holds thumbnail 2 and poster 5, where 2 is a copy of group A and 5 is a copy of group B
When the client sends POST /v1/media/purge with {}
Then entry 41 holds the kept image of group A as thumbnail and the kept image of group B as poster
And entry.Repository.Update is called twice for entry 41
Scenario: The usage counts and the candidates come from the same scan
Given the duplicate group 7, 9 where only 9 is used, by 1 entry
When the purge preview and the purge run
Then 9 is the kept image and 7 is the merged copy
And there is one scan per call
Rule: A purge run commits one group at a time
Scenario Outline: A failing group rolls back alone
Given groups A, B and C are planned, in that order
And <failure> is armed for group B
When the client sends POST /v1/media/purge with {}
Then the response status is 200
And the body is {"groups_total": 3, "groups_purged": 2, "merged": <copies of A and C>, "articles_updated": <distinct articles of A and C>, "failed_groups": 1}
And all of group B's article bodies, entries, sites, authors and images are back to their original state
And groups A and C are merged
And the stored last_purge_merged and last_purge_articles_updated equal the response totals
Examples:
| failure |
| the UpdateBody of the second article |
| the article repository RepointImage |
| the entry repository Update |
| the image repository Delete of a merged copy |
Scenario: Every group failing is still a 200
Given every group is armed to fail
When the client sends POST /v1/media/purge with {}
Then the response status is 200
And groups_purged is 0 and failed_groups equals groups_total
And no image, body, entry, site or author changed and the stored last_purge_at is set
Scenario: The run opens one transaction per planned group
Given 3 planned groups
When the client sends POST /v1/media/purge with {}
Then the transactor Run is called 3 times
Rule: Behaviour unchanged (the media-field walk refactor)
Scenario: The shared walk changes nothing
Given the media-field rule constants, the InvalidField wrapper and the walks over a content type's media fields live in one place
Then every scenario of features/media_field_type.feature, media_library.feature and media_purge.feature passes unchanged, except the two amended below
Rule: Amendments to earlier features
Scenario: media_library.feature "A failure deleting a copy after the rewrite is 500 and the bodies are rolled back" is amended
Given the image repository's Delete fails for image 3
When the client sends POST /v1/media/merge with {"keep_id": 2, "merge_ids": [3]}
Then the response status is 500
And article 1's and article 2's bodies are back to their original text and image 3 still exists
Scenario: media_purge.feature "A group that fails after rewriting bodies" is amended
Given the image repository's Delete fails for a merged image of group A, and group B is planned
When the client sends POST /v1/media/purge with {}
Then the response status is 200, "failed_groups" is 1 and "groups_purged" is 1
And group A contributes 0 to "merged" and none of its article ids to "articles_updated"
And group A's article bodies are back to their original text
And a following GET /v1/media/purge-preview plans group A again, and the next run converges
@manual
Rule: Persistence (verified by hand, see the qa.md)
Scenario: The GORM adapter rolls back on SQLite, MySQL/MariaDB and PostgreSQL
Given duplicates with articles, a site, an author and entries pointing at a copy
When a merge fails at the image delete on each driver
Then no row changed on any of the three drivers
+80
View File
@@ -0,0 +1,80 @@
# QA procedure: media_merge_hardening
Package: `test` (black-box). New file `test/media_merge_hardening_test.go`. Go only: no SPA, no env var, no live server, no real SQLite file, no real SMTP. Fake type names must be unique in the package.
## Setup shared by every case
1. Call `validator.InitValidator()` once per test.
2. Reuse the fakes of the media tests and the purge tests: `mockImageRepo`, `mockArticleRepo`, the site, author and storage fakes, the variant file fake, the audit recorder fake, `mockContentTypeRepo`, `mockEntryRepo`, `mockPurgeSettingsRepo`, and the helpers `seedGroup` and `articleUsing`.
3. New fake `mockMergeTransactor` (implements `transaction.Transactor`):
- It holds the fakes of step 2 and hands them to the function as the `Repositories` struct. In-memory fakes need no real binding to the transaction.
- Rollback emulation: before calling the function it snapshots the state of every fake it holds (a deep copy of their maps), and it restores the snapshots when the function returns an error. Counters (`updateCalls`, `getCalls`, `deleteCalls`) are NOT restored, so tests can still assert that calls happened.
- Switches: `failBegin`, `failCommit`. `failCommit` restores the snapshots and returns the error after the function returned nil.
- Fields: `runCalls`, and a `committed bool` that is true only between the commit and the next Run.
- Each fake gains `snapshot()` and `restore()` helpers in the test package only; no production code change.
4. Fake extensions (no new method on a domain interface):
- `mockEntryRepo`: `listPageCalls`, `getCalls`, `failUpdateOn(n)` (already exists), `failGetOn(n)`, and `afterListPage func()` called right after `ListPage` builds its result, used to mutate or delete an entry after the scan.
- `mockContentTypeRepo`: `listCalls`.
- `mockArticleRepo`: failure switches for `UpdateBody` (per id and per call number) and `RepointImage`.
- Site and author fakes: failure switches for `RepointImage` and `RepointAvatar`.
- `mockImageRepo`: `Delete` with `failDeleteFor`.
- Storage fake: records `Delete` calls, with a failure switch per stored name; each record notes `transactor.committed` at call time.
- Variant file fake: the same recording and failure switch.
5. Build `NewMergeMediaUseCase(...)` with the transactor, storage, variant files, recorder, the fakes, an injected `*log.Logger` over a `bytes.Buffer`, and `NewRunPurgeUseCase` / `NewPreviewPurgeUseCase` over the same fakes. The constructors are chosen by the coder. Mount the media handler on a fresh `chi.NewRouter()` mirroring `NewMediaRouter` in api/router.go, with the media_purge.qa.md setup, `jwtauth.New("HS256", []byte("test-secret"), nil)` and an admin 2 cookie. Compare error bodies as `message + "\n"`.
6. Seed: images 7, 8 and 9 (same sha256 A), 2 and 3 (sha256 B). The type "event" has title and thumbnail (media, optional), plus a second type with two media fields (thumbnail, poster) for the walk and index cases. Seed articles, a site and an author that point at the copies. Inject a fixed clock so entry `updated_at` is known.
7. Snapshot helper `libraryState()` deep-copying every fake. Assert "unchanged" with `reflect.DeepEqual` of before and after.
## All-or-nothing
8. Failing step table (the 9 rows of the first outline), one subtest per row. Arm the failure, POST `/v1/media/merge` with keep 7 and merge [9]. Assert 500 and "Internal server error\n". Assert `libraryState()` equals the state before, including bodies, cover ids, site and author references, entries with `updated_at` and `updated_by`, and both image rows. Assert the storage fake and the variant fake recorded no `Delete` call. Assert exactly one failed `media.merge` audit event. Use `failCommit` for the commit row.
9. `failBegin`: 500, no write call on any fake, no file call.
10. Two copies (8 and 9), `failDeleteFor(9)` after 8 was deleted: 500, image 8 exists again after rollback, all else unchanged.
11. Success path: 200 and the unchanged body, entries 41 and 42 hold 7 with `created_by`, `updated_by`, `created_at` and `updated_at` unchanged, image 9 gone, the storage fake got `Delete`, and the audit event is a success with `merged` and `articles_updated`.
12. Validation, lookup and 409 requests (all existing 400, 404, 409 cases): `runCalls == 0`.
13. Rollback and `updated_at` / `updated_by`: arm `failUpdateOn(2)` on the entry fake, assert both entries are `DeepEqual` to the seed.
## Files after commit
14. Success: the storage fake `Delete` record has `committed == true` for every call; the variant fake records likewise. Failure rows of step 8: no records at all.
15. File failure table (storage `Delete` fails for 9; variant purge fails for 9) with copies 8 and 9: 200 and the same body as the no-failure run, images gone, repoints kept, the other copy's removal still attempted, the log buffer holds one line with the stored name and the error text, the audit event is a success with the usual params.
16. Purge group with a storage failure after commit: 200, `groups_purged` 2, `failed_groups` 0, merged count includes the copies of group A, the log buffer holds the failure.
## Concurrent entry edit
17. Edit after the scan: set `afterListPage` to rewrite entry 41 to a new title with new `updated_at` and `updated_by`. After the merge, entry 41 has the new title, thumbnail 7 and the edit's `updated_at` and `updated_by`.
18. Edit that moves the entry to image 8 after the scan: entry 41 still holds 8 and the entry fake saw no `Update` for 41.
19. Entry deleted after the scan: 200, image 9 gone, no error.
20. Re-read data: an entry with thumbnail 9 and poster 9: both become 7, the title is kept, `Update` is called once for that entry.
## Concurrent article edit
17a. `mockArticleRepo` gains `afterFindByBody func()` called right after `FindByBodyContaining` builds its result. Edit after planning: article 1 gets an extra paragraph; after the merge it holds the paragraph and the kept stored name. Edit removing the copy name: no `UpdateBody` for article 1, not in `articles_updated`. Article deleted after planning: 200, image 9 gone. Suffix collision (`a.jpg` inside `ba.jpg`): `ba.jpg` untouched. Add a property-style table for the replacement helper (identity without the copy name, idempotence, kept name never removed).
## Cancelled purge
17b. Cancel the context from a fake hook after group A commits: A merged, B and C untouched, `Execute`/`Run` return the context error, `failed_groups` unchanged, no `last_purge_*` saved, no success `media.purge` audit event. Scheduler: `Execute` receives the scheduler context (no more `context.Background()`), cancelled between groups it stops the same way.
## One scan per run and per preview
21. Preview over 6 groups, 40 entries, 2 media types: `contenttype listCalls == 1`, `entry listPageCalls == 2`. Body equals the body from before the slice (same seed in an existing test).
22. Run over the same seed: `listCalls == 1`, `listPageCalls == 2`, and the response and stored `last_purge_*` match.
23. Stale index: an entry with thumbnail in group A and poster in group B ends with both kept ids, `Update` called twice for it.
24. Media-used-only-by-entry group (existing step 30 of media_field_type.qa.md): the used copy is kept, the preview and the run each scan once.
## Purge per group
25. Failure table (UpdateBody of the second article, article RepointImage, entry Update, image Delete for a merged copy) armed for group B in plan order A, B, C: 200 and the counters of the feature, group B fully rolled back, A and C merged, `Save` counters equal the response.
26. All groups failing: 200, `groups_purged` 0, `failed_groups == groups_total`, state unchanged, `last_purge_at` saved.
27. Three groups: `transactor.runCalls == 3`.
## Amended existing tests (the coder owns them)
28. media_library test "failure deleting a copy": bodies are now restored and image 3 still exists. media_purge step 30: group A's bodies are restored (no longer switched), failed_groups 1, groups_purged 1, A contributes 0, the next run converges.
29. Every other existing test passes unchanged. Constructors of `MergeMedia`, `RunPurge` and `PreviewPurge` gain the transactor and logger; update the call sites in tests only.
## Behaviour unchanged (walk refactor)
30. No new case. Run the full existing suites (`task test`) and require them to pass, as the pure-refactor proof.
## Layering guards
31. `internal/domain/transaction` imports only the stdlib and `internal/domain/*`. The use cases import no `persistence`, `gorm`, `models` or `net/http`. The GORM adapter asserts `var _ transaction.Transactor = &X{}` and is constructed only in api/dependecyInjection.go. Use the grep-style test of media_purge.qa.md.
## Manual verification (not exercised by the Go tests)
- Real SQLite, then MySQL/MariaDB and PostgreSQL via the driver tasks: seed duplicates with articles, a site, an author and entries on a copy; make the image delete fail (for example a read-only DB or a trigger); confirm no row changed.
- Real merge against real uploads: the copy's file and variant files are gone after a 200, and still present after a forced failure.
- Concurrent merge and entry edit with two shells (curl with the jwt cookie): the edit survives.
- Time `POST /v1/media/purge` with many groups and 1,000 entries (one scan, not one per group).
- Check that a SQLite transaction does not deadlock with the connection settings in `persistence/database` (all reads inside the transaction go through the tx-bound repositories).
## Decisions accepted by the user
Amend the two earlier scenarios; a file failure after commit is 200 plus a log line (injected `*log.Logger`); one transaction per purge group; entries scanned then re-read per candidate inside the transaction; article bodies are re-read and rewritten inside the transaction (the user chose to fix the body race: the plan only decides which articles change); a purge cancelled by its context stops between groups without recording a run; entries created after the scan that point at a copy are not repointed (accepted limitation, shown as missing); adapter verified by hand, Go tests use fakes with snapshot/restore rollback.
+3 -2
View File
@@ -342,11 +342,12 @@ Feature: Owners and admins can merge duplicate images in use, with persisted pur
And group B's UpdatedArticleIDs is empty, so no article of group B is in "articles_updated" And group B's UpdatedArticleIDs is empty, so no article of group B is in "articles_updated"
And the stored last_purge_merged and last_purge_articles_updated equal the response totals And the stored last_purge_merged and last_purge_articles_updated equal the response totals
Scenario: A group that fails after rewriting bodies is reported as failed and contributes nothing Scenario: A group that fails after rewriting bodies is rolled back, reported as failed and contributes nothing
Given the image repository's Delete fails for a merged image of group A, and group B is planned Given the image repository's Delete fails for a merged image of group A, and group B is planned
When the client sends POST /v1/media/purge with {} When the client sends POST /v1/media/purge with {}
Then the response status is 200, "failed_groups" is 1 and "groups_purged" is 1 Then the response status is 200, "failed_groups" is 1 and "groups_purged" is 1
And group A contributes 0 to "merged" and its article ids are not added to "articles_updated", even though its article bodies stay switched to the kept copy And group A contributes 0 to "merged" and its article ids are not added to "articles_updated"
And group A's article bodies are back to their original text
And "articles_updated" and "merged" count only the fully merged group B And "articles_updated" and "merged" count only the fully merged group B
And a following GET /v1/media/purge-preview plans group A again, and the next run converges because the plan is recomputed from current data And a following GET /v1/media/purge-preview plans group A again, and the next run converges because the plan is recomputed from current data
+1 -1
View File
@@ -57,7 +57,7 @@ Package: `test` (black-box). New files `test/media_purge_http_test.go` and `test
27. Fingerprint: match gives 200. A stale fingerprint gives 409 with `apperr.PurgeConflictErrorMessage + "\n"`, no `Delete`, no `UpdateBody`, no `Save`. A garbage string gives 409 with the same body. No fingerprint, `{}` and an empty body all run. 27. Fingerprint: match gives 200. A stale fingerprint gives 409 with `apperr.PurgeConflictErrorMessage + "\n"`, no `Delete`, no `UpdateBody`, no `Save`. A garbage string gives 409 with the same body. No fingerprint, `{}` and an empty body all run.
28. Empty plan: 200 zeros, `Save` with `last_purge_at` = clock and zero counters, and a run with the empty plan's fingerprint is also 200. 28. Empty plan: 200 zeros, `Save` with `last_purge_at` = clock and zero counters, and a run with the empty plan's fingerprint is also 200.
29. Partial failure, rolled back: arm `UpdateBody` to fail for the second article of group B (plan order A, B, C). Assert the body counters, B's bodies restored byte for byte, all B images present, A and C merged, B's articles absent from `articles_updated`, and `Save` counters equal the response. 29. Partial failure, rolled back: arm `UpdateBody` to fail for the second article of group B (plan order A, B, C). Assert the body counters, B's bodies restored byte for byte, all B images present, A and C merged, B's articles absent from `articles_updated`, and `Save` counters equal the response.
30. Partial failure, delete: arm `failDeleteFor` for one of group A's merged images and plan B too. Assert `failed_groups` 1, `groups_purged` 1, A contributes 0 to `merged` and none of its ids to `articles_updated` (only B counts), A's article bodies stay switched to the kept copy, and a following preview plans A again. Run the purge again with the failure disarmed and assert it converges (A's leftover copy is merged away). Then arm every `UpdateBody` and assert `groups_purged` 0, `failed_groups` = `groups_total` and `last_purge_at` still saved. 30. Partial failure, delete: arm `failDeleteFor` for one of group A's merged images and plan B too. Assert `failed_groups` 1, `groups_purged` 1, A contributes 0 to `merged` and none of its ids to `articles_updated` (only B counts), A's article bodies are back to their original text, and a following preview plans A again. Run the purge again with the failure disarmed and assert it converges (A's leftover copy is merged away). Then arm every `UpdateBody` and assert `groups_purged` 0, `failed_groups` = `groups_total` and `last_purge_at` still saved.
31. Concurrency: start run 1 in a goroutine, blocked in the image fake (wait on a "started" channel). Send run 2 (once with a fingerprint, once without). Assert both answer 409 with `apperr.PurgeBusyErrorMessage + "\n"` immediately (use a timeout) and no `Save`/`Delete` calls from them. Release run 1, assert its 200 body and that a later run is accepted. Run this test with `-race`. 31. Concurrency: start run 1 in a goroutine, blocked in the image fake (wait on a "started" channel). Send run 2 (once with a fingerprint, once without). Assert both answer 409 with `apperr.PurgeBusyErrorMessage + "\n"` immediately (use a timeout) and no `Save`/`Delete` calls from them. Release run 1, assert its 200 body and that a later run is accepted. Run this test with `-race`.
32. Sentinels at the use-case level, asserted separately: a stale fingerprint gives `errors.Is(err, purge.ErrPurgeConflict)` true and `errors.Is(err, purge.ErrPurgeBusy)` false; a busy guard gives `ErrPurgeBusy` true and `ErrPurgeConflict` false. Call RunPurge without any HTTP package to prove it is reusable (that test file section imports no `net/http`). 32. Sentinels at the use-case level, asserted separately: a stale fingerprint gives `errors.Is(err, purge.ErrPurgeConflict)` true and `errors.Is(err, purge.ErrPurgeBusy)` false; a busy guard gives `ErrPurgeBusy` true and `ErrPurgeConflict` false. Call RunPurge without any HTTP package to prove it is reusable (that test file section imports no `net/http`).
33. Malformed body gives 400 `apperr.BodyErrorMessage`. `ListDuplicates` failure gives 500 and no `Save`. 33. Malformed body gives 400 `apperr.BodyErrorMessage`. `ListDuplicates` failure gives 500 and no `Save`.
+3 -2
View File
@@ -26,8 +26,9 @@ Feature: Pending registration screen
you'll log in there first. Can't find it? Check your spam folder. If the link has expired, you'll log in there first. Can't find it? Check your spam folder. If the link has expired,
cancel your registration and start again.") is rendered through ResultPanel's default slot cancel your registration and start again.") is rendered through ResultPanel's default slot
as a second paragraph below the description, per components.md's "Slot default for extras" as a second paragraph below the description, per components.md's "Slot default for extras"
And "Log out" calls POST /v1/auth/logout, which per loginHandler.Logout always responds 200 and And "Log out" calls POST /v1/auth/logout, which per loginHandler.Logout clears the jwt cookie
clears the jwt cookie; on its response, PendingPage calls session.clear() and navigates to and responds 200 (500 only when the session cannot be revoked server-side; the cookie is
cleared either way); on its response, PendingPage calls session.clear() and navigates to
/login, disabling both actions while the call is in flight /login, disabling both actions while the call is in flight
And "Cancel registration" opens ConfirmDialog (built by this slice; components.md documents it And "Cancel registration" opens ConfirmDialog (built by this slice; components.md documents it
but no file exists yet) via useOverlay().create(ConfirmDialog).open(), with title "Cancel but no file exists yet) via useOverlay().create(ConfirmDialog).open(), with title "Cancel
+380
View File
@@ -0,0 +1,380 @@
Feature: Relation field in the SPA
As an owner or admin building a content type, and as a verified user filling an entry
I want a Relation field that links an entry to entries of another content type
So that structured content can point at other structured content
Background:
Given the SPA calls the API with relative URLs under /v1 and the "jwt" HttpOnly cookie
And API errors are plain text
And this slice changes only web/ (and web/visual); the backend of features/relation_field_type.feature is done
And the design is docs/design/screens/schema-later.md section 7 (3 states) and the board group "7 Relations" of "RenewCMS Screens Schema.dc.html" with SchemaFrame.dc.html; the frame markup wins over prose for layout
And the registry is lib/fieldTypes with lib/entryEditors, the single source for the builder, the list cells and the entry form; no screen branches on the type name "relation" where a registry property can say it
And the tags "Later" and "Relation columns: later" / "Relation field: later" drawn on the board are not rendered; the feature ships
And a relation value is an id (uint32 of at least 1) or null for one_to_one and one_to_many, and an array of ids ([] when empty, at most 50) for many_to_many
And a field loaded from the API has "relation": {"content_type","kind"} with kind "one_to_one", "one_to_many" or "many_to_many"
And every entry answer (POST 201, PUT 200, GET one, each list item) carries a top-level "relations" object keyed by relation field key: {"id","content_type","first_field":{"key","type","value"}} for an existing target, or {"id","missing":true}; an array of these for many_to_many; the label of a target is its first_field formatted by the same rule as the entry list, and "Entry N" when null
And the API refuses with 422 "invalid_entry: <key>: required", "invalid_entry: <key>: type", 409 "invalid_entry: <key>: unique", 409 "schema_incompatible" for a new required relation on a type with entries, 422 "invalid_field" for a bad definition, and 409 "content_type_referenced" when deleting a target type
And the picker searches GET /v1/content-type/{target}/entry?q=&page=&size= and reads total from the answer
And the inverse side is shown in the builder preview only; the target type's form, list and API are unchanged
And sentence case, buttons are verbs, every string goes through t() and has a French entry in i18n/messages.ts
And a copy tagged "(proposed copy)" is not in the design and is the coder's single point of change
And the sample data is the board's: Event with Venue (one_to_many) and Speakers (many_to_many); venues "Rue Verte hall" (Lyon · 120 seats), "Rue Verte yard" (Lyon · outdoor), "Rue du Port studio" (Nantes · 24 seats); speakers "Ines Duarte" and "Jonas Pereira"; entries 42 "Lime plaster workshop", 41 "Heat pumps: what the numbers say", 40 "Open day at the Rue Verte site"
Scenario Outline: Relation in the registry
Given the registry entry for "relation"
Then <property> is <value>
Examples:
| property | value |
| type name in the API | relation (the eighth entry, after media) |
| label | Relation |
| description | Links to another type's entries (proposed copy) |
| icon | lucide:link |
| control | RelationField |
| pairs with a neighbour | no, full width |
| empty value | null for one_to_one and one_to_many, [] for many_to_many |
| initial on create | the empty value; a relation has no default, so no "Default" tag ever shows |
| initial on edit | the stored id or ids |
| supports unique | no |
| supports limits | no |
| supports default | no |
| supports choices | no |
| counter | none |
| list cell | chips: one chip, two chips and "+N", or "–"; not sortable |
| sample in the API preview | null for a single kind, [] for many_to_many |
Scenario: A loaded relation field is not shown as Text
Given GET /v1/content-type/events returns a field {"key":"venue","label":"Venue","type":"relation","required":false,"unique":false,"default":null,"min":null,"max":null,"options":[],"relation":{"content_type":"venues","kind":"one_to_many"}}
Then the builder, the entry form and the list resolve it to the relation entry of the registry, never to the fallback type "text"
Scenario Outline: Client validation of a relation value
Given a <kind> relation "Venue" that is <required>
When the value is <value>
Then the rule is <rule>
Examples:
| kind | required | value | rule |
| single | required | null | required |
| single | optional | null | none |
| single | required | 3 | none |
| single | optional | 0 | type |
| single | optional | "3" | type |
| single | optional | [3] | type |
| many_to_many | required | [] | required |
| many_to_many | optional | [] | none |
| many_to_many | optional | [11, 12] | none |
| many_to_many | optional | [11, 11] | type |
| many_to_many | optional | 11 | type |
| many_to_many | optional | 51 ids | type |
Scenario Outline: Messages of a relation field
Given a relation field labelled "Venue" whose related type is named "Venues"
Then the message of the rule <rule> reads <message>
Examples:
| rule | message |
| required | Choose a Venue. (proposed copy) |
| type | Venue must point to an existing entry. (proposed copy) |
| unique | That Venue is already used by another entry. (proposed copy) |
| min | not produced for relation |
| max | not produced for relation |
| options | not produced for relation |
Scenario: The type gallery gains Relation
Given the inspector of a field that can still change type
Then the tile "Relation" with the link icon is the last tile, selectable like the others
And on a saved field the other tiles are dimmed to 40 % and not selectable, as for any locked type
Scenario: Adding a relation field
Given Events and a second content type Venues exist
When the user activates "Add field", types the label "Venue" and chooses the tile "Relation"
Then the new row shows the badge "New", the key "venue" (Auto, editable) and the chip reads "Unsaved changes"
And the inspector reads "Field: Venue" and shows, after the Type tiles and in this order, the select "Related content type" with the help "Choose the content type this field points to." and the group "How are they connected?"
And no related type is chosen yet and "Save" cannot send a relation without one (proposed copy for the message: "Choose a related content type.")
Scenario: The related content type select
Given the user is editing Events
Then the select lists the other content types by name, and Events itself, each with its key as a hint (proposed)
And choosing Venues sets the sentences of the preview to "Venue" and "Events"
Scenario: Three shape cards (design "Relation in the builder")
Given the related type is Venues, the owner Events
Then three cards are shown in a row (one column on mobile), each with a diagram of squares and a line, a title and a sentence
| card | sentence |
| One to one | Each Event has one Venue, and each Venue has one Event. |
| One to many | Each Event has one Venue. A Venue has many Events. |
| Many to many | Each Event has many Venues, and each Venue has many Events. |
And the selected card has the primary border and the sand fill with --rc-on-sand text, the others the accented border
And the cards are a radio group, one is selected at a time, and a new relation starts with "One to many" selected (proposed default)
Scenario: The preview of both sides
Given "One to many" is selected with Event and Venue
Then a block with the elevated background reads "Each Event has [one] Venue" and "Each Venue has [many] Events" followed by the muted text `· shown on Venue as the field "Events"`
And the bracketed words are drawn as selects showing the chosen kind and follow the selected card
And below it two cards "Event" (Venue: chip "Rue Verte hall") and "Venue" (Events: chips "Open day", "Lime plaster workshop" and "+1") illustrate both sides, side by side on desktop and stacked on mobile
And the inverse field is not stored anywhere and nothing about it is sent
Scenario Outline: The preview follows the kind
Given the owner Event and the related type Venue
When the user selects <card>
Then the sentences read <owner side> and <inverse side>
Examples:
| card | owner side | inverse side |
| One to one | Each Event has one Venue | Each Venue has one Event |
| One to many | Each Event has one Venue | Each Venue has many Events |
| Many to many | Each Event has many Venues| Each Venue has many Events |
Scenario: Plural and names come from the types
Given the owner "Events" and the related type "Venues"
Then "Event"/"Events" and "Venue"/"Venues" in the sentences are the singular and plural forms drawn from the type names (proposed rule: singular is the name without a final "s"; the field label is used for the singular of the related side)
Scenario: The PUT and POST body of a relation field
Given a relation "Venue" to "venues", kind "One to many", Required off
When the type is saved
Then the field is sent as {"key":"venue","label":"Venue","type":"relation","required":false,"unique":false,"default":null,"min":null,"max":null,"options":[],"relation":{"content_type":"venues","kind":"one_to_many"}}
And every other field is sent with "relation": null
And a round trip of the loaded field to the payload produces no change
Scenario: The inspector of a saved relation (locked) (state not drawn; proposed copy)
Given Events with a saved relation "Venue" as its field
When the user selects its row
Then the Label input and the Required switch are editable
And the Key is locked with "Used in the API, so it can't change."
And the legend of the tiles reads "Type" with a lock and "Can't change after saving", Relation is selected and the other tiles are dimmed to 40 %
And "Related content type" and the three cards are shown disabled with the selected card kept, under the note "The related type and the connection can't change after saving. (proposed copy)"
Scenario: A required relation added to a type with entries is refused first
Given Events with 12 entries and a new relation "Venue" that is required
When the user activates Save
Then no PUT is sent and the dialog "Review changes to Events" opens
And the row "Add Venue" has the warning badge "Can't be applied" and the text "Relation, required. A relation can't have a default, so the 12 existing entries would have no Venue. Make Venue optional to add it. (proposed copy)"
And "Back to editing" is enabled and "Apply changes" is disabled, so pressing it sends nothing
And an optional relation shows the clean row "Relation, optional. 12 entries are unaffected. (proposed copy)" with "Apply changes" enabled
Scenario: The server answers on the builder
Given the user applies a type with a relation
When the server answers <status> "<body>"
Then <result>
Examples:
| status | body | result |
| 409 | schema_incompatible | the existing "Nothing was changed" refusal flow runs unchanged |
| 422 | invalid_field | the existing invalid-field failure of the builder is shown, the edits stay |
Scenario: Deleting a type that another type points at (proposed copy)
Given Venues is the target of the relation on Events and Venues has no entries
When the user confirms the delete of Venues
Then the API answers 409 "content_type_referenced"
And the existing delete failure surface shows the title "You can't delete Venues yet" and the text "Events has a field that points to Venues. Remove that field first. (proposed copy)"
And the type is still listed
Scenario: The builder is for owners and admins
Given a verified user who is neither owner nor admin
Then the builder keeps its existing "You don't have access to Schema" state and no relation control is rendered
Scenario: Where the controls sit
Given Events with the fields Title, Venue and Speakers
Then the controls follow the schema order, full width in the 760 px column, each with its label ("Venue", "Speakers") in weight 500
Scenario: Single relation, empty, focused search (design "Venue")
Given /content/events/42 whose venue is null
When the user focuses the "Venue" control and types "rue"
Then the input shows the search icon, the typed text and "Search to add"
And a popover list under the input shows rows of at least 40 px (48 on mobile) with the title in weight 500 and a second muted 12/18 line, each row a button
| title | second line |
| Rue Verte hall | Lyon · 120 seats |
| Rue Verte yard | Lyon · outdoor |
| Rue du Port studio | Nantes · 24 seats|
And the first row has the elevated background
And the title is the first field of the related type and the second line is the next fields formatted as the entry list does, joined by " · " (up to 2 fields, proposed rule)
Scenario: Picking a single target
When the user activates the row "Rue Verte hall"
Then the list closes, the control shows one chip "Rue Verte hall" with an x, the value becomes 3, and the chip of the page reads "Unsaved changes"
And the live region says "Venue set to Rue Verte hall. (proposed copy)" and the focus stays in the control
And the chip's x removes it, sets the value to null, and says "Venue cleared. (proposed copy)"
Scenario: Many relation (design "Speakers")
Given Events with speakers [11, 12]
Then the control is a bordered box (1 px accented, min height 40, 44 on mobile) holding the chips "Ines Duarte" and "Jonas Pereira", each 24 px high (32 on mobile) with an x, then the muted text "Search to add"
And the help line under it reads "An event can have many speakers."
And a chip is a sand chip with --rc-on-sand text, weight 500
Scenario: Adding and removing in a many relation
When the user types "ines" in the control and activates the row "Ines Duarte"
Then the chip is added at the end in the chosen order and the row no longer appears in later results
When the user activates the x of a chip, or presses Backspace in the empty input
Then that chip is removed and the live region says "Ines Duarte removed from Speakers. (proposed copy)"
And a 51st target cannot be added: the search shows "You can add up to 50. (proposed copy)" and no row is selectable
Scenario: One to one targets already used (proposed copy)
Given a one_to_one relation
When the server answers 409 "invalid_entry: room: unique"
Then "That Venue is already used by another entry." shows under the control with a circle-alert icon, the error border applies, the chip reads "Not saved" and the focus moves to the control
Scenario: The search request
When the user types "rue"
Then the input is trimmed and debounced, and only GET /v1/content-type/venues/entry?q=rue&page=1&size=<page size> is sent
And the response replaces the list and a stale answer never overwrites a newer one
And with an empty input the first page of the type is listed without q (proposed)
Scenario: Picker loading (not drawn; proposed copy)
Given the search has not answered
Then after 150 ms the list shows three skeleton rows of the same height, with "Searching… (proposed copy)" announced politely, and no row is selectable
Scenario: No match (not drawn; proposed copy)
Given the search answers total 0 for "zzz"
Then the list shows `No Venues match "zzz"` (proposed copy) and the action "Clear search" that empties the input
And when the related type has no entries at all the list reads "No Venues yet. Add one in Content, then come back. (proposed copy)"
Scenario Outline: Search failures (not drawn; proposed copy)
Given the search answers <outcome>
Then <result>
Examples:
| outcome | result |
| 500 | the list shows "Couldn't load Venues" / "Check your connection and try again." with "Try again" (proposed copy) |
| a network error | the same |
| 429 | the existing rate-limit countdown alert |
| 401 | the global redirect, no local copy |
| 404 | "Couldn't load Venues" as for 500, since the related type may have been deleted (proposed copy) |
Scenario: Load more in the list
Given the search has more results than one page
When the user scrolls to the end of the list or activates "Load more" (proposed copy)
Then the next page is appended and the focus stays on the active row
Scenario: Keyboard
Given the control is focused and the list is open
Then ArrowDown and ArrowUp move the active row, Enter picks it, Esc closes the list and keeps the typed text, Tab leaves the control
And in a many relation Backspace on an empty input removes the last chip and chips are reachable with ArrowLeft
Scenario: A missing target (not drawn; proposed copy)
Given relations.venue is {"id":3,"missing":true}
Then the control shows a dashed chip "Entry no longer exists (proposed copy)" with an x and the help "You can still save. The entry keeps the link until you change it. (proposed copy)" when the field is optional
And when the field is required the help reads "Venue is required. Choose another to save. (proposed copy)", and saving with the missing target sends no request, shows the required message and focuses the control
And saving an optional field with the missing target sends the same id
Scenario: Required and empty
Given a required relation with no target
When the user activates "Save"
Then no request is sent, the error "Choose a Venue." replaces the help line, the border is --ui-error, the chip reads "Not saved" and the focus goes to the control
And only the first field in schema order with an error takes the focus
When the user picks a target
Then the error goes and the chip reads "Unsaved changes"
Scenario: Saving
Given the PUT has not answered
Then the form is dimmed to 70 %, the chips and the input are not operable and the list cannot open
And Save reads "Saving…"
Scenario Outline: What the control shows and sends
Given the loaded value <loaded> with relations <relations>
When the user <action> and activates "Save"
Then the control shows <shown>
And the data holds <sent>
Examples:
| loaded | relations | action | shown | sent |
| null | none | saves with nothing changed | no chip | "venue": null |
| 3 | existing venue 3 | saves with nothing changed | the chip "Rue Verte hall"| "venue": 3 |
| 3 | missing venue 3 | saves with nothing changed | the missing chip | "venue": 3 |
| 3 | existing venue 3 | picks "Rue Verte yard" | the chip "Rue Verte yard"| "venue": 4 |
| 3 | existing venue 3 | activates the x | no chip | "venue": null |
| [11] | speaker 11 | adds Jonas Pereira | two chips | "speakers": [11, 12] |
| [11,12] | speakers 11, 12 | removes both | no chip | "speakers": [] |
Scenario: Create payload with relations
Given /content/events/new with Title "Open day", Venue left empty and Speakers left empty
When the user activates "Save"
Then POST /v1/content-type/events/entry is sent once with "venue": null and "speakers": [] among the other keys, never absent
And with Rue Verte hall picked it holds "venue": 3, a JSON number
Scenario: Right after a pick the control uses the picked row
Given the user picks "Rue Verte yard" from the results
Then before any save the chip shows its title from the result and no extra request is made
When the PUT answers 200 with relations.venue
Then the control is rebuilt from the answered relations object
Scenario: Dirty tracking of a relation value
Given an entry whose venue is 3
When the user picks 4 then picks 3 again
Then the chip reads "Saved", "Save" is disabled and the leave guard does not prompt
And for a many relation the same ids in another order count as changed
Scenario Outline: Server answers for a relation field
Given the client found no error and the PUT or POST is sent
When the server answers <status> "<body>"
Then <result>
Examples:
| status | body | result |
| 422 | invalid_entry: venue: required | "Choose a Venue." under the control, error border, chip "Not saved", focus on the control |
| 422 | invalid_entry: venue: type | "Venue must point to an existing entry." (proposed copy) under the control, chip "Not saved" |
| 409 | invalid_entry: venue: unique | the one to one copy above |
| 422 | invalid_entry: venue: unknown_field | the read-only reload alert of features/content_entry_editor.feature, same as for media |
Scenario: Layout of the generated form with a relation
Given a boolean, a number or a date field before the relation
Then the relation never pairs and is full width at every viewport
Scenario: Mobile form
Given a 390 px viewport
Then chips are 32 px high, rows are 48 px high, the input is 44 px high, and the list opens as a bottom sheet (proposed) or under the input as drawn
Scenario Outline: The relation cell (design "Relation in the list")
Given the entry list of Events with the columns Title, Starts on, Venue and Speakers
And the item's relations <relations>
Then the cell shows <cell>
Examples:
| relations | cell |
| venue 3 "Rue Verte hall" | one chip "Rue Verte hall" (20 px high, 6 px padding) |
| speakers 11, 12 | two chips "Ines Duarte" and "Jonas Pereira" |
| speakers 11, 12 and two more | two chips and the muted 12 px text "+2" |
| no venue | the muted "–" |
| an empty speakers list | the muted "–" |
| a missing venue | a dashed chip "Entry no longer exists" (proposed copy) |
Scenario: Columns of the board (desktop)
Given the items 42, 41 and 40
Then the grid reads ID, Title, Starts on, Venue, Speakers with the columns 48 px, 1.4fr, 110 px, 200 px, 200 px
And row 42 shows "Rue Verte hall" and "Ines Duarte", "Jonas Pereira", "+2"; row 41 shows "–" and "Jonas Pereira"; row 40 shows "Rue Verte yard" and "–"
And rows stay 48 px high and the header is 36 px high on the elevated background
And the note "One chip for a single relation. Up to two chips and a "+N" for many. Empty shows a dash." is a design annotation and is not rendered
Scenario: The mobile card
Given a 390 px viewport and Venue and Speakers among the columns
Then each card lists the title, then a line "Venue" (12 px muted) followed by its chips, then a line "Speakers" followed by its chips (wrapping), and "–" for none
And the card keeps its minimum height
Scenario: Columns menu
When the user opens "Columns"
Then "Venue" and "Speakers" are listed with the link icon, their keys, and a checkbox like other fields
And the cap of 6, Reset and the stored choice work as for any field
And a relation column is not sortable and has no sort icon and no aria-sort
Scenario: Cell data comes from the item
Then the chips are read from each item's own "relations" object with no extra request
And the plain text of a relation cell (card title, page title) reads the labels joined by ", " or "–", never the numeric id
Scenario: Relation as the first column
Given a type whose first field is a relation
Then the first column still links to the editor and the chips are the link content
And the page title and breadcrumb of such an entry read "Entry 42"
Scenario: Accessibility of the control
Then the control is a combobox with role="combobox", aria-expanded, aria-controls and aria-activedescendant on the input, labelled by the field label
And the list is role="listbox" with role="option" rows
And chips are a group labelled by the field label, each x is a button named "Remove Ines Duarte from Speakers"
And required adds aria-required, the error text has an id and aria-invalid and aria-describedby point at it then at the help
And one polite live region announces added, removed and cleared values and the result count ("3 results" / "No results", proposed copy)
And mobile targets are 44 px
Scenario: Accessibility of the builder
Then the shape cards are a radio group with a visible selected state that is not only a colour, the disabled locked controls are announced as disabled, and "Can't be applied" is a text badge
+59
View File
@@ -0,0 +1,59 @@
# QA procedure: relation field in the SPA
Two parts. Part 1 is automated (Vitest component tests, `task test:web`). Part 2 is the visual gate (`task visual:check`). Part 3 is manual. The Go side is in `relation_field_type.qa.md`. Until `task test:web` exists, SPA tests are reported NOT RUN, never passing.
## Part 1: automated (Vitest + Vue Test Utils)
Mock `/v1` per test with the shapes below; no live server. A field is `{"key","label","type":"relation","required","unique":false,"default":null,"min":null,"max":null,"options":[],"relation":{"content_type","kind"}}` and every other field carries `"relation": null`.
Registry
1. `lib/fieldTypes`: the relation entry has the properties of the registry outline (label, icon `lucide:link`, control `RelationField`, no unique/limits/default/choices, empty value per kind, sample null or []). An unknown type still falls back to text; a relation never does.
2. Client validation table (single and many, required/optional, 0, "3", [3], duplicates, 51 ids) and the message map including the "not produced" rules.
Builder (one test per state)
3. Type gallery: Relation is the last tile; locked on a saved field with the other tiles dimmed.
4. New relation: the related-type select lists the other types (mock `GET /v1/content-type`), the help text, the three cards with the exact sentences, default "One to many" (proposed); choosing a type updates the sentences.
5. Preview outline: the kind change updates both sentences and the line `· shown on Venue as the field "Events"`; the example cards "Event" and "Venue" show the board's chips (Rue Verte hall, Open day, Lime plaster workshop, +1). Nothing about the inverse is in any request.
6. Save body: relation sent as `{"content_type","kind"}`, others `"relation": null`; a loaded field round-trips unchanged; no related type chosen blocks Save with the proposed message.
7. Saved relation: key, tiles, related type and cards are disabled; Label and Required editable; the proposed lock note shows.
8. Review: required relation + entries > 0 shows the flagged row and disabled "Apply changes" with no PUT; optional shows the clean row; required with 0 entries sends at once; making an optional relation required shows "Entries may not fit" with Apply enabled.
9. Server answers: 409 `schema_incompatible` and 422 `invalid_field` map to the existing flows.
10. Delete refused: 409 `content_type_referenced` shows the proposed copy and the type stays listed.
11. A non-owner/admin sees no builder.
Entry form (one test per state)
12. Single control: type "rue" -> only `GET /v1/content-type/venues/entry?q=rue&page=1&size=...` is sent (debounced, trimmed, stale answers ignored); rows show title and second line; pick sets the value to 3, one chip, "Unsaved changes", live message.
13. Many control: chips for [11, 12], "Search to add", the help line; add keeps order; x and Backspace remove; picked ids are not offered again; the 51st is blocked with the proposed message.
14. States: loading (skeleton after 150 ms), no match with "Clear search", empty type, 500, network error, 429 countdown, 401 redirect, 404 (all with the proposed copy where tagged), "Try again" re-sends only the search.
15. Missing target (optional and required), saving, keyboard (arrows, Enter, Esc, Tab, Backspace), required-empty error and focus order (first invalid field only).
16. Outline "What the control shows and sends" (all 7 rows) and the create payload with `venue: null`, `speakers: []` and with a picked number.
17. Dirty tracking: back to the original value gives "Saved"; reordered many ids count as changed.
18. Server answers table: `required`, `type`, `unique`, `unknown_field` (reload alert), each with the right copy, chip and focus.
19. Layout: a relation after boolean/number/date never pairs.
List
20. Cell outline (one chip, two chips, two chips + "+2", dash for null, dash for [], missing chip) from each item's `relations` with no extra request; relation columns are not sortable (no sort icon, no `aria-sort`).
21. Desktop grid for items 42/41/40 matches the board texts; the mobile card shows the labelled lines; the Columns menu lists Venue and Speakers with the link icon and the cap of 6.
22. Plain text of a relation cell never shows the numeric id; a first-field relation keeps the link and the "Entry N" title.
Accessibility
23. Combobox/listbox roles and attributes, chip group label, "Remove X from Y" button names, required/invalid/describedby wiring, the live region texts.
## Part 2: visual (`task visual:check -- <screen>`)
Hard gate: each capture within 10 % at 1440x900 and 390x844, light and dark. Add setups in `web/visual/states.ts` with the board's own sample data; no clock-sensitive state exists in this group.
| Screen | State | Board sample data the mock must reuse |
| --- | --- | --- |
| schema | Relation in the builder | Events with Venue (label), key `venue`, related type Venue, "One to many" selected, preview sentences, example cards with chips "Rue Verte hall", "Open day", "Lime plaster workshop", "+1" |
| entry (content/events/42) | Relation in the entry form | Title "Lime plaster workshop" (21 / 80); Venue search "rue" with rows "Rue Verte hall / Lyon · 120 seats", "Rue Verte yard / Lyon · outdoor", "Rue du Port studio / Nantes · 24 seats"; Speakers chips "Ines Duarte", "Jonas Pereira"; help "An event can have many speakers." |
| content (events) | Relation in the list | Items 42 "Lime plaster workshop" 21 Nov 2026 (Rue Verte hall; Ines Duarte, Jonas Pereira, +2), 41 "Heat pumps: what the numbers say" 3 Nov 2026 (–; Jonas Pereira), 40 "Open day at the Rue Verte site" 12 Nov 2026 (Rue Verte yard; –) |
Notes:
- The board's states are drawn with a "Later" badge; the SPA does not render it. Expect a pixel difference at the badge. If the 10 % gate fails because of it, the user decides on a documented `exception` (`approvedBy`); the QA never adds one.
- The board's builder shows a four-tile gallery plus Relation; the SPA shows the full gallery. The mismatch is reported to the user, not worked around.
- States tagged "(proposed copy)" (loading, no match, error, missing chip, locked inspector, review refusal, delete refusal) are not on the board and get Vitest tests only, no visual capture.
## Part 3: manual (screenshots can't cover)
- Keyboard and focus order across the combobox, chips and list; screen reader announcements of the live region.
- Hover and motion of the popover and of the chips' x; the mobile bottom-sheet versus under-input choice.
- Real SQLite end to end with the built binary: build the type pair, pick, save, reload, delete a target and see the missing chip.
- `bunx playwright install chromium` the first time on a machine.
+235
View File
@@ -0,0 +1,235 @@
Feature: Relation field type for custom content types
As a site owner or admin
I want a content type field that links an entry to entries of another content type
So that structured content can refer to other structured content
Background:
Given internal/domain/contenttype adds the field type "relation" next to text, richtext, number, boolean, date, select and media
And a relation field carries "relation": {"content_type": <key of an existing type>, "kind": "one_to_one" | "one_to_many" | "many_to_many"}
And "one_to_many" reads from the owner: each owner entry has one target, a target has many owner entries
And every field response gains the key "relation", null for the other types, so a field has exactly ten keys
And a relation field accepts only label, key, required and relation; unique, default, min, max and options are refused with ErrInvalidField
And the target type must exist, else ErrInvalidField; a self relation is allowed for one_to_many and many_to_many and refused for one_to_one
And the connection is stored once, on the owner field; the inverse side is derived, never stored, never added to the target schema, and the target type's schema, entry responses, list and routes are unchanged
And the owner value is an id (uint32, at least 1) or null for one_to_one and one_to_many, and an array of ids ([] when empty, at most 50, no duplicates, order kept) for many_to_many
And entry.Validate stays pure; the existence of target entries is checked by CreateEntry and UpdateEntry through entry.Repository
And a changed value means an id not equal to the one in the stored document for that key; on POST every id is changed; on PUT an unchanged id is not checked for existence unless the field is required
And a changed id must be an existing entry of the target type, else 422 "invalid_entry: <key>: type"
And a required relation is never saved empty: null, absent or [] give 422 "invalid_entry: <key>: required", and so does an unchanged id whose entry is gone
And a one_to_one id already held by another entry of the owner type is refused with 409 "invalid_entry: <key>: unique" (entry.ErrUniqueViolation)
And rules are checked in field order for Validate, then target existence in field order, then unique, and the body names one field per answer
And an entry response keeps its eight keys and adds "relations", always present ({} when no relation is set)
And "relations"[key] is {"id","content_type","first_field":{"key","type","value"}} for an existing target, or {"id","missing":true} when it is gone; for many_to_many it is an array of these in stored order
And first_field is the first field of the target type in schema order with its raw stored value, never formatted by the server
And the same "relations" object is on POST 201, PUT 200, GET one and every item of the list
And GET /v1/content-type/{key}/entry accepts ?q=, a trimmed case-insensitive substring of the display text of the first field, filtered in Go on the unpaged list before pagination, so total counts the matches; an empty q means no filter
And deleting an entry that other entries reference is allowed and leaves them untouched
And DELETE /v1/content-type/{key} on a type that is the target of a relation field is refused with 409 "content_type_referenced" (contenttype.ErrReferenced, new apperr string), even with no entries
And a saved relation field's type, target and kind never change: a change is refused with 422 "invalid_field"
And a new required relation on a type with entries gives 409 "schema_incompatible"
And no repository method is added; the code works on SQLite, MySQL/MariaDB and PostgreSQL with no JSON operators
And the key-set assertions of the earlier custom content type, entry and media features and tests are amended (field 9 to 10 keys, entry 8 to 9 keys)
And types: "venue" has title (text, required) and city (text); "event" has title (text, required) then venue (relation to venue, one_to_many, label "Venue") then speakers (relation to speaker, many_to_many); "speaker" has name (text, required)
And entries: venue 3 "Rue Verte hall", venue 4 "Rue Verte yard"; speaker 11 "Ines Duarte", speaker 12 "Jonas Pereira"
And users: admin id 2 (verified) can write types; any verified user can write entries
Scenario: Creating a content type with a relation field
Given a valid jwt cookie for admin 2 and the type "venue"
When the client sends POST /v1/content-type with fields title (text, required) and
{"key":"venue","label":"Venue","type":"relation","required":false,"unique":false,"default":null,"min":null,"max":null,"options":[],"relation":{"content_type":"venue","kind":"one_to_many"}}
Then the response status is 201
And the venue field comes back with that relation object and the other fields have "relation": null
Scenario Outline: A relation field with a bad definition is refused
Given a valid jwt cookie for admin 2
When the client sends POST /v1/content-type with a relation field that has <defect>
Then the response status is 422
And the response body is "invalid_field"
And no content type is stored
Examples:
| defect |
| relation null |
| content_type "nope" (unknown type) |
| content_type "" or missing |
| kind "many_to_one" |
| kind missing |
| a relation object on a text field |
| unique true |
| default 3 |
| min 1 |
| max 5 |
| options ["a"] |
| a one_to_one self relation |
Scenario: The shape of a saved relation never changes
Given the type "event" has a saved relation "venue" (one_to_many to venue) and at least one entry
When admin 2 sends PUT /v1/content-type/event changing its kind to many_to_many
Then the response is 422 invalid_field and the schema is unchanged
When admin 2 sends PUT changing its target to speaker
Then the response is 422 invalid_field and the schema is unchanged
When admin 2 sends PUT turning it into a text field
Then the response is 422 invalid_field and the schema is unchanged
Scenario Outline: Adding a relation field to a type that has entries
Given the type "event" has 12 entries
When admin 2 sends PUT adding a relation field "venue" that is <required>
Then the response status is <status> and the body is <message>
Examples:
| required | status | message |
| required | 409 | schema_incompatible |
| optional | 200 | |
Scenario: Deleting a type that another type points at
Given the type "venue" has no entries and "event" has a relation to it
When admin 2 sends DELETE /v1/content-type/venue
Then the response status is 409 with "content_type_referenced" and venue still exists
When the relation field is removed from "event" and DELETE is sent again
Then the response status is 204
Scenario: Creating an entry with a single target
When a verified user sends POST /v1/content-type/event/entry with {"data":{"title":"Lime plaster workshop","venue":3}}
Then the response status is 201 and data.venue is 3
And relations is {"venue":{"id":3,"content_type":"venue","first_field":{"key":"title","type":"text","value":"Rue Verte hall"}}}
Scenario: Creating an entry with many targets
When the client sends POST with {"data":{"title":"A","speakers":[12,11]}}
Then data.speakers is [12,11] and relations.speakers lists speaker 12 then speaker 11
Scenario Outline: Empty optional relations
When the client sends POST with <data>
Then the response status is 201, <stored>, and relations is {}
Examples:
| data | stored |
| {"data":{"title":"A","venue":null}} | data.venue is null |
| {"data":{"title":"A"}} | data.venue is absent |
| {"data":{"title":"A","speakers":[]}} | data.speakers is [] |
Scenario Outline: Values that break a relation are refused and store nothing
Given "venue" is <required> and "speakers" is many_to_many
When the client sends POST with the data <data>
Then the response status is <status> and the body is <message>
And no entry exists
Examples:
| required | data | status | message |
| required | {"title":"A"} | 422 | invalid_entry: venue: required |
| required | {"title":"A","venue":null} | 422 | invalid_entry: venue: required |
| optional | {"title":"A","venue":999} | 422 | invalid_entry: venue: type |
| optional | {"title":"A","venue":"3"} | 422 | invalid_entry: venue: type |
| optional | {"title":"A","venue":0} | 422 | invalid_entry: venue: type |
| optional | {"title":"A","venue":3.5} | 422 | invalid_entry: venue: type |
| optional | {"title":"A","venue":[3]} | 422 | invalid_entry: venue: type |
| optional | {"title":"A","speakers":11} | 422 | invalid_entry: speakers: type |
| optional | {"title":"A","speakers":[11,11]} | 422 | invalid_entry: speakers: type |
| optional | {"title":"A","speakers":[11,999]}| 422 | invalid_entry: speakers: type |
| optional | {"title":"A","speakers":[3]} | 422 | invalid_entry: speakers: type |
| optional | speakers with 51 ids | 422 | invalid_entry: speakers: type |
Scenario: A required many relation is never empty
Given "speakers" is required
When the client sends POST with speakers [] or with the key absent
Then the response is 422 invalid_entry: speakers: required
Scenario: One to one keeps targets exclusive
Given the type "talk" has a one_to_one relation "room" to "venue" and a talk already holds venue 3
When the client sends POST with room 3
Then the response is 409 "invalid_entry: room: unique" and nothing is stored
When the holder is updated with room 3 unchanged
Then the response is 200
When the holder is deleted and the POST is sent again
Then the response is 201
Scenario: Replacing and clearing targets
Given the entry 5 holds venue 3 and speakers [11]
When a verified user sends PUT with venue 4 and speakers [11,12]
Then data and relations reflect venue 4 and speakers 11, 12
When the user sends PUT with venue null and speakers []
Then relations is {}
Scenario: A target deleted after the entry was saved
Given the entry 5 holds venue 3 and speakers [11,12]
When entry 3 of venue and entry 12 of speaker are deleted (both answer 204)
And the client sends GET /v1/content-type/event/entry/5
Then data is unchanged
And relations.venue is {"id":3,"missing":true}
And relations.speakers is [{"id":11,"content_type":"speaker","first_field":{"key":"name","type":"text","value":"Ines Duarte"}},{"id":12,"missing":true}]
And the entry 5 was not modified (updated_at and updated_by unchanged)
Scenario Outline: Unchanged and changed ids when the target is gone
Given the entry 5 holds venue 3 and venue 3 was deleted
When the user sends PUT with venue <value>
Then the response status is <status> and the body is <message>
Examples:
| value | status | message |
| 3 | 200 | |
| 999 | 422 | invalid_entry: venue: type |
| 4 | 200 | |
| null | 200 | |
Scenario Outline: A required relation with a missing target can't be saved as is
Given venue is required, entry 5 holds venue 3 and venue 3 was deleted
When the user sends PUT with venue <value>
Then the status is <status>, the body is <message> and the stored entry is <outcome>
Examples:
| value | status | message | outcome |
| 3 | 422 | invalid_entry: venue: required | unchanged |
| null | 422 | invalid_entry: venue: required | unchanged |
| 4 | 200 | | updated |
Scenario: A create always treats the id as changed
Given venue 3 was deleted
When the client sends POST with venue 3
Then the response is 422 invalid_entry: venue: type
Scenario: Two broken fields name only one
Given a body with a required text left empty and a relation to a missing target
Then the answer names one field: Validate rules first in field order, then existence, then unique
Scenario: Entry list responses carry relations per item
Given 3 events: one with a venue and two speakers, one with a deleted venue, one with nothing
When the client sends GET /v1/content-type/event/entry
Then each item keeps its eight keys and adds "relations"
And items, total, page and size are unchanged
And a type without a relation field returns "relations": {} and makes no target repository call
Scenario Outline: Searching the entries of a type
Given the type "venue" has entries titled "Rue Verte hall", "Rue Verte yard", "Rue du Port studio"
When the client sends GET /v1/content-type/venue/entry?q=<q>
Then total is <total>
Examples:
| q | total |
| rue | 3 |
| RUE VERTE | 2 |
| yard | 1 |
| nothing | 0 |
| | 3 |
Scenario: Search is paginated after filtering
Given 30 venues match "rue"
When the client sends GET /v1/content-type/venue/entry?q=rue&page=2&size=10
Then total is 30, page is 2, size is 10 and items holds the second ten matches in the requested sort
Scenario: Deleting an entry that is referenced
Given 4 events hold venue 3
When a verified user sends DELETE /v1/content-type/venue/entry/3
Then the response status is 204 and the 4 events are not modified
Scenario: The target type, entries and API are unchanged
Given "event" has a one_to_many relation to "venue"
When the client sends GET /v1/content-type/venue and GET /v1/content-type/venue/entry/3
Then neither response carries the inverse field "Events" and the venue field list is the one saved
Scenario: Use case level
Given fake contenttype and entry repositories
Then contenttype.ValidateFields returns ErrInvalidField for each refused definition
And entry.Validate returns errors.Is(err, entry.ErrInvalidEntry) with Key and Rule "required" or "type" for the shapes above
And CreateEntry and UpdateEntry return the same for a missing target and perform no Create or Update
And UpdateContentType returns contenttype.ErrSchemaIncompatible for a new required relation and ErrInvalidField for a changed shape
And DeleteContentType returns contenttype.ErrReferenced for a target type
+48
View File
@@ -0,0 +1,48 @@
# QA procedure: relation field type (API only)
Package: `test` (black-box). No live server, no real SQLite file, no real SMTP, no SPA.
## Setup shared by every case
1. Call `validator.InitValidator()` once per test.
2. Reuse `mockContentTypeRepo` and `mockEntryRepo` of the custom content type and media pairs. Fake names stay unique across the package. The entry fake needs `createCalls`, `updateCalls`, a `getCalls` counter per content type and a `deleteEntry(contentTypeID, id)` helper. No repository method is added.
3. Build `NewHandler(...)` for the content type and entry handlers over use cases wired to the fakes. Mount them on a fresh `chi.NewRouter()` mirroring api/router.go under `/v1/content-type`, with `jwtauth.Verifier`, `jwtauth.Authenticator` and a test `jwtauth.New("HS256", []byte("test-secret"), nil)`, and `RequireOwnerOrAdmin` on the type write routes. Prefer `api.InitBackendRoutes` with a partial `*api.UseCases` if it works.
4. Seed admin 2 and a plain verified user. Seed the types venue, speaker, event and talk, and the entries venue 3, 4 and speaker 11, 12 from the feature.
5. Inject a fake clock so `updated_at` > `created_at`. Decode bodies into `map[string]any` and compare numbers as `float64`.
## Schema
6. POST a valid relation field -> 201; `relation` is the object sent; every other field has `"relation": null`; every field has exactly ten keys.
7. Refusal table (null relation, unknown target, empty target, bad kind, missing kind, relation on a text field, unique/default/min/max/options, one_to_one self) -> 422 `invalid_field`, repo empty.
8. Locking: kind, target and type changes on a saved relation -> 422 `invalid_field`, schema byte-identical. A type with no entries keeps today's free type change for non-saved shapes.
9. Type with 12 entries: add required relation -> 409 `schema_incompatible`, unchanged; add optional -> 200 and the old entries read with `relations` `{}`.
10. DELETE a target type with no entries -> 409 `content_type_referenced` (plain text); after removing the relation field -> 204. A type with entries is still 409 `content_type_has_entries`.
## Entry writes
11. Single and many targets -> 201, `data` as sent (array order kept), `relations` as in the feature. The target object has exactly `id`, `content_type`, `first_field`; `first_field` has exactly `key`, `type`, `value`, with the raw stored value.
12. Empty optional (null, absent, []) -> 201, `relations` is `{}` (assert JSON `{}`, not null). A required many field with [] or absent -> 422 required.
13. Refusal table -> exact status and body, `createCalls == 0`. The 51-id case is built in the test.
14. A venue id in a speaker field -> 422 type.
15. One-to-one exclusivity: 409 `invalid_entry: room: unique`, nothing stored; PUT of the holder unchanged -> 200; after deleting the holder, POST -> 201.
16. PUT replace/clear -> 200 with updated `relations`.
17. Dangling targets: `deleteEntry` venue 3 and speaker 12 -> GET entry 5 shows `{"id":3,"missing":true}` and the mixed array; `updated_at`/`updated_by` unchanged. PUT unchanged id -> 200; 999 -> 422 type; other id or null -> 200.
18. Required relation with a gone target: PUT same id -> 422 required; null -> 422 required; other id -> 200. POST with a deleted id -> 422 type.
19. Ordering: two bad fields name one only (Validate in field order, then existence, then unique).
## Reads
20. List with 3 events (full, dangling, empty) -> every item has the 8 old keys plus `relations`; `total`, `page`, `size` unchanged; `items` is `[]` for an empty type.
21. A type without a relation field -> `relations` `{}` and zero Get calls on target types. 100 entries pointing at one target call Get at most once for that id.
22. `?q=` table (case-insensitive, trimmed, empty = all, none = 0); `total` counts matches; page 2 size 10 of 30 matches returns the second ten; invalid `page`/`size`/`sort` keep their existing errors.
23. GET venue and GET a venue entry after the relation exists on event -> no inverse field, same keys as before.
## Delete
24. DELETE a referenced venue entry -> 204; the referencing events are byte-identical and no Update is recorded.
## Use case level (no HTTP)
25. `ValidateFields`, `entry.Validate`, `CreateEntry`/`UpdateEntry`, `UpdateContentType`, `DeleteContentType` as in the last scenario (`errors.Is`).
## Existing tests to amend
26. Key-set assertions in the custom content type, entry and media specs and tests: field 9 -> 10 keys, entry 8 -> 9 keys. The coder owns this.
## Manual verification (not exercised by the Go tests)
- Real SQLite, then MySQL/MariaDB and PostgreSQL via the driver tasks: create venue and event with a relation, save entries, delete the venue entry, reload the event and confirm the dangling id and `missing`.
- Time `GET .../entry?q=` against a type with 1,000 entries (the filter loads the whole type).
- The SPA is the second pair and is not checked here.
+190
View File
@@ -0,0 +1,190 @@
Feature: Sessions, uploads and stored personal data are hardened against forgery, replay and over-retention
As the operator of a RenewCMS instance
I want cross-site writes refused, logged-out sessions dead, weak secrets rejected, mail encrypted,
photo metadata removed and stale personal data deleted on a schedule
So that the instance meets the security-of-processing and storage-limitation duties of the GDPR
(art. 5(1)(c), 5(1)(e), 25 and 32) without the operator having to configure anything
Background:
Given api.InitRoutes wraps every route in middleware.CrossOriginProtection(settings.PublicURL),
built on the standard library's http.CrossOriginProtection, after CORS and before any router
And the jwt cookie is set and cleared with HttpOnly, SameSite=Lax, Path "/" and, in
production, Secure
Rule: Cross-site writes are refused
Scenario Outline: An unsafe cross-origin browser request is refused before any handler runs
Given a request <method> /v1/user/invite carrying the jwt cookie and the headers <headers>
Then the response is 403 with the body "Cross-origin requests are not allowed."
And the handler never runs
Examples:
| method | headers |
| POST | Sec-Fetch-Site: cross-site, Origin: https://evil.example |
| POST | Sec-Fetch-Site: same-site, Origin: https://blog.example.com |
| DELETE | Sec-Fetch-Site: cross-site, Origin: https://evil.example |
| POST | Origin: https://evil.example (an older browser, no Sec-Fetch-Site) |
Scenario Outline: Requests that cannot be forged are let through
Given a request <request>
Then the handler runs
Examples:
| request |
| POST with Sec-Fetch-Site: same-origin |
| POST with Sec-Fetch-Site: none |
| POST with neither Sec-Fetch-Site nor Origin (a non-browser client) |
| GET, HEAD or OPTIONS from any origin |
| POST from another origin carrying an Authorization header (an API key or bearer jwt) |
| POST whose Origin is the origin of PUBLIC_URL while a proxy rewrote Host |
Scenario: A PUBLIC_URL that cannot be parsed still leaves the protection on
Given PUBLIC_URL is not a URL
When a cross-site POST arrives
Then it is refused with 403
Rule: Logging out kills the session server-side
Scenario: Every session token carries a unique id and an expiry
When authtoken.Encode issues a token without "jti" or "exp"
Then it adds a random "jti" (crypto/rand.Text) and "exp" 24 hours after "iat"
And authtoken.Decode refuses a token without "exp" and a token whose "jti" is not a string
with ErrInvalid
Scenario: The token presented at logout is refused afterwards, other sessions are not
Given alice logged in twice, getting tokens A and B
When she sends POST /v1/auth/logout with token A
Then the response is 200 and clears the cookie
And a session.Revocation for A's jti, expiring at A's exp, is stored in revoked_sessions
And GET /v1/auth/me with token A answers 401 and with token B answers 200
Scenario: Logout without a valid session stores nothing
When POST /v1/auth/logout arrives without a cookie, or with an expired or revoked one
Then the response is 200, the cookie is cleared and nothing is stored
Scenario: A revocation that cannot be stored is reported
Given the revoked_sessions store refuses writes
When alice logs out
Then the response is 500 and the cookie is still cleared
Scenario: A token whose revocation cannot be checked is refused
Given the revoked_sessions store cannot be read
Then any request authenticated by a jwt is treated as unauthenticated
Rule: Only a current session sees drafts
Scenario: A verified user's stale token reads like an anonymous visitor
Given alice is verified and her token_version is 1
When GET /v1/article/ arrives with a token carrying token_version 0
Then only online articles are listed
Rule: Passwords fit bcrypt
Scenario Outline: A password over 72 bytes is refused with 400
When <request> carries a password of 73 bytes, or of 37 two-byte characters
Then the response is 400 with the body "The password must be 72 bytes or fewer."
And nothing is created or changed
Examples:
| request |
| POST /v1/auth/register |
| POST /v1/auth/password-reset/confirm (valid code) |
| POST /v1/auth/invite/accept (valid code) |
Scenario: A wrong reset code still wins over a long password
When POST /v1/auth/password-reset/confirm carries a wrong code and a 73-byte password
Then the response is 403 as for any wrong code
Rule: The server refuses to start with a guessable signing secret
Scenario Outline: A weak JWT_SECRET stops startup
Given JWT_SECRET is <value>
Then config.NewSettingsFromEnv fails with config.ErrWeakJWTSecret
And the message says to generate one with `openssl rand -hex 32`
Examples:
| value |
| empty |
| shorter than 32 bytes |
| "change-me-to-a-long-random-string" |
| "replace-with-output-of-openssl-rand-hex-32" |
Rule: Mail is never sent in clear text over the network by default
Scenario: A non-loopback SMTP server without STARTTLS is refused
Given SMTP_PORT is not 465, SMTP_HOST is not localhost, 127.0.0.1 or ::1, and the server does
not offer STARTTLS
When a mail is sent
Then delivery fails before MAIL FROM with an error naming SMTP_ALLOW_INSECURE
Scenario: The operator can opt out for a trusted relay
Given SMTP_ALLOW_INSECURE is "true"
When a mail is sent to such a server without credentials
Then it is delivered in clear text
And credentials are still never sent in clear text
Rule: Uploaded photos lose their metadata
Scenario Outline: Metadata is removed before the bytes are stored, hashed or measured for size
When a <format> image is uploaded
Then the stored bytes no longer contain <removed>
And they still contain <kept>
And the image's size and sha256 describe the stored bytes, and its pixels are unchanged
Examples:
| format | removed | kept |
| JPEG | EXIF, XMP, IPTC (APP13), comments, MPF and other APPn segments, trailing images | JFIF, ICC profile, Adobe |
| PNG | eXIf, tEXt, zTXt, iTXt, tIME and data after IEND | every other chunk |
| WebP | EXIF and XMP chunks (their VP8X flags cleared) and data after the RIFF size | every other chunk |
Scenario: A rotated photo keeps only its orientation
Given an uploaded JPEG, PNG or WebP whose EXIF orientation is 2 to 8
Then the stored file carries a minimal EXIF block holding only that orientation (after SOI or
JFIF for JPEG, after IHDR for PNG, at the end with the EXIF flag set for WebP)
Scenario: An image whose container cannot be walked is refused
When a JPEG, PNG or WebP with a truncated header, a chunk longer than the file or no IEND
(PNG) is uploaded
Then the upload fails with image.ErrImageUnreadable and nothing is stored
And a JPEG cut off inside its scan data is kept as it is
Scenario: SVG is stored as uploaded
When an SVG is uploaded
Then its bytes are stored unchanged
Rule: Stale personal data is deleted on a schedule
Scenario: The retention job runs hourly and logs only when it removed something
Given scheduler.NewSystemRetentionRunner runs useCases.EnforceRetentionUseCase a minute after
startup and then every hour
When a run removes something
Then the log reads "scheduler: personal data retention completed: revoked_sessions=<n>
unverified_users=<n> invites=<n>"
And a run that removes nothing logs nothing, and a failed run logs "... failed: <error>"
Scenario Outline: What is removed
Given <record>
Then the retention job <outcome>
Examples:
| record | outcome |
| a revoked session whose exp has passed | deletes it |
| an unverified account whose verification code expired more than 7 days ago | deletes it |
| an unverified account without a code expiry created more than 7 days ago | deletes it |
| an invite that expired more than 30 days ago | deletes it |
| an invite accepted more than 30 days ago | deletes it |
| a verified account, a pending invite or an account still inside its 7 days | keeps it |
Scenario: A failure stops the run and keeps the counts of what was done
Given deleting a user fails
Then the run returns the error with the sessions already purged counted and touches no invite
Rule: The back office loads nothing from third parties
Scenario: Fonts are bundled
Given the SPA's fonts (IBM Plex Sans, IBM Plex Mono, Source Serif 4) live in
web/src/assets/fonts with their OFL licences
Then the Content-Security-Policy allows "font-src 'self'" and "style-src 'self'
'unsafe-inline'" with no Google Fonts host
And loading the back office sends no request to fonts.googleapis.com or fonts.gstatic.com
+84
View File
@@ -0,0 +1,84 @@
# QA: security and privacy hardening
Everything below runs in `task test` (package `test`, `-tags nofrontend`) unless marked manual.
## Cross-origin protection and cookie flags
1. `test/cross_origin_protection_http_test.go`: wrap a counting handler in
`middleware.CrossOriginProtection("https://cms.example.com")`.
- Refused with 403 and `apperr.CrossOriginErrorMessage`, handler not reached: a cross-site POST, a
same-site POST from `https://blog.example.com`, a cross-site DELETE, and a POST with only
`Origin: https://evil.example`.
- Allowed: same-origin POST, `Sec-Fetch-Site: none`, no headers, cross-site GET and OPTIONS, a
cross-site POST with `Authorization: Bearer rcms_key`, and a POST whose `Origin` is the public
URL while `Host` is `127.0.0.1:8080`.
- With `PUBLIC_URL` `::not a url`, a cross-site POST is still 403.
2. `test/session_revocation_http_test.go` drives `api.InitRoutes`: the login cookie is HttpOnly,
Secure and `SameSite=Lax`, and a cross-site `POST /v1/auth/logout` is 403 and revokes nothing.
## Session revocation
3. `test/authtoken_test.go` (`TestAuthTokenRevocation`, `TestAuthTokenDecodeRejections`): distinct
`jti` per token; explicit `jti` kept; a revoked token gives `ErrRevoked` and is stored until its
`exp`; other tokens stay valid; store read failure gives `ErrInvalid`; store write failure is
returned by `Revoke`; no `jti` is a no-op; no `exp` refuses; tokens without `exp` or with a
non-string `jti` are refused by `Decode`.
4. `TestSessionRevocationUseCase`: an already-expired session is not stored; an empty or 65-byte id
is `session.ErrInvalidSessionID`; 64 bytes is accepted.
5. `TestRevokedSessionRepository` on a migrated SQLite file: revoking twice is harmless,
`DeleteExpired(now)` removes rows whose `expires_at <= now` and reports the count.
6. `TestLogoutRevokesTheSession` through `api.InitRoutes`: two logins, logout with the first, `/me`
with it is 401 and with the second is 200; logout without a cookie is 200 and stores nothing;
a failing write gives 500 with the cookie cleared; a failing read makes `/me` 401.
7. `test/verified_account_required_http_test.go`: a verified user whose `token_version` moved on
only sees online articles.
## Passwords
8. `test/password_length_limit_test.go`: 72 bytes accepted, 73 bytes and 37 × "é" refused by
`user.ValidatePassword`; register, reset (valid code) and invite accept answer 400 with
`apperr.PasswordTooLongErrorMessage` and change nothing; a wrong reset code still answers 403.
9. `test/hasher_test.go`: an unknown username compares against a decoy hash once per attempt and
hashes the decoy once.
## Configuration and mail
10. `test/runtime_settings_from_env_test.go`: empty, short, 31-byte and both example
`JWT_SECRET` values fail with `config.ErrWeakJWTSecret` and mention `openssl rand -hex 32`;
32 bytes passes. `SMTP_ALLOW_INSECURE` reads `""`/`false` as false, `true`/`TRUE` as true, and
`maybe` fails naming the variable.
11. `test/smtp_mailer_test.go` against the fake server on `127.0.0.2`: no STARTTLS and no opt-out
fails before `MAIL FROM` naming `SMTP_ALLOW_INSECURE`; with the opt-out the message is
delivered in clear text; with the opt-out and credentials, nothing is sent.
## Upload metadata
12. `test/image_metadata_stripping_test.go` builds JPEG, PNG and WebP files carrying a GPS-like
marker in EXIF, XMP, IPTC, comments, text chunks, MPF and trailing data. Assert the marker is
gone, ICC is kept, pixels decode identically, the orientation-only EXIF appears only when the
orientation is not 1 and sits in the documented place, WebP flags and RIFF size are correct,
a plain WebP and an SVG come back unchanged, and each malformed container is
`ErrImageUnreadable`.
13. `TestUploadStoresTheStrippedImage`: the stored bytes carry no marker and `Size`/`SHA256` match
them. `TestUploadRefusesAnImageWhoseContainerIsBroken`: nothing is stored.
## Retention
14. `test/personal_data_retention_test.go`: the user and invite rules at their boundaries; one run
over a seeded world removes exactly one expired revocation, one abandoned account and two
invites; a second run removes nothing; a session store failure touches nothing else; a user
or invite deletion failure returns the partial counts; the runner logs counts only when
something was removed and logs failures.
## Fonts
15. `test/security_headers_test.go`: the CSP contains `font-src 'self';` and no Google host.
16. Manual: `task build:web`, open the back office with the network panel; no request leaves for
`fonts.googleapis.com` or `fonts.gstatic.com`, and `task visual:check -- log-in` passes.
## Manual verification
- Behind the real reverse proxy, log in, copy the `jwt` cookie, log out, then replay the cookie
with `curl`: `/v1/auth/me` answers 401.
- With an SMTP relay that lacks STARTTLS on a non-loopback host, sending fails until
`SMTP_ALLOW_INSECURE=true` is set.
@@ -10,7 +10,7 @@ Feature: The rate limiter keys on the real connection address, trusting a forwar
Background: Background:
Given POST /v1/auth/login and POST /v1/auth/password-reset are each wrapped, inside Given POST /v1/auth/login and POST /v1/auth/password-reset are each wrapped, inside
NewAuthRouter, by a middleware that runs before RateLimiter (api/middleware/rateLimit.go), NewAuthRouter, by a middleware that runs before RateLimiter (api/middleware/rateLimit.go),
which keys its counters on r.RemoteAddr which keys its counters on the host portion of r.RemoteAddr, never on its source port
And this slice replaces chimiddleware.RealIP on those two route groups with And this slice replaces chimiddleware.RealIP on those two route groups with
TrustedProxyRealIP(trustedProxies []string) func(http.Handler) http.Handler TrustedProxyRealIP(trustedProxies []string) func(http.Handler) http.Handler
(api/middleware/trustedProxyRealIP.go) (api/middleware/trustedProxyRealIP.go)
@@ -96,3 +96,23 @@ Feature: The rate limiter keys on the real connection address, trusting a forwar
X-Real-IP header X-Real-IP header
Then the first response is not rejected by rate limiting and the second is 429 — both are Then the first response is not rejected by rate limiting and the second is 429 — both are
counted against "10.0.0.1" itself counted against "10.0.0.1" itself
Scenario: New connections from the same address share one counter
Given TRUSTED_PROXIES is "" and AUTH_RATE_LIMIT_MAX_ATTEMPTS is 1
When a request arrives with connection address "203.0.113.7:40000"
And a second request arrives with connection address "203.0.113.7:40001"
Then the first response is not rejected by rate limiting and the second is 429, because the
counter is keyed on "203.0.113.7" and the source port is ignored
Scenario: A forwarded client keeps one counter across the proxy's connections
Given TRUSTED_PROXIES is "10.0.0.1" and AUTH_RATE_LIMIT_MAX_ATTEMPTS is 1
When a request arrives with connection address "10.0.0.1:51000" and header
X-Real-IP: "198.51.100.9"
And a second request arrives with connection address "10.0.0.1:51001" and the same header
Then the first response is not rejected by rate limiting and the second is 429
Scenario: Expired counters do not accumulate
Given requests from many distinct addresses
When a full window has passed since a counter started
Then the next request evicts every counter whose window has ended, so memory stays bounded by
the addresses seen within one window
@@ -56,6 +56,14 @@ setup (`mockUserRepo`, `stubHasher`, `mockMailRepo`, the full `useCases` set, `a
no forwarding header at all. Assert not `429`. Send a second, identical request. Assert `429` — no forwarding header at all. Assert not `429`. Send a second, identical request. Assert `429` —
a trusted proxy with nothing to forward falls back to its own address as the key. a trusted proxy with nothing to forward falls back to its own address as the key.
14. `trustedProxies = nil`, limit 5. Send 100 requests from `203.0.113.7` on ports `40000`–`40099`.
Assert exactly 95 are `429` — the source port never yields a fresh counter
(`test/rate_limit_connection_key_http_test.go`).
15. Same for IPv6: `[2001:db8::1]:50000` then `[2001:db8::1]:50001` with limit 1 → `200` then `429`.
16. `trustedProxies = ["10.0.0.1"]`, limit 1. `10.0.0.1:51000` and `10.0.0.1:51001`, both with
`X-Real-IP: 198.51.100.9` → `200` then `429`.
17. Limit 1, window 20 ms: `200`, `429`, wait 30 ms, `200` — an expired counter starts over.
## Manual verification (not exercised by the Go test) ## Manual verification (not exercised by the Go test)
- Real behaviour behind the documented nginx and Caddy reverse proxies (`docs/deployment.md`) — - Real behaviour behind the documented nginx and Caddy reverse proxies (`docs/deployment.md`) —
+44 -64
View File
@@ -1,84 +1,64 @@
module RenewCMS module RenewCMS
go 1.27.1 go 1.27.3
require ( require (
github.com/MadAppGang/httplog v1.3.0 github.com/aws/aws-sdk-go-v2 v1.47.3
github.com/aws/aws-sdk-go-v2 v1.47.1 github.com/aws/aws-sdk-go-v2/config v1.33.9
github.com/aws/aws-sdk-go-v2/config v1.33.6 github.com/aws/aws-sdk-go-v2/credentials v1.20.9
github.com/aws/aws-sdk-go-v2/credentials v1.20.6 github.com/aws/aws-sdk-go-v2/service/s3 v1.114.4
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.0
github.com/gen2brain/webp v0.6.4 github.com/gen2brain/webp v0.6.4
github.com/glebarez/sqlite v1.11.0 github.com/glebarez/sqlite v1.11.0
github.com/go-chi/chi/v5 v5.2.3 github.com/go-chi/chi/v5 v5.5.0
github.com/go-chi/cors v1.2.2 github.com/go-playground/validator/v10 v10.30.5
github.com/go-chi/jwtauth/v5 v5.4.0 github.com/go-sql-driver/mysql v1.10.1
github.com/go-playground/validator/v10 v10.28.0
github.com/go-sql-driver/mysql v1.8.1
github.com/google/uuid v1.6.0 github.com/google/uuid v1.6.0
github.com/jackc/pgx/v5 v5.10.0 github.com/jackc/pgx/v5 v5.11.0
github.com/joho/godotenv v1.5.1 golang.org/x/crypto v0.58.0
github.com/lestrrat-go/jwx/v3 v3.3.0 golang.org/x/image v0.47.0
golang.org/x/crypto v0.57.0 golang.org/x/net v0.61.0
golang.org/x/image v0.46.0 golang.org/x/text v0.43.0
golang.org/x/net v0.59.0
golang.org/x/sync v0.23.0
golang.org/x/text v0.42.0
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
gorm.io/driver/mysql v1.6.0 gorm.io/driver/mysql v1.6.0
gorm.io/driver/postgres v1.6.3 gorm.io/driver/postgres v1.6.3
gorm.io/gorm v1.31.2 gorm.io/gorm v1.31.2
) )
require ( require (
filippo.io/edwards25519 v1.1.0 // indirect filippo.io/edwards25519 v1.2.0 // indirect
github.com/TylerBrock/colorjson v0.0.0-20200706003622-8a50f05110d2 // indirect github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.23 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20 // indirect github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.3 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.1 // indirect github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4 // indirect github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4 // indirect github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4 // indirect github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19 // indirect github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5 // indirect github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4 // indirect github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4 // indirect github.com/aws/aws-sdk-go-v2/service/signin v1.10.4 // indirect
github.com/aws/aws-sdk-go-v2/service/signin v1.10.1 // indirect github.com/aws/aws-sdk-go-v2/service/sso v1.38.4 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.38.1 // indirect github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1 // indirect github.com/aws/aws-sdk-go-v2/service/sts v1.51.4 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.51.1 // indirect github.com/aws/smithy-go v1.28.6 // indirect
github.com/aws/smithy-go v1.28.1 // indirect github.com/dustin/go-humanize v1.1.0 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1 // indirect github.com/ebitengine/purego v0.11.2 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect github.com/gabriel-vasile/mimetype v1.4.16 // indirect
github.com/ebitengine/purego v0.10.1 // indirect github.com/glebarez/go-sqlite v1.23.0 // indirect
github.com/fatih/color v1.18.0 // indirect github.com/go-playground/locales v0.14.2 // indirect
github.com/gabriel-vasile/mimetype v1.4.11 // indirect github.com/go-playground/universal-translator v0.18.2 // indirect
github.com/glebarez/go-sqlite v1.22.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/goccy/go-json v0.10.6 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/jackc/puddle/v2 v2.2.3 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect github.com/jinzhu/now v1.1.5 // indirect
github.com/leodido/go-urn v1.4.0 // indirect github.com/leodido/go-urn v1.5.0 // indirect
github.com/lestrrat-go/blackmagic v1.0.4 // indirect github.com/mattn/go-isatty v0.0.24 // indirect
github.com/lestrrat-go/dsig v1.4.0 // indirect github.com/ncruces/go-strftime v1.1.0 // indirect
github.com/lestrrat-go/dsig-secp256k1 v1.0.0 // indirect
github.com/lestrrat-go/httpcc v1.0.1 // indirect
github.com/lestrrat-go/httprc/v3 v3.0.6 // indirect
github.com/lestrrat-go/option/v2 v2.0.0 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/segmentio/asm v1.2.1 // indirect github.com/stretchr/testify v1.12.1 // indirect
github.com/valyala/fastjson v1.6.10 // indirect golang.org/x/sync v0.24.0 // indirect
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 // indirect golang.org/x/sys v0.49.0 // indirect
golang.org/x/sys v0.48.0 // indirect modernc.org/libc v1.79.0 // indirect
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
modernc.org/libc v1.67.0 // indirect
modernc.org/mathutil v1.7.1 // indirect modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect modernc.org/memory v1.12.1 // indirect
modernc.org/sqlite v1.40.1 // indirect modernc.org/sqlite v1.61.0 // indirect
) )
+100 -146
View File
@@ -1,165 +1,119 @@
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
github.com/MadAppGang/httplog v1.3.0 h1:1XU54TO8kiqTeO+7oZLKAM3RP/cJ7SadzslRcKspVHo= github.com/aws/aws-sdk-go-v2 v1.47.3 h1:HRoT/MkNi3bjO5xF4dCzLzvVmkvRGHj3/cLINDnJejk=
github.com/MadAppGang/httplog v1.3.0/go.mod h1:gpYEdkjh/Cda6YxtDy4AB7KY+fR7mb3SqBZw74A5hJ4= github.com/aws/aws-sdk-go-v2 v1.47.3/go.mod h1:xSl+OSI5ZUw6bSMupWc218zE5Pl+65MCCu3ySWFY99A=
github.com/TylerBrock/colorjson v0.0.0-20200706003622-8a50f05110d2 h1:ZBbLwSJqkHBuFDA6DUhhse0IGJ7T5bemHyNILUjvOq4= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.23 h1:/fGPpKrXTjzkhsDXExBgNT2cGwxiF9rLrQXh8RlXMhI=
github.com/TylerBrock/colorjson v0.0.0-20200706003622-8a50f05110d2/go.mod h1:VSw57q4QFiWDbRnjdX8Cb3Ow0SFncRw+bA/ofY6Q83w= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.23/go.mod h1:QWUDuRi9PFjBHIU2iH1Pkldbe7zqLfXJC4wWLbF8nuQ=
github.com/aws/aws-sdk-go-v2 v1.47.1 h1:uOIZnp4PK3ZhKI0dNrJrhTEsLxbpXHTAJlwoS1pvAtw= github.com/aws/aws-sdk-go-v2/config v1.33.9 h1:Hv6bcQUJVnmuWaKjqD6Ot8sE75NrWsWV20oGT5aWle0=
github.com/aws/aws-sdk-go-v2 v1.47.1/go.mod h1:bttEH6JqnUL8LepvDVfdrds/fZ5bCIxzpe3abyUrhDU= github.com/aws/aws-sdk-go-v2/config v1.33.9/go.mod h1:ivowmrZNfBQLcg4QkaItgi5wae4Bzot9RzIdbY1hfTg=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20 h1:GPRlPwz40I2B2VrBEASOA3Bi77NyeqejNLkifosX0rs= github.com/aws/aws-sdk-go-v2/credentials v1.20.9 h1:SNO55PnWhaDafsOcv16lCA0kdoFMl/YlegWoVsU02s0=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20/go.mod h1:g7PNzKcsOKWb4fkSRBA7BZVAS6Y8IcxzN+nRohhQ1Q8= github.com/aws/aws-sdk-go-v2/credentials v1.20.9/go.mod h1:+2reOTRtdD3VSBqpRDNwrZIYy8yMCYa7oK3WKTJ/I1I=
github.com/aws/aws-sdk-go-v2/config v1.33.6 h1:MBjkSTLczek/UgiK+EYPIoRTqE7gP8vtW3OFbFo7Nug= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.3 h1:gr3b87OLB29jymWPzp/CAyXwQRJVE+sC4Wm0qBIKHsk=
github.com/aws/aws-sdk-go-v2/config v1.33.6/go.mod h1:grRAFzdAZJrwcbasJRg2MPvIrVjtlfXllHssN6+E1JE= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.3/go.mod h1:BRjf4L/Yx2hY54o+ZibPbLJyMMeSwqYQXwcJfqW66a8=
github.com/aws/aws-sdk-go-v2/credentials v1.20.6 h1:NpAFXCU7NzXNkdGK3zQTtsRJ+3v9tZQV0xcdRw8uBdw= github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6 h1:CqL8NN3p4I0JTwwV5MEoatIl4Y2amZ2X9dRD+0hbRL0=
github.com/aws/aws-sdk-go-v2/credentials v1.20.6/go.mod h1:mcZCoiPnyMvP8VMNbygNX5lLqSlkYJIMPODylQMurOk= github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6/go.mod h1:exdJ32hMqXl0Wyo6NwqEC5yIhtua3+PDaKE8P29m4qE=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.1 h1:8gALAAmacnIXh+z6VkdDanv4/IkG5APdg4DZLDTmLog= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6 h1:FpBq24TG6WVSObTNhQOv7Q0088rounUUlwn3zlNItkM=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.1/go.mod h1:Z7IJhJU+poOdJjUR2wpyY21ossQ1XS/R3Lk9Msq5kM4= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6/go.mod h1:ONzdPVYC95oBOu0VWNEsKEntcoemP3xVKjT+qWml1s4=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4 h1:CLq4+8UHCI+ZZYl/EuJxXovaIVN2xeeT8JV+dsApQ5E= github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6 h1:Qmn60RWuk9+bd2ddvJJqwf3Cpac3VvGMOdbGemtUhX4=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4/go.mod h1:Wv4q5sAM04xAMkoOedxLx2inVf6K5FdxYp+A61L+q/0= github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6/go.mod h1:h/YJhe4AVyQxEUMluph10iqV7mjajH7A9L+BHF5ppis=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4 h1:dD4MR81I7YkpEBRk6UP9rocC2QnT3qVuXwzlYTtfGEs= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21 h1:e6YW5uME30TkrElR+4/xcY7NB6CCj2dcv7vtmGXhfhQ=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4/go.mod h1:EcXV1kAFd5XwSkDHlj94gnF3q5CkJyYiIJfH8N0VmrE= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21/go.mod h1:obpHAMP693+f3/A8PkLhIqfK1C+NWWn8zXzqD3OH520=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4 h1:7Wo47d/xn/7KttCSBd8EGYeZ7ULRFRkUHr6vkZPBzVQ= github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7 h1:CwvFlKw0uUScfgOMflXSRZa+ayXgOf6wk7lhyMemQYU=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4/go.mod h1:tDB2IVC1xC3vX8o+6uRlzhTxP3g1b77CZXFX/oD2FnQ= github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7/go.mod h1:4SbD8BB+p+QEnG0aX6DoWwrtk9SufyYXRsUv0nve8LE=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19 h1:bAdDl/HkGCcGPoe25ToSHEw23VIxt6CT5fLcg111BKg= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6 h1:LHHdobjo5le1sjJdolitV7uVvYg3wkaeM1Ju2fDgeZQ=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19/go.mod h1:KaUzbLxv4CeSxh6ZCl9B4m7CuFenS8kUEaDs+f/DQr4= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6/go.mod h1:CBGB0evAiaMD3Lk4wPO7LQCcCZLuhzL5Qf/wfEUHQ5w=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5 h1:/TYsZXdA8UTa+WCtCYSAJIr1vwl0+eho6TUgJGwFFO8= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6 h1:mYViDr2azcgxOpRrObZOl631bvavqILoE/L+Kxgbwys=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5/go.mod h1:qPqp1Uwd/BqdhPufv6oem9j5J7HNsgc2V22dUiDPn+s= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6/go.mod h1:OXVdAo9jNhggB+hJRGOyy7WolGTKB6Rg7IIulDeSzPM=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4 h1:29SvnfGhXjTl8ONxFwbj2rs6lbhiFXD2CgFQmbT/bXY= github.com/aws/aws-sdk-go-v2/service/s3 v1.114.4 h1:MrkWRB58Qw5TEkb51QVooVLjlM3IevO2iVXEz74B8pg=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4/go.mod h1:wm04I5DMuNVvZHFe/dHnUxincvNbbK7AiNBbYsQivek= github.com/aws/aws-sdk-go-v2/service/s3 v1.114.4/go.mod h1:yfIxaKRHasvfy6tNEm3/LpqKsupMzQjMaWj9Y0jMVbo=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4 h1:pPiWfgeNxqluKEph7hvU88kuGKBPOWzO+Dk9t2zqqNs= github.com/aws/aws-sdk-go-v2/service/signin v1.10.4 h1:tvpDjuUvgKURf3Yk4hOaGbZ4QdY+070OWcA5d6LUv2A=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4/go.mod h1:YlwGoIUDG/3kBQbdNOVs/xKZ9J01G8e/6D1mRBj9uTk= github.com/aws/aws-sdk-go-v2/service/signin v1.10.4/go.mod h1:3ibVKg5Ng82Zby8++jELTD2nHxiPk2DJRLEeW/LKp8M=
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.0 h1:VMAdYqr4Jn/8ATs9BHC5riwrs0d6m1Z2ohFriSwZwm0= github.com/aws/aws-sdk-go-v2/service/sso v1.38.4 h1:ChCtagixSFOxltv0o6E3NT8F7ksvZtZGPwUBynO5Nmk=
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.0/go.mod h1:9APRWGLFITKD+xzWSIyT9V7QV4bNlEuIieWlzXgGFlI= github.com/aws/aws-sdk-go-v2/service/sso v1.38.4/go.mod h1:+FEO9jrVMpc9oN3CdAxJbtlQEu3z8UddDPSedpeM3PY=
github.com/aws/aws-sdk-go-v2/service/signin v1.10.1 h1:DzCCWLzcIRQ77F3DEUljud7bEjTgFOIKXP52NmVRyhU= github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4 h1:j6c+HA4AoS0EBEjArPjavFEBrucJEryfrQU0TffmACk=
github.com/aws/aws-sdk-go-v2/service/signin v1.10.1/go.mod h1:xpo/geVldu8payT375WekctUzopG/hBU7miiqItMUlw= github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4/go.mod h1:RhghaXUk9q66VtOQUX1FdPddQuHnqQZzbB0fEYXmPRA=
github.com/aws/aws-sdk-go-v2/service/sso v1.38.1 h1:Umtl/0YZhng4xndfW3lKJrYYP7NLEjI6bGXVomwLcs0= github.com/aws/aws-sdk-go-v2/service/sts v1.51.4 h1:OKEfbf2tcfsF2pBk/S9QqNpo6alaAtiBs4hysCsBjPw=
github.com/aws/aws-sdk-go-v2/service/sso v1.38.1/go.mod h1:rRD/dnm7q0HYE/I5TMaPgkWyyUGLcwuxHLABsLnQ3e0= github.com/aws/aws-sdk-go-v2/service/sts v1.51.4/go.mod h1:mCd6qGo9b8hTtfjgsmNkFlzwjyce4owd7HDVFnCLXhM=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1 h1:orIWdNiLgzrhu/11RcPPKO/SBzUUymbUQuZbSPImghg= github.com/aws/smithy-go v1.28.6 h1:Pj+/sUviNYjow8ELRtNwKHZ9ECeF+7pATX3+shjLIrw=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1/go.mod h1:skwM/xsbR/1ReUTesv9BhpJp1VjajR7DWQnuVLwiXsQ= github.com/aws/smithy-go v1.28.6/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/aws/aws-sdk-go-v2/service/sts v1.51.1 h1:0HOqZXRvMytH6bFHVIc0oJX07sZjfhz0zXtjs6gdE8s=
github.com/aws/aws-sdk-go-v2/service/sts v1.51.1/go.mod h1:26zA0GhDrLo+yiLI2yXWxqB1PdsShfLikoI7GOEgugM=
github.com/aws/smithy-go v1.28.1 h1:R/nXH00c8qcfCzQVELtRw+eLQWtzv+VAIEFJ1/xxXlQ=
github.com/aws/smithy-go v1.28.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1 h1:5RVFMOWjMyRy8cARdy79nAmgYw3hK/4HUq48LQ6Wwqo= github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40= github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/ebitengine/purego v0.11.2 h1:WWiTx8rD8zYdOwSj8O/NiNbsOvSAgJMTlyV1XlbUSeU=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/ebitengine/purego v0.11.2/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ=
github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY= github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E=
github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ= github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4=
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
github.com/gabriel-vasile/mimetype v1.4.11 h1:AQvxbp830wPhHTqc1u7nzoLT+ZFxGY7emj5DR5DYFik=
github.com/gabriel-vasile/mimetype v1.4.11/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/gen2brain/webp v0.6.4 h1:SUDdmxADOAiPQ+5ylNmuHhuYf2dOi0KgKZHL5vpVCNU= github.com/gen2brain/webp v0.6.4 h1:SUDdmxADOAiPQ+5ylNmuHhuYf2dOi0KgKZHL5vpVCNU=
github.com/gen2brain/webp v0.6.4/go.mod h1:iGWMaCSw7t3I/Cv9llzEKmpnR36S8lS8VL/ZVjxU0JE= github.com/gen2brain/webp v0.6.4/go.mod h1:iGWMaCSw7t3I/Cv9llzEKmpnR36S8lS8VL/ZVjxU0JE=
github.com/glebarez/go-sqlite v1.22.0 h1:uAcMJhaA6r3LHMTFgP0SifzgXg46yJkgxqyuyec+ruQ= github.com/glebarez/go-sqlite v1.23.0 h1:FyhIq4jqmgphQAUlY79zPldYGwISEZikaDfhiGWkkaI=
github.com/glebarez/go-sqlite v1.22.0/go.mod h1:PlBIdHe0+aUEFn+r2/uthrWq4FxbzugL0L8Li6yQJbc= github.com/glebarez/go-sqlite v1.23.0/go.mod h1:IIYrOH3L0rHY3jb4IXOHoWdklNajSGUN2eJcvK8WrnI=
github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw= github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw=
github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ= github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ=
github.com/go-chi/chi/v5 v5.2.3 h1:WQIt9uxdsAbgIYgid+BpYc+liqQZGMHRaUwp0JUcvdE= github.com/go-chi/chi/v5 v5.5.0 h1:xdKQ1dJmVJsmgahrXSKhUx8NyVPzpwdlyrrQFpMPJgg=
github.com/go-chi/chi/v5 v5.2.3/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops= github.com/go-chi/chi/v5 v5.5.0/go.mod h1:d1IG7GtKPSjPyBP365PH8sAGVHk3qfB/IhjFNRH1wWM=
github.com/go-chi/cors v1.2.2 h1:Jmey33TE+b+rB7fT8MUy1u0I4L+NARQlK6LhzKPSyQE=
github.com/go-chi/cors v1.2.2/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
github.com/go-chi/jwtauth/v5 v5.4.0 h1:Ieh0xMJsFvqylqJ02/mQHKzbbKO9DYNBh4DPKCwTwYI=
github.com/go-chi/jwtauth/v5 v5.4.0/go.mod h1:w6yjqUUXz1b8+oiJel64Sz1KJwduQM6qUA5QNzO5+bQ=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk=
github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688= github.com/go-playground/validator/v10 v10.30.5 h1:YyCXvVShZbs2Sm3Mb53eNOlhRXctSOzW5QJAouCTZL4=
github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU= github.com/go-playground/validator/v10 v10.30.5/go.mod h1:wEqiaov48pXX1kjhc3Da8y0M0Dtg/BK7gurFBLgwFrQ=
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME=
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
github.com/goccy/go-json v0.10.6 h1:p8HrPJzOakx/mn/bQtjgNjdTcN+/S6FcG2CTtQOrHVU= github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50 h1:PlNWJRxu5APSV0pWqfIsZ0qt9OOGHSWfZQ4zvx+WgWs=
github.com/goccy/go-json v0.10.6/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50/go.mod h1:yUo1AMMpsPIDFGuwDK8nLcf8+vvAd5l2O6JDZ6hpwrM=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/hokaccha/go-prettyjson v0.0.0-20211117102719-0474bc63780f h1:7LYC+Yfkj3CTRcShK0KOL/w6iTiKyqqBA9a41Wnggw8=
github.com/hokaccha/go-prettyjson v0.0.0-20211117102719-0474bc63780f/go.mod h1:pFlLw2CfqZiIBOx6BuCeRLCrfxBJipTY0nIOF/VbGcI=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0= github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/lestrrat-go/blackmagic v1.0.4 h1:IwQibdnf8l2KoO+qC3uT4OaTWsW7tuRQXy9TRN9QanA=
github.com/lestrrat-go/blackmagic v1.0.4/go.mod h1:6AWFyKNNj0zEXQYfTMPfZrAXUWUfTIZ5ECEUEJaijtw=
github.com/lestrrat-go/dsig v1.4.0 h1:g7LUjK8cT74A5DzBXJI5HzsJuLhoYN0Wzj4nuOMIrH8=
github.com/lestrrat-go/dsig v1.4.0/go.mod h1:I8Nddg/vN2cUl/h8N7SRRApLnNNeyZPIqLYpvpOtGGo=
github.com/lestrrat-go/dsig-secp256k1 v1.0.0 h1:JpDe4Aybfl0soBvoVwjqDbp+9S1Y2OM7gcrVVMFPOzY=
github.com/lestrrat-go/dsig-secp256k1 v1.0.0/go.mod h1:CxUgAhssb8FToqbL8NjSPoGQlnO4w3LG1P0qPWQm/NU=
github.com/lestrrat-go/httpcc v1.0.1 h1:ydWCStUeJLkpYyjLDHihupbn2tYmZ7m22BGkcvZZrIE=
github.com/lestrrat-go/httpcc v1.0.1/go.mod h1:qiltp3Mt56+55GPVCbTdM9MlqhvzyuL6W/NMDA8vA5E=
github.com/lestrrat-go/httprc/v3 v3.0.6 h1:4FpLQ18KK/ypPbVU3NLWJNRvH3kcYiqKqWfKGqNWxxI=
github.com/lestrrat-go/httprc/v3 v3.0.6/go.mod h1:mSMtkZW92Z98M5YoNNztbRGxbXHql7tSitCvaxvo9l0=
github.com/lestrrat-go/jwx/v3 v3.3.0 h1:OXcYvQOQ7cxWzeZ/Q9sYk8ABe/kCSI371WmuACiCT+4=
github.com/lestrrat-go/jwx/v3 v3.3.0/go.mod h1:eIJhDcKHBwcgxqv8RiIylV67TVl1wJp/265IAHY1Db8=
github.com/lestrrat-go/option/v2 v2.0.0 h1:XxrcaJESE1fokHy3FpaQ/cXW8ZsIdWcdFzzLOcID3Ss=
github.com/lestrrat-go/option/v2 v2.0.0/go.mod h1:oSySsmzMoR0iRzCDCaUfsCzxQHUEuhOViQObyy7S6Vg=
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0=
github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/valyala/fastjson v1.6.10 h1:/yjJg8jaVQdYR3arGxPE2X5z89xrlhS0eGXdv+ADTh4=
github.com/valyala/fastjson v1.6.10/go.mod h1:e6FubmQouUNP73jtMLmcbxS6ydWIpOfhz34TSfO3JaE=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 h1:zfMcR1Cs4KNuomFFgGefv5N0czO2XZpUbxGUy8i8ug0= golang.org/x/image v0.47.0 h1:za/8gVz++PPZqmZJBNSISICN5Rrj5zixP/8K++fgmqo=
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6/go.mod h1:46edojNIoXTNOhySWIWdix628clX9ODXwPsQuG6hsK0= golang.org/x/image v0.47.0/go.mod h1:IkN5o4A7vq55vXN8FWjjnhg9Rs2GOtffqsSi9mWAKYE=
golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ= golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew= golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw=
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues= golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc h1:2gGKlE2+asNV9m7xrywl36YYNnBG5ZQ0r/BOOxqPpmk=
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc/go.mod h1:m7x9LTH6d71AHyAX77c9yqWCCa3UKHcVEj9y7hAtKDk=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df h1:n7WqCuqOuCbNr617RXOY0AWRXxgwEyPp2z+p0+hgMuE=
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df/go.mod h1:LRQQ+SO6ZHR7tOkpBDuZnXENFzX8qRjMDMyPD6BRkCw=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/mysql v1.6.0 h1:eNbLmNTpPpTOVZi8MMxCi2aaIm0ZpInbORNXDwyLGvg= gorm.io/driver/mysql v1.6.0 h1:eNbLmNTpPpTOVZi8MMxCi2aaIm0ZpInbORNXDwyLGvg=
gorm.io/driver/mysql v1.6.0/go.mod h1:D/oCC2GWK3M/dqoLxnOlaNKmXz8WNTfcS9y5ovaSqKo= gorm.io/driver/mysql v1.6.0/go.mod h1:D/oCC2GWK3M/dqoLxnOlaNKmXz8WNTfcS9y5ovaSqKo=
@@ -169,30 +123,30 @@ gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8= gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo= gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo=
gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs= gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
modernc.org/cc/v4 v4.27.1 h1:9W30zRlYrefrDV2JE2O8VDtJ1yPGownxciz5rrbQZis= modernc.org/cc/v4 v4.30.3 h1:aDq8gIX1X7+VFgO/JYYji6pLWL2H4tv3g8WatT3KCys=
modernc.org/cc/v4 v4.27.1/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0= modernc.org/cc/v4 v4.30.3/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
modernc.org/ccgo/v4 v4.30.1 h1:4r4U1J6Fhj98NKfSjnPUN7Ze2c6MnAdL0hWw6+LrJpc= modernc.org/ccgo/v4 v4.37.0 h1:BAuJCUtIHIxFIYaFhqXIw5YaoMBlNCUlFovejHfMip4=
modernc.org/ccgo/v4 v4.30.1/go.mod h1:bIOeI1JL54Utlxn+LwrFyjCx2n2RDiYEaJVSrgdrRfM= modernc.org/ccgo/v4 v4.37.0/go.mod h1:/8627VhwWtAbqUXmPORxFQU5SgLrAx2jl9seLw9GBhY=
modernc.org/fileutil v1.3.40 h1:ZGMswMNc9JOCrcrakF1HrvmergNLAmxOPjizirpfqBA= modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
modernc.org/fileutil v1.3.40/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc= modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/gc/v3 v3.1.1 h1:k8T3gkXWY9sEiytKhcgyiZ2L0DTyCQ/nvX+LoCljoRE= modernc.org/gc/v3 v3.2.0 h1:/Y3LGDMQaoYf55PebP1qsZ5FDGgAZyG1RYKEHeQzh1o=
modernc.org/gc/v3 v3.1.1/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= modernc.org/gc/v3 v3.2.0/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.67.0 h1:QzL4IrKab2OFmxA3/vRYl0tLXrIamwrhD6CKD4WBVjQ= modernc.org/libc v1.79.0 h1:9Dvvv++bAMSkSuBzuOFAatbTV5OIoq6Y6FohmD3e7q8=
modernc.org/libc v1.67.0/go.mod h1:QvvnnJ5P7aitu0ReNpVIEyesuhmDLQ8kaEoyMjIFZJA= modernc.org/libc v1.79.0/go.mod h1:uT3kR61NsbeKJSLqq83GJwSnZMVLlSjyAz4DfTaBy1M=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8= modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.40.1 h1:VfuXcxcUWWKRBuP8+BR9L7VnmusMgBNNnBYGEe9w/iY= modernc.org/sqlite v1.61.0 h1:sQi63oLQ9uquAUA4CzOisH35Q3pEszkPBuHM0tFL8CY=
modernc.org/sqlite v1.40.1/go.mod h1:9fjQZ0mB1LLP0GYrp39oOJXx/I2sxEnZtzCmEQIKvGE= modernc.org/sqlite v1.61.0/go.mod h1:f4gr5tbpx2umklaT/QVtbi/50hNdM+4ng+2zMo8KXJ0=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
@@ -13,6 +13,7 @@ var (
ErrInvalidIcon = errors.New("invalid content type icon") ErrInvalidIcon = errors.New("invalid content type icon")
ErrInvalidField = errors.New("invalid field") ErrInvalidField = errors.New("invalid field")
ErrHasEntries = errors.New("the content type still has entries") ErrHasEntries = errors.New("the content type still has entries")
ErrReferenced = errors.New("the content type is the target of a relation field")
ErrSchemaIncompatible = errors.New("the schema is incompatible with the stored entries") ErrSchemaIncompatible = errors.New("the schema is incompatible with the stored entries")
) )
@@ -25,6 +26,8 @@ const (
TypeBoolean FieldType = "boolean" TypeBoolean FieldType = "boolean"
TypeDate FieldType = "date" TypeDate FieldType = "date"
TypeSelect FieldType = "select" TypeSelect FieldType = "select"
TypeMedia FieldType = "media"
TypeRelation FieldType = "relation"
) )
const ( const (
@@ -53,6 +56,7 @@ type Field struct {
Min any `json:"min"` Min any `json:"min"`
Max any `json:"max"` Max any `json:"max"`
Options []string `json:"options"` Options []string `json:"options"`
Relation *Relation `json:"relation"`
} }
type ContentType struct { type ContentType struct {
+31
View File
@@ -20,6 +20,37 @@ var kinds = map[FieldType]kind{
TypeBoolean: {accepts: isBoolean}, TypeBoolean: {accepts: isBoolean},
TypeDate: {accepts: isDate, measure: dateDays, bound: dateDays, unique: true}, TypeDate: {accepts: isDate, measure: dateDays, bound: dateDays, unique: true},
TypeSelect: {accepts: isString, unique: true}, TypeSelect: {accepts: isString, unique: true},
TypeMedia: {accepts: isMediaID},
TypeRelation: {},
}
func MediaID(value any) (uint32, bool) {
switch typed := value.(type) {
case uint32:
return typed, typed >= 1
case int:
return mediaIDFromInt(int64(typed))
case int64:
return mediaIDFromInt(typed)
case float64:
if typed != math.Trunc(typed) || typed < 1 || typed > math.MaxUint32 {
return 0, false
}
return uint32(typed), true
}
return 0, false
}
func mediaIDFromInt(number int64) (uint32, bool) {
if number < 1 || number > math.MaxUint32 {
return 0, false
}
return uint32(number), true
}
func isMediaID(value any) bool {
_, ok := MediaID(value)
return ok
} }
func isString(value any) bool { func isString(value any) bool {
+29 -1
View File
@@ -63,7 +63,7 @@ func (f Field) validSchema() bool {
if f.Unique && !fieldKind.unique { if f.Unique && !fieldKind.unique {
return false return false
} }
return f.validOptions() && f.validBounds(fieldKind) && f.validDefault() return f.validRelation() && f.validOptions() && f.validBounds(fieldKind) && f.validDefault()
} }
func (f Field) validOptions() bool { func (f Field) validOptions() bool {
@@ -109,5 +109,33 @@ func (f Field) validDefault() bool {
if f.Default == nil { if f.Default == nil {
return true return true
} }
if f.Type == TypeMedia || f.Type == TypeRelation {
return false
}
return !f.Unique && f.Violation(f.Default) == "" return !f.Unique && f.Violation(f.Default) == ""
} }
type MediaRef struct {
Field Field
ID uint32
}
func MediaRefs(fields []Field, data map[string]any) []MediaRef {
var refs []MediaRef
for _, field := range MediaFields(fields) {
if id, set := MediaID(data[field.Key]); set {
refs = append(refs, MediaRef{Field: field, ID: id})
}
}
return refs
}
func MediaFields(fields []Field) []Field {
var media []Field
for _, field := range fields {
if field.Type == TypeMedia {
media = append(media, field)
}
}
return media
}
@@ -3,6 +3,9 @@ package contenttype
import "slices" import "slices"
func (f Field) Violation(value any) string { func (f Field) Violation(value any) string {
if f.Type == TypeRelation {
return f.relationViolation(value)
}
fieldKind, known := kinds[f.Type] fieldKind, known := kinds[f.Type]
if !known || !fieldKind.accepts(value) { if !known || !fieldKind.accepts(value) {
return RuleType return RuleType
@@ -0,0 +1,134 @@
package contenttype
const MaxRelationIDs = 50
type RelationKind string
const (
RelationOneToOne RelationKind = "one_to_one"
RelationOneToMany RelationKind = "one_to_many"
RelationManyToMany RelationKind = "many_to_many"
)
type Relation struct {
ContentType string `json:"content_type"`
Kind RelationKind `json:"kind"`
}
func (r Relation) validKind() bool {
return r.Kind == RelationOneToOne || r.Kind == RelationOneToMany || r.Kind == RelationManyToMany
}
func (f Field) validRelation() bool {
if f.Type != TypeRelation {
return f.Relation == nil
}
return f.Relation != nil && f.Relation.ContentType != "" && f.Relation.validKind()
}
func (f Field) IsRelation() bool {
return f.Type == TypeRelation && f.Relation != nil
}
func (f Field) HoldsManyRelations() bool {
return f.IsRelation() && f.Relation.Kind == RelationManyToMany
}
func (f Field) IsExclusiveRelation() bool {
return f.IsRelation() && f.Relation.Kind == RelationOneToOne
}
func (f Field) RelationIDs(value any) ([]uint32, bool) {
if value == nil {
return []uint32{}, true
}
if !f.HoldsManyRelations() {
id, ok := MediaID(value)
if !ok {
return nil, false
}
return []uint32{id}, true
}
return manyRelationIDs(value)
}
func manyRelationIDs(value any) ([]uint32, bool) {
var items []any
switch typed := value.(type) {
case []any:
items = typed
case []uint32:
for _, id := range typed {
items = append(items, id)
}
default:
return nil, false
}
if len(items) > MaxRelationIDs {
return nil, false
}
ids := make([]uint32, 0, len(items))
seen := make(map[uint32]bool, len(items))
for _, item := range items {
id, ok := MediaID(item)
if !ok || seen[id] {
return nil, false
}
seen[id] = true
ids = append(ids, id)
}
return ids, true
}
func (f Field) relationViolation(value any) string {
if _, ok := f.RelationIDs(value); !ok {
return RuleType
}
return ""
}
func EmptyRelation(field Field, value any) bool {
if !field.HoldsManyRelations() {
return false
}
ids, ok := field.RelationIDs(value)
return ok && len(ids) == 0
}
type RelationRef struct {
Field Field
IDs []uint32
}
func RelationRefs(fields []Field, data map[string]any) []RelationRef {
var refs []RelationRef
for _, field := range RelationFields(fields) {
if ids, ok := field.RelationIDs(data[field.Key]); ok && len(ids) > 0 {
refs = append(refs, RelationRef{Field: field, IDs: ids})
}
}
return refs
}
func RelationFields(fields []Field) []Field {
var relations []Field
for _, field := range fields {
if field.IsRelation() {
relations = append(relations, field)
}
}
return relations
}
func ReferencesType(fields []Field, key string) bool {
for _, field := range RelationFields(fields) {
if field.Relation.ContentType == key {
return true
}
}
return false
}
func SameRelation(left Field, right Field) bool {
return left.IsRelation() && right.IsRelation() && *left.Relation == *right.Relation
}
+58 -5
View File
@@ -2,8 +2,11 @@ package entry
import ( import (
"RenewCMS/internal/domain/contenttype" "RenewCMS/internal/domain/contenttype"
"fmt"
"reflect" "reflect"
"sort" "sort"
"strconv"
"strings"
) )
func SameValue(left any, right any) bool { func SameValue(left any, right any) bool {
@@ -49,14 +52,14 @@ func Validate(fields []contenttype.Field, data map[string]any) error {
func validateField(field contenttype.Field, data map[string]any) error { func validateField(field contenttype.Field, data map[string]any) error {
value := data[field.Key] value := data[field.Key]
if value == nil { if value == nil || contenttype.EmptyRelation(field, value) {
if field.Required { if field.Required {
return invalidField(field.Key, RuleRequired) return InvalidField(field.Key, RuleRequired)
} }
return nil return nil
} }
if rule := field.Violation(value); rule != "" { if rule := field.Violation(value); rule != "" {
return invalidField(field.Key, rule) return InvalidField(field.Key, rule)
} }
return nil return nil
} }
@@ -76,15 +79,65 @@ func firstUnknownField(fields []contenttype.Field, data map[string]any) error {
return nil return nil
} }
sort.Strings(unknown) sort.Strings(unknown)
return invalidField(unknown[0], RuleUnknownField) return InvalidField(unknown[0], RuleUnknownField)
} }
func UniqueValues(fields []contenttype.Field, data map[string]any) []UniqueValue { func UniqueValues(fields []contenttype.Field, data map[string]any) []UniqueValue {
var values []UniqueValue var values []UniqueValue
for _, field := range fields { for _, field := range fields {
if value := data[field.Key]; field.Unique && value != nil { if value := data[field.Key]; (field.Unique || field.IsExclusiveRelation()) && value != nil {
values = append(values, UniqueValue{Key: field.Key, Value: value}) values = append(values, UniqueValue{Key: field.Key, Value: value})
} }
} }
return values return values
} }
func MediaIDs(fields []contenttype.Field, data map[string]any) map[string]uint32 {
ids := map[string]uint32{}
for _, ref := range contenttype.MediaRefs(fields, data) {
ids[ref.Field.Key] = ref.ID
}
return ids
}
func MissingMedia(field contenttype.Field, unchanged bool) error {
if unchanged {
return InvalidField(field.Key, RuleRequired)
}
return InvalidField(field.Key, contenttype.RuleType)
}
func RelationIDs(fields []contenttype.Field, data map[string]any) map[string]map[uint32]bool {
ids := map[string]map[uint32]bool{}
for _, ref := range contenttype.RelationRefs(fields, data) {
held := make(map[uint32]bool, len(ref.IDs))
for _, id := range ref.IDs {
held[id] = true
}
ids[ref.Field.Key] = held
}
return ids
}
func MissingRelation(field contenttype.Field, unchanged bool) error {
return MissingMedia(field, unchanged)
}
func MatchesQuery(fields []contenttype.Field, data map[string]any, query string) bool {
if len(fields) == 0 {
return false
}
return strings.Contains(strings.ToLower(displayText(data[fields[0].Key])), strings.ToLower(query))
}
func displayText(value any) string {
switch typed := value.(type) {
case nil:
return ""
case string:
return typed
case float64:
return strconv.FormatFloat(typed, 'f', -1, 64)
}
return fmt.Sprint(value)
}
+1 -1
View File
@@ -55,7 +55,7 @@ func (e FieldError) Unwrap() error {
return e.Cause return e.Cause
} }
func invalidField(key string, rule string) error { func InvalidField(key string, rule string) error {
return FieldError{Key: key, Rule: rule, Cause: ErrInvalidEntry} return FieldError{Key: key, Rule: rule, Cause: ErrInvalidEntry}
} }
+49
View File
@@ -246,3 +246,52 @@ type Image struct {
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"` UpdatedAt time.Time `json:"updated_at"`
} }
func isStoredNameByte(char byte) bool {
return char == '-' || char == '_' || char == '.' || char >= '0' && char <= '9' || char >= 'a' && char <= 'z' || char >= 'A' && char <= 'Z'
}
func continuesName(body string, end int) bool {
if end >= len(body) || !isStoredNameByte(body[end]) {
return false
}
return body[end] != '.' || end+1 < len(body) && isStoredNameByte(body[end+1])
}
func storedNameMatches(body string, name string) []int {
var starts []int
if name == "" {
return starts
}
for from := 0; from < len(body); {
found := strings.Index(body[from:], name)
if found < 0 {
break
}
start := from + found
end := start + len(name)
from = start + 1
if start > 0 && isStoredNameByte(body[start-1]) || continuesName(body, end) {
continue
}
starts = append(starts, start)
from = end
}
return starts
}
func ContainsStoredName(body string, name string) bool {
return len(storedNameMatches(body, name)) > 0
}
func ReplaceStoredName(body string, from string, to string) string {
var rewritten strings.Builder
last := 0
for _, start := range storedNameMatches(body, from) {
rewritten.WriteString(body[last:start])
rewritten.WriteString(to)
last = start + len(from)
}
rewritten.WriteString(body[last:])
return rewritten.String()
}
@@ -0,0 +1,5 @@
package image
type MetadataStripper interface {
Strip(contentType string, data []byte) ([]byte, error)
}
+12
View File
@@ -15,6 +15,8 @@ var ErrInviteAlreadyAccepted = errors.New("invite already accepted")
const Lifetime = 3 * 24 * time.Hour const Lifetime = 3 * 24 * time.Hour
const Retention = 30 * 24 * time.Hour
type Status string type Status string
const ( const (
@@ -42,3 +44,13 @@ func (i Invite) StatusAt(now time.Time) Status {
} }
return StatusExpired return StatusExpired
} }
func (i Invite) IsStaleAt(now time.Time) bool {
switch i.StatusAt(now) {
case StatusAccepted:
return now.After(i.AcceptedAt.Add(Retention))
case StatusExpired:
return now.After(i.ExpiresAt.Add(Retention))
}
return false
}
@@ -0,0 +1,11 @@
package retention
type Result struct {
RevokedSessions int
UnverifiedUsers int
Invites int
}
func (r Result) Total() int {
return r.RevokedSessions + r.UnverifiedUsers + r.Invites
}
+22
View File
@@ -0,0 +1,22 @@
package session
import (
"errors"
"time"
)
var ErrInvalidSessionID = errors.New("invalid session id")
const MaxIDLength = 64
type Revocation struct {
ID string
ExpiresAt time.Time
}
func ValidateID(id string) error {
if id == "" || len(id) > MaxIDLength {
return ErrInvalidSessionID
}
return nil
}
@@ -0,0 +1,9 @@
package session
import "time"
type Repository interface {
Revoke(revocation Revocation) error
IsRevoked(id string) (bool, error)
DeleteExpired(now time.Time) (int, error)
}
@@ -0,0 +1,22 @@
package transaction
import (
"RenewCMS/internal/domain/article"
"RenewCMS/internal/domain/author"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image"
"RenewCMS/internal/domain/site"
"context"
)
type Repositories struct {
Articles article.Repository
Sites site.Repository
Authors author.Repository
Entries entry.Repository
Images image.Repository
}
type Transactor interface {
Run(ctx context.Context, work func(Repositories) error) error
}
+26
View File
@@ -18,9 +18,19 @@ var ErrInvalidDisplayName = errors.New("invalid display name")
var ErrUsernameTaken = errors.New("username taken") var ErrUsernameTaken = errors.New("username taken")
var ErrInvalidLookup = errors.New("invalid user lookup") var ErrInvalidLookup = errors.New("invalid user lookup")
var ErrVerificationEmailNotSent = errors.New("verification email not sent") var ErrVerificationEmailNotSent = errors.New("verification email not sent")
var ErrPasswordTooLong = errors.New("password too long")
const MaxLookupIDs = 100 const MaxLookupIDs = 100
const MaxPasswordBytes = 72
func ValidatePassword(password string) error {
if len(password) > MaxPasswordBytes {
return ErrPasswordTooLong
}
return nil
}
type Role string type Role string
const ( const (
@@ -45,6 +55,22 @@ type User struct {
UpdatedAt time.Time `json:"updated_at"` UpdatedAt time.Time `json:"updated_at"`
} }
const UnverifiedRetention = 7 * 24 * time.Hour
func (u User) IsStaleUnverifiedAt(now time.Time) bool {
if u.IsVerified {
return false
}
deadline := u.VerificationExpiration
if deadline.IsZero() {
deadline = u.CreatedAt
}
if deadline.IsZero() {
return false
}
return now.After(deadline.Add(UnverifiedRetention))
}
func (u User) NameOrUsername() string { func (u User) NameOrUsername() string {
if trimmed := strings.TrimSpace(u.DisplayName); trimmed != "" { if trimmed := strings.TrimSpace(u.DisplayName); trimmed != "" {
return trimmed return trimmed
+142
View File
@@ -0,0 +1,142 @@
package config
import (
"bufio"
"fmt"
"io"
"os"
"strings"
)
const (
dotenvExportPrefix = "export "
dotenvCommentMarker = "#"
dotenvInlineComment = " #"
dotenvByteOrderMark = "\xef\xbb\xbf"
dotenvMaxLineBytes = 1 << 20
dotenvAssignment = "="
dotenvDoubleQuote = '"'
dotenvSingleQuote = '\''
dotenvEscapeBackslash = '\\'
)
var dotenvDoubleQuoteEscapes = map[byte]byte{
'n': '\n',
'r': '\r',
't': '\t',
'"': '"',
'\\': '\\',
}
func LoadDotenv(path string) error {
file, err := os.Open(path)
if err != nil {
return err
}
defer func() { _ = file.Close() }()
values, err := ParseDotenv(file)
if err != nil {
return fmt.Errorf("%s: %w", path, err)
}
for name, value := range values {
if _, isSet := os.LookupEnv(name); !isSet {
if err := os.Setenv(name, value); err != nil {
return err
}
}
}
return nil
}
func ParseDotenv(reader io.Reader) (map[string]string, error) {
scanner := bufio.NewScanner(reader)
scanner.Buffer(make([]byte, 0, bufio.MaxScanTokenSize), dotenvMaxLineBytes)
values := map[string]string{}
for lineNumber := 1; scanner.Scan(); lineNumber++ {
line := strings.TrimSpace(strings.TrimPrefix(scanner.Text(), dotenvByteOrderMark))
if line == "" || strings.HasPrefix(line, dotenvCommentMarker) {
continue
}
name, value, err := parseDotenvAssignment(line)
if err != nil {
return nil, fmt.Errorf("line %d: %w", lineNumber, err)
}
values[name] = value
}
return values, scanner.Err()
}
func parseDotenvAssignment(line string) (string, string, error) {
line = strings.TrimSpace(strings.TrimPrefix(line, dotenvExportPrefix))
name, raw, found := strings.Cut(line, dotenvAssignment)
name = strings.TrimSpace(name)
if !found || !isDotenvName(name) {
return "", "", fmt.Errorf("expected NAME=value")
}
value, err := parseDotenvValue(strings.TrimSpace(raw))
return name, value, err
}
func isDotenvName(name string) bool {
if name == "" {
return false
}
for _, r := range name {
isLetter := r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z'
isDigit := r >= '0' && r <= '9'
if !isLetter && !isDigit && r != '_' && r != '.' {
return false
}
}
return true
}
func parseDotenvValue(raw string) (string, error) {
if raw == "" {
return "", nil
}
switch raw[0] {
case dotenvDoubleQuote:
return parseDoubleQuoted(raw)
case dotenvSingleQuote:
return parseSingleQuoted(raw)
}
if comment := strings.Index(raw, dotenvInlineComment); comment >= 0 {
raw = raw[:comment]
}
return strings.TrimSpace(raw), nil
}
func parseSingleQuoted(raw string) (string, error) {
end := strings.IndexByte(raw[1:], dotenvSingleQuote)
if end < 0 {
return "", fmt.Errorf("unterminated single quote")
}
return raw[1 : 1+end], nil
}
func parseDoubleQuoted(raw string) (string, error) {
var value strings.Builder
for i := 1; i < len(raw); i++ {
switch raw[i] {
case dotenvDoubleQuote:
return value.String(), nil
case dotenvEscapeBackslash:
i++
if i >= len(raw) {
return "", fmt.Errorf("unterminated double quote")
}
if unescaped, known := dotenvDoubleQuoteEscapes[raw[i]]; known {
value.WriteByte(unescaped)
} else {
value.WriteByte(dotenvEscapeBackslash)
value.WriteByte(raw[i])
}
default:
value.WriteByte(raw[i])
}
}
return "", fmt.Errorf("unterminated double quote")
}
@@ -0,0 +1,39 @@
package config
import (
"errors"
"fmt"
"os"
)
const (
EnvJWTSecret = "JWT_SECRET"
MinJWTSecretBytes = 32
EnvSmtpAllowInsecure = "SMTP_ALLOW_INSECURE"
DefaultSmtpAllowInsecure = "false"
)
var ErrWeakJWTSecret = errors.New("JWT_SECRET is too weak")
var placeholderJWTSecrets = map[string]bool{
"change-me-to-a-long-random-string": true,
"replace-with-output-of-openssl-rand-hex-32": true,
}
func ValidateJWTSecret(secret string) error {
if placeholderJWTSecrets[secret] {
return fmt.Errorf("%w: it is still the example value; generate one with `openssl rand -hex 32`", ErrWeakJWTSecret)
}
if len(secret) < MinJWTSecretBytes {
return fmt.Errorf("%w: it must be at least %d bytes long; generate one with `openssl rand -hex 32`", ErrWeakJWTSecret, MinJWTSecretBytes)
}
return nil
}
func jwtSecretFromEnv() (string, error) {
secret := os.Getenv(EnvJWTSecret)
if err := ValidateJWTSecret(secret); err != nil {
return "", err
}
return secret, nil
}
+13 -1
View File
@@ -14,6 +14,7 @@ type SmtpSettings struct {
Password string Password string
Host string Host string
Port int Port int
AllowInsecure bool
} }
type AuthRateLimitSettings struct { type AuthRateLimitSettings struct {
@@ -55,11 +56,21 @@ func (s Settings) IsProduction() bool {
} }
func NewSettingsFromEnv() (Settings, error) { func NewSettingsFromEnv() (Settings, error) {
jwtSecret, err := jwtSecretFromEnv()
if err != nil {
return Settings{}, err
}
smtpPort, err := intEnv("SMTP_PORT") smtpPort, err := intEnv("SMTP_PORT")
if err != nil { if err != nil {
return Settings{}, err return Settings{}, err
} }
smtpAllowInsecure, err := boolEnv(EnvSmtpAllowInsecure, DefaultSmtpAllowInsecure)
if err != nil {
return Settings{}, err
}
authRateLimitMaxAttempts, err := intEnv("AUTH_RATE_LIMIT_MAX_ATTEMPTS") authRateLimitMaxAttempts, err := intEnv("AUTH_RATE_LIMIT_MAX_ATTEMPTS")
if err != nil { if err != nil {
return Settings{}, err return Settings{}, err
@@ -100,7 +111,7 @@ func NewSettingsFromEnv() (Settings, error) {
CorsAllowedOrigins: parseSemicolonSeparatedList(os.Getenv("CORS_ALLOWED_ORIGINS")), CorsAllowedOrigins: parseSemicolonSeparatedList(os.Getenv("CORS_ALLOWED_ORIGINS")),
PublicURL: os.Getenv("PUBLIC_URL"), PublicURL: os.Getenv("PUBLIC_URL"),
UploadDir: os.Getenv("UPLOAD_DIR"), UploadDir: os.Getenv("UPLOAD_DIR"),
JWTSecret: os.Getenv("JWT_SECRET"), JWTSecret: jwtSecret,
DBFile: os.Getenv("DB_FILE"), DBFile: os.Getenv("DB_FILE"),
Database: database, Database: database,
Storage: storage, Storage: storage,
@@ -112,6 +123,7 @@ func NewSettingsFromEnv() (Settings, error) {
Password: os.Getenv("SMTP_PASSWORD"), Password: os.Getenv("SMTP_PASSWORD"),
Host: os.Getenv("SMTP_HOST"), Host: os.Getenv("SMTP_HOST"),
Port: smtpPort, Port: smtpPort,
AllowInsecure: smtpAllowInsecure,
}, },
AuthRateLimit: AuthRateLimitSettings{ AuthRateLimit: AuthRateLimitSettings{
MaxAttempts: authRateLimitMaxAttempts, MaxAttempts: authRateLimitMaxAttempts,
@@ -0,0 +1,75 @@
package imaging
import (
"bytes"
"encoding/binary"
)
const (
tiffOrientationTag = 0x0112
tiffTypeShort = 3
tiffHeaderSize = 8
tiffEntrySize = 12
tiffMagic = 42
uprightOrientation = 1
maxOrientation = 8
)
var exifHeader = []byte("Exif\x00\x00")
func exifOrientation(payload []byte) (uint16, bool) {
tiff := bytes.TrimPrefix(payload, exifHeader)
if len(tiff) < tiffHeaderSize {
return 0, false
}
var order binary.ByteOrder
switch string(tiff[:2]) {
case "II":
order = binary.LittleEndian
case "MM":
order = binary.BigEndian
default:
return 0, false
}
if order.Uint16(tiff[2:]) != tiffMagic {
return 0, false
}
ifd := int(order.Uint32(tiff[4:]))
if ifd < tiffHeaderSize || ifd+2 > len(tiff) {
return 0, false
}
count := int(order.Uint16(tiff[ifd:]))
for i := range count {
entry := ifd + 2 + i*tiffEntrySize
if entry+tiffEntrySize > len(tiff) {
return 0, false
}
if order.Uint16(tiff[entry:]) != tiffOrientationTag || order.Uint16(tiff[entry+2:]) != tiffTypeShort {
continue
}
value := order.Uint16(tiff[entry+8:])
if value < uprightOrientation || value > maxOrientation {
return 0, false
}
return value, true
}
return 0, false
}
func needsOrientation(orientation uint16) bool {
return orientation > uprightOrientation
}
func orientationOnlyTIFF(orientation uint16) []byte {
tiff := make([]byte, 0, tiffHeaderSize+2+tiffEntrySize+4)
tiff = append(tiff, 'M', 'M')
tiff = binary.BigEndian.AppendUint16(tiff, tiffMagic)
tiff = binary.BigEndian.AppendUint32(tiff, tiffHeaderSize)
tiff = binary.BigEndian.AppendUint16(tiff, 1)
tiff = binary.BigEndian.AppendUint16(tiff, tiffOrientationTag)
tiff = binary.BigEndian.AppendUint16(tiff, tiffTypeShort)
tiff = binary.BigEndian.AppendUint32(tiff, 1)
tiff = binary.BigEndian.AppendUint16(tiff, orientation)
tiff = binary.BigEndian.AppendUint16(tiff, 0)
return binary.BigEndian.AppendUint32(tiff, 0)
}
@@ -0,0 +1,168 @@
package imaging
import (
"bytes"
"encoding/binary"
)
const (
jpegMarkerPrefix = 0xFF
jpegSOI = 0xD8
jpegEOI = 0xD9
jpegSOS = 0xDA
jpegTEM = 0x01
jpegRST0 = 0xD0
jpegRST7 = 0xD7
jpegAPP0 = 0xE0
jpegAPP1 = 0xE1
jpegAPP2 = 0xE2
jpegAPP14 = 0xEE
jpegAPP15 = 0xEF
jpegCOM = 0xFE
jpegStuffedZero = 0x00
)
var iccProfileSignature = []byte("ICC_PROFILE\x00")
type jpegSegment struct {
marker byte
payload []byte
}
func stripJPEG(data []byte) ([]byte, error) {
if len(data) < 4 || data[0] != jpegMarkerPrefix || data[1] != jpegSOI {
return nil, errMalformedContainer
}
out := []byte{jpegMarkerPrefix, jpegSOI}
insertAt := len(out)
orientation := uint16(uprightOrientation)
first := true
for pos := 2; ; {
marker, next, err := readJPEGMarker(data, pos)
if err != nil {
return nil, err
}
pos = next
if marker == jpegEOI {
out = append(out, jpegMarkerPrefix, jpegEOI)
return withOrientationSegment(out, insertAt, orientation), nil
}
if isStandaloneJPEGMarker(marker) {
out = append(out, jpegMarkerPrefix, marker)
continue
}
segment, next, err := readJPEGSegment(data, pos, marker)
if err != nil {
return nil, err
}
pos = next
if isJPEGMetadata(segment) {
if found, ok := jpegExifOrientation(segment); ok {
orientation = found
}
} else {
out = appendJPEGSegment(out, segment)
if first && segment.marker == jpegAPP0 {
insertAt = len(out)
}
}
first = false
if marker == jpegSOS {
end := jpegScanEnd(data, pos)
out = append(out, data[pos:end]...)
if end == len(data) {
return withOrientationSegment(out, insertAt, orientation), nil
}
pos = end
}
}
}
func readJPEGMarker(data []byte, pos int) (byte, int, error) {
if pos >= len(data) || data[pos] != jpegMarkerPrefix {
return 0, 0, errMalformedContainer
}
for pos < len(data) && data[pos] == jpegMarkerPrefix {
pos++
}
if pos >= len(data) {
return 0, 0, errMalformedContainer
}
return data[pos], pos + 1, nil
}
func readJPEGSegment(data []byte, pos int, marker byte) (jpegSegment, int, error) {
if pos+2 > len(data) {
return jpegSegment{}, 0, errMalformedContainer
}
length := int(binary.BigEndian.Uint16(data[pos:]))
if length < 2 || pos+length > len(data) {
return jpegSegment{}, 0, errMalformedContainer
}
return jpegSegment{marker: marker, payload: data[pos+2 : pos+length]}, pos + length, nil
}
func jpegScanEnd(data []byte, pos int) int {
for pos < len(data) {
if data[pos] != jpegMarkerPrefix || pos+1 >= len(data) {
pos++
continue
}
next := data[pos+1]
if next == jpegStuffedZero || isRestartMarker(next) {
pos += 2
continue
}
return pos
}
return len(data)
}
func isStandaloneJPEGMarker(marker byte) bool {
return marker == jpegTEM || isRestartMarker(marker)
}
func isRestartMarker(marker byte) bool {
return marker >= jpegRST0 && marker <= jpegRST7
}
func isJPEGMetadata(segment jpegSegment) bool {
if segment.marker == jpegCOM {
return true
}
if segment.marker == jpegAPP2 {
return !bytes.HasPrefix(segment.payload, iccProfileSignature)
}
if segment.marker == jpegAPP0 || segment.marker == jpegAPP14 {
return false
}
return segment.marker >= jpegAPP1 && segment.marker <= jpegAPP15
}
func jpegExifOrientation(segment jpegSegment) (uint16, bool) {
if segment.marker != jpegAPP1 || !bytes.HasPrefix(segment.payload, exifHeader) {
return 0, false
}
return exifOrientation(segment.payload)
}
func appendJPEGSegment(out []byte, segment jpegSegment) []byte {
out = append(out, jpegMarkerPrefix, segment.marker)
out = binary.BigEndian.AppendUint16(out, uint16(len(segment.payload)+2))
return append(out, segment.payload...)
}
func withOrientationSegment(out []byte, insertAt int, orientation uint16) []byte {
if !needsOrientation(orientation) {
return out
}
payload := append(bytes.Clone(exifHeader), orientationOnlyTIFF(orientation)...)
segment := appendJPEGSegment(nil, jpegSegment{marker: jpegAPP1, payload: payload})
return append(out[:insertAt:insertAt], append(segment, out[insertAt:]...)...)
}
Loaded 100 of 381 files, more files were not shown because too many files have changed in this diff. Show more