Compare commits

..
69 Commits
Author SHA1 Message Date
Florian Sylvain 3e02e14da4 refac: missing mutation tests, spa specs, checks shown to pass, touch targets, catalogue entry, production code 2026-11-04 03:04:35 +01:00
Florian Sylvain 7c15206170 refac: article reads, story delete, no leaks, stored SEO status, rate limit, cleanup (%site%, article repo split, old lang repos, one default per site rule to domain) 2026-11-03 16:01:52 +01:00
Florian Sylvain 9d284e65a9 refac: migration crash, real-database tests, site deleted during create, ruels out of the repo, lists 2026-11-03 05:06:04 +01:00
Florian Sylvain 680b9a1308 feat: article editor header redesign 2026-11-03 04:24:44 +01:00
Florian Sylvain 58fd753559 fix: bottom border on article list filter tabs 2026-11-03 04:12:05 +01:00
Florian Sylvain 3da62db61b fix: missing text-start in editor language select and overflow menu 2026-11-03 04:00:40 +01:00
Florian Sylvain c390fcfe8d feat: public API, SEO and existing surfaces 2026-11-03 03:58:10 +01:00
Florian Sylvain 45fbbc33b1 feat: translation flows, revision conflicts, delete scopes, article moves and a target site for new articles 2026-11-03 00:12:29 +01:00
Florian Sylvain 339e646eb8 feat: editor language menu, title field, header actions, publish dialogs, read-only rendering and draft recovery 2026-11-02 17:13:14 +01:00
Florian Sylvain a671b81f80 feat: editorial article list 2026-11-02 07:28:44 +01:00
Florian Sylvain a0b3c58c52 feat: editor write path 2026-11-02 03:24:30 +01:00
Florian Sylvain d9158025d4 feat: site languages, setup and site URL settings 2026-11-01 22:13:02 +01:00
Florian Sylvain 0806733d5c feat: storage, language rules and migration 2026-11-01 17:50:28 +01:00
Florian Sylvain 8c4a1825ab chore: redesign article localization before implementation 2026-11-01 14:57:07 +01:00
Florian Sylvain 99a74dc3a2 chore: articles localization groundwork 2026-10-31 21:22:44 +01:00
Florian Sylvain 0bdcca8a90 fix: mcp server media sending 2026-10-31 16:54:34 +01:00
Florian Sylvain 63b671c6f3 docs: getting started doc 2026-10-31 01:35:02 +01:00
Florian Sylvain ed0686085a docs: release notes for v3.7.2-beta 2026-10-30 21:38:08 +01:00
Florian Sylvain f3fcdf9ce9 fix: added items-center to the item class of the role select 2026-10-30 21:24:52 +01:00
Florian Sylvain 018fc98295 docs: release notes for v3.7.1-beta 2026-10-30 21:08:47 +01:00
Florian Sylvain 03f5d54bb6 fix: contrast on the selected role card 2026-10-30 21:07:21 +01:00
Florian Sylvain 39ff84e967 fix: user can edit its own author from author list page 2026-10-30 20:48:46 +01:00
Florian Sylvain f084ccb66f fix: create author button height in article editor 2026-10-30 20:47:52 +01:00
Florian Sylvain c92d8740ed docs: consolidate design change logs and refresh stale docs 2026-10-30 20:40:24 +01:00
Florian Sylvain c050db78d2 docs: release notes for v3.7.0-beta 2026-10-30 20:20:51 +01:00
Florian Sylvain 10a66cd979 feat: change email, export my data, delete account (with data anonymization) 2026-10-30 20:19:07 +01:00
Florian Sylvain bb191c389a chore: gdpr features design groundwork 2026-10-29 23:24:15 +01:00
Florian Sylvain c6d49db95e chore: updated reference design to app changes and fixes 2026-10-29 18:07:06 +01:00
Florian Sylvain 8cdd70bd81 fix: french buttons labels overflowing 2026-10-29 17:16:19 +01:00
Florian Sylvain b40a792d02 fix: hide date separators when date picker field idle, to prevent overlapping labels 2026-10-29 17:14:02 +01:00
Florian Sylvain 7a66318a73 fix: sticky footer on role editor 2026-10-29 17:11:40 +01:00
Florian Sylvain 89da2f6b14 fix: "used in" media badge color when selected readabiltiy issue 2026-10-29 17:09:17 +01:00
Florian Sylvain fda2793888 fix: add details to media panel when image is used in author or site 2026-10-29 17:05:25 +01:00
Florian Sylvain 63c0aec444 fix: visual issues (footer floating, table elements overflowing each others) 2026-10-29 16:57:39 +01:00
Florian Sylvain b39a41be88 refac: DELETE /v1/user/{id}?expected_role_id=N, user.remove audit event, 409 target_role_not_found, GetAll returns its error, Own-scope visibility filter moved into repos, JSON tags removed from use-case types 2026-10-29 16:28:25 +01:00
Florian Sylvain 5d6f378fce refac: stale test entries, failing web tests, Postgre backup bug, Hardcoded MySQL table count, Stale Postgre connection in test, own-scope visibility filter, GetAll ignoring its error, JSON tags in use-case types, 31 copies of DESKTOP_QUERY, ProfileView endpoint paths 2026-10-28 17:54:10 +01:00
Florian Sylvain efecdee200 docs: release notes for v3.6.0-beta 2026-10-28 00:13:30 +01:00
Florian Sylvain 34dffe222f feat: roles SPA Users, Profile, API keys, Activity 2026-10-28 00:10:15 +01:00
Florian Sylvain 3db490a615 feat: SPA Roles screens 2026-10-27 23:05:04 +01:00
Florian Sylvain 907949aa12 feat: roles SPA foundations 2026-10-27 22:21:12 +01:00
Florian Sylvain 80f7037d3a feat: Users API, ownership transfer and removal of the legacy role string 2026-10-27 03:08:15 +01:00
Florian Sylvain 094df63a7f feat: /v1/role list, get, create, update and delete. Reassign members on delete. Write-time validation (ValidateGrants, duplicates, typed keys against real content types). Name uniqueness (role_name_taken), role_locked, role_has_members, role_conflict on version mismatch. No-escalation: nobody grants a permission they don't hold, and roles.edit_owner_only guards the Owner role. Activity events for role changes. Typed-key exposure in /auth/me. Cleanup of typed rows when a content type is deleted. | Backend only. Will carry the deferred ListGrants decision. 2026-10-27 00:45:24 +01:00
Florian Sylvain a043f7f41a refac: debt on role backend 2026-10-26 23:34:35 +01:00
Florian Sylvain de142f6c5f feat: more role backend and admin/writer roles additions and adjustments 2026-10-26 18:15:26 +01:00
Florian Sylvain 8c6c6456da feat: roles system backend 2026-10-26 05:02:49 +01:00
Florian Sylvain 44cca46d5e chore: roles management groundwork 2026-10-26 02:53:33 +01:00
Florian Sylvain 7c0ee21906 feat: updated integration page with missing API routes 2026-10-26 02:18:35 +01:00
Florian Sylvain 25d9c30b8a feat: integration search bar 2026-10-25 21:57:43 +01:00
Florian Sylvain a8fea8d900 fix: changed "Jump to" so it scrolls only the page's own scroll container 2026-10-25 20:26:52 +01:00
Florian Sylvain a0fdf03be0 docs: release notes for v3.5.3-beta 2026-10-23 01:57:29 +02:00
Florian Sylvain 9ab98fd50c fix: response schema is now inferred from each endpoint's sample JSON 2026-10-23 01:56:35 +02:00
Florian Sylvain d2af39da61 docs: release notes for v3.5.2-beta 2026-10-23 01:31:51 +02:00
Florian Sylvain 4cff43fefb feat: llms.txt and llms-full.txt, openapi.json, MCP server 2026-10-23 01:29:59 +02:00
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
1429 changed files with 141092 additions and 7467 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
+6
View File
@@ -28,3 +28,9 @@ CLAUDE.md
.agents/ .agents/
AGENTS.md AGENTS.md
codex-workflow.md codex-workflow.md
CODING_STANDARDS.md
tools/product-videos/
# Generated LLM docs
internal/infrastructure/llmdocs/generated/*
!internal/infrastructure/llmdocs/generated/.gitkeep
-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)
+6 -1
View File
@@ -4,8 +4,12 @@ COPY web/package.json web/bun.lock ./
RUN bun install --frozen-lockfile RUN bun install --frozen-lockfile
COPY web/ ./ COPY web/ ./
RUN bun run build-only RUN bun run build-only
WORKDIR /src
COPY docs/ ./docs/
COPY scripts/generate-llms.ts ./scripts/generate-llms.ts
RUN bun scripts/generate-llms.ts
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
@@ -13,6 +17,7 @@ COPY go.mod go.sum ./
RUN go mod download RUN go mod download
COPY . . COPY . .
COPY --from=web /src/internal/infrastructure/assets/dist ./internal/infrastructure/assets/dist COPY --from=web /src/internal/infrastructure/assets/dist ./internal/infrastructure/assets/dist
COPY --from=web /src/internal/infrastructure/llmdocs/generated ./internal/infrastructure/llmdocs/generated
RUN go build -trimpath -ldflags "-s -w -X main.version=${VERSION}" -o /out/renewcms ./cmd/server RUN go build -trimpath -ldflags "-s -w -X main.version=${VERSION}" -o /out/renewcms ./cmd/server
FROM alpine:3.22 FROM alpine:3.22
+5 -6
View File
@@ -27,7 +27,7 @@ Upgrade with `docker compose pull && docker compose up -d`. The image is `git.fl
### Updates from the browser ### Updates from the browser
On Linux with systemd, install v2.6.0-beta or newer manually, then follow [the browser-update setup guide](docs/deployment.md#browser-updates). It covers finding the actual database directory, installing the helper, testing a restart and troubleshooting. Other platforms use manual upgrades. On Linux with systemd, install the helper manually once, then follow [the browser-update setup guide](docs/deployment.md#browser-updates). It covers finding the actual database directory, installing the helper, testing a restart and troubleshooting. Other platforms use manual upgrades.
### Develop ### Develop
@@ -43,18 +43,17 @@ task dev # API with hot reload + Vite HMR → http://localhost:51
| Doc | Contents | | Doc | Contents |
|---|---| |---|---|
| [docs/getting-started.md](docs/getting-started.md) | Set up an instance: download the binary or start Docker, fill the settings, HTTPS, first login |
| [docs/development.md](docs/development.md) | Dev setup, how Vite and the API fit together, tests, lint, `task` commands | | [docs/development.md](docs/development.md) | Dev setup, how Vite and the API fit together, tests, lint, `task` commands |
| [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 |
| [docs/api/articles.md](docs/api/articles.md) | Reading articles: pagination, search, `format` and body schemas | | [docs/api/articles.md](docs/api/articles.md) | Reading articles: pagination, search, `format` and body schemas |
| [docs/custom-content-types.md](docs/custom-content-types.md) | Custom content types: layering, phase 1 limitations and their fix path | | [docs/api/site-languages.md](docs/api/site-languages.md) | Site languages, first-time language setup and the public URL pattern |
| [docs/custom-content-types.md](docs/custom-content-types.md) | Custom content types: layering and known limitations |
| [docs/image-variants.md](docs/image-variants.md) | Image variants and their cache | | [docs/image-variants.md](docs/image-variants.md) | Image variants and their cache |
| [docs/release-notes.md](docs/release-notes.md) | Release notes format, the published releases and how to publish one | | [docs/release-notes.md](docs/release-notes.md) | Release notes format, the published releases and how to publish one |
## TODOs
- Cancel button when email validation pending or expired
+27 -4
View File
@@ -3,6 +3,7 @@ version: '3'
vars: vars:
BINARY: renewcms BINARY: renewcms
DIST_DIR: internal/infrastructure/assets/dist DIST_DIR: internal/infrastructure/assets/dist
LLMS_DIR: internal/infrastructure/llmdocs/generated
VERSION: VERSION:
sh: git describe --tags --always --dirty sh: git describe --tags --always --dirty
LDFLAGS: -s -w -X main.version={{.VERSION}} LDFLAGS: -s -w -X main.version={{.VERSION}}
@@ -32,6 +33,7 @@ tasks:
dev:api: dev:api:
desc: Run the API with hot reload on :8080 (SPA not embedded) desc: Run the API with hot reload on :8080 (SPA not embedded)
deps: [build:llms]
cmds: cmds:
- air - air
@@ -77,7 +79,7 @@ tasks:
return 1 return 1
fi fi
echo "== $IMAGE on 127.0.0.1:$PORT" echo "== $IMAGE on 127.0.0.1:$PORT"
RENEWCMS_TEST_MYSQL_DSN="root:$PASSWORD@tcp(127.0.0.1:$PORT)/mysql" go test -tags nofrontend ./test/... -run MySQL -count=1 {{.CLI_ARGS}} RENEWCMS_TEST_MYSQL_DSN="root:$PASSWORD@tcp(127.0.0.1:$PORT)/mysql" go test -tags nofrontend ./test/... -run 'MySQL|TestLocalizationPersistence' -count=1 -timeout 20m {{.CLI_ARGS}}
RESULT=$? RESULT=$?
docker rm -f "$NAME" >/dev/null 2>&1 docker rm -f "$NAME" >/dev/null 2>&1
return $RESULT return $RESULT
@@ -117,7 +119,7 @@ tasks:
return 1 return 1
fi fi
echo "== $IMAGE on 127.0.0.1:$PORT" echo "== $IMAGE on 127.0.0.1:$PORT"
RENEWCMS_TEST_POSTGRES_DSN="postgres://postgres:$PASSWORD@127.0.0.1:$PORT/postgres?sslmode=disable" go test -tags nofrontend ./test/... -run Postgres -count=1 {{.CLI_ARGS}} RENEWCMS_TEST_POSTGRES_DSN="postgres://postgres:$PASSWORD@127.0.0.1:$PORT/postgres?sslmode=disable" go test -tags nofrontend ./test/... -run 'Postgres|TestLocalizationPersistence' -count=1 -timeout 20m {{.CLI_ARGS}}
RESULT=$? RESULT=$?
docker rm -f "$NAME" >/dev/null 2>&1 docker rm -f "$NAME" >/dev/null 2>&1
return $RESULT return $RESULT
@@ -194,6 +196,13 @@ tasks:
cmds: cmds:
- bun visual/check.ts {{.CLI_ARGS}} - bun visual/check.ts {{.CLI_ARGS}}
visual:touch:
desc: Measure the computed height and tap area of the mobile touch targets at 390 px (Playwright)
dir: web
deps: [web:install]
cmds:
- bun visual/touchTargets.ts
lint: lint:
desc: gofmt check, go vet, eslint (--fix) and vue-tsc desc: gofmt check, go vet, eslint (--fix) and vue-tsc
cmds: cmds:
@@ -231,22 +240,36 @@ 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
build:llms:
desc: Generate llms.txt, llms-full.txt and openapi.json from the route catalogue and docs/ → {{.LLMS_DIR}}
deps: [web:install]
sources: [scripts/generate-llms.ts, web/src/data/apiCatalogue.ts, docs/api.md, docs/api/*.md, docs/llm/*.md, docs/configuration.md]
generates: ['{{.LLMS_DIR}}/llms-full.txt']
cmds:
- bun scripts/generate-llms.ts
build: build:
desc: Production binary for this machine → bin/{{.BINARY}} desc: Production binary for this machine → bin/{{.BINARY}}
deps: [build:web] deps: [build:web, build:llms]
cmds: cmds:
- go build -trimpath -ldflags "{{.LDFLAGS}}" -o bin/{{.BINARY}}{{exeExt}} ./cmd/server - go build -trimpath -ldflags "{{.LDFLAGS}}" -o bin/{{.BINARY}}{{exeExt}} ./cmd/server
build:mcp:
desc: MCP server (stdio) for this machine → bin/{{.BINARY}}-mcp
cmds:
- go build -trimpath -ldflags "{{.LDFLAGS}}" -o bin/{{.BINARY}}-mcp{{exeExt}} ./cmd/mcp
release: release:
desc: Cross-compile and sign production binaries for all release targets → bin/ (needs RELEASE_SIGNING_KEY) desc: Cross-compile and sign production binaries for all release targets → bin/ (needs RELEASE_SIGNING_KEY)
cmds: cmds:
- task: release:check - task: release:check
- task: build:web - task: build:web
- task: build:llms
- for: { var: RELEASE_TARGETS } - for: { var: RELEASE_TARGETS }
task: build:target task: build:target
vars: vars:
+111 -30
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"
@@ -9,9 +10,13 @@ import (
domainEntry "RenewCMS/internal/domain/entry" domainEntry "RenewCMS/internal/domain/entry"
domainImage "RenewCMS/internal/domain/image" domainImage "RenewCMS/internal/domain/image"
domainInvite "RenewCMS/internal/domain/invite" domainInvite "RenewCMS/internal/domain/invite"
domainLocalization "RenewCMS/internal/domain/localization"
domainMail "RenewCMS/internal/domain/mail" domainMail "RenewCMS/internal/domain/mail"
domainPurge "RenewCMS/internal/domain/purge" domainPurge "RenewCMS/internal/domain/purge"
domainRole "RenewCMS/internal/domain/role"
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 +41,17 @@ 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 publicReadLimitOnce sync.Once
publicReadLimitMiddleware func(http.Handler) http.Handler
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
@@ -53,16 +59,28 @@ type UseCases struct {
ResolveArticleSEOUseCase *useCases.ResolveArticleSEOUseCase ResolveArticleSEOUseCase *useCases.ResolveArticleSEOUseCase
CheckArticleSEOUseCase *useCases.CheckArticleSEOUseCase CheckArticleSEOUseCase *useCases.CheckArticleSEOUseCase
ListSitemapUseCase *useCases.ListSitemapUseCase ListSitemapUseCase *useCases.ListSitemapUseCase
ResolvePublicArticleUseCase *useCases.ResolvePublicArticleUseCase
DeleteArticleUseCase *useCases.DeleteArticleUseCase DeleteArticleUseCase *useCases.DeleteArticleUseCase
CreateTranslationUseCase *useCases.CreateTranslationUseCase
DescribeArticleUseCase *useCases.DescribeArticleUseCase
MoveStoryUseCase *useCases.MoveStoryUseCase
DeleteStoryUseCase *useCases.DeleteStoryUseCase
ListAuthorsUseCase *useCases.ListAuthorsUseCase ListAuthorsUseCase *useCases.ListAuthorsUseCase
CreateAuthorUseCase *useCases.CreateAuthorUseCase CreateAuthorUseCase *useCases.CreateAuthorUseCase
CreateMyAuthorUseCase *useCases.CreateMyAuthorUseCase CreateMyAuthorUseCase *useCases.CreateMyAuthorUseCase
UpdateAuthorUseCase *useCases.UpdateAuthorUseCase UpdateAuthorUseCase *useCases.UpdateAuthorUseCase
DeleteAuthorUseCase *useCases.DeleteAuthorUseCase DeleteAuthorUseCase *useCases.DeleteAuthorUseCase
GetMyAuthorUseCase *useCases.GetMyAuthorUseCase GetMyAuthorUseCase *useCases.GetMyAuthorUseCase
GetMyAccessUseCase *useCases.GetMyAccessUseCase
CheckPermissionUseCase *useCases.CheckPermissionUseCase
ListPermissionsUseCase *useCases.ListPermissionsUseCase
ListSitesUseCase *useCases.ListSitesUseCase ListSitesUseCase *useCases.ListSitesUseCase
CreateSiteUseCase *useCases.CreateSiteUseCase CreateSiteUseCase *useCases.CreateSiteUseCase
UpdateSiteUseCase *useCases.UpdateSiteUseCase UpdateSiteUseCase *useCases.UpdateSiteUseCase
GetSiteLanguagesUseCase *useCases.GetSiteLanguagesUseCase
UpdateSiteLanguagesUseCase *useCases.UpdateSiteLanguagesUseCase
GetLanguageSetupUseCase *useCases.GetLanguageSetupUseCase
ApplyLanguageSetupUseCase *useCases.ApplyLanguageSetupUseCase
SetDefaultSiteUseCase *useCases.SetDefaultSiteUseCase SetDefaultSiteUseCase *useCases.SetDefaultSiteUseCase
DeleteSiteUseCase *useCases.DeleteSiteUseCase DeleteSiteUseCase *useCases.DeleteSiteUseCase
CreateContentTypeUseCase *useCases.CreateContentTypeUseCase CreateContentTypeUseCase *useCases.CreateContentTypeUseCase
@@ -70,6 +88,12 @@ type UseCases struct {
GetContentTypeUseCase *useCases.GetContentTypeUseCase GetContentTypeUseCase *useCases.GetContentTypeUseCase
UpdateContentTypeUseCase *useCases.UpdateContentTypeUseCase UpdateContentTypeUseCase *useCases.UpdateContentTypeUseCase
DeleteContentTypeUseCase *useCases.DeleteContentTypeUseCase DeleteContentTypeUseCase *useCases.DeleteContentTypeUseCase
ListRolesUseCase *useCases.ListRolesUseCase
GetRoleUseCase *useCases.GetRoleUseCase
CreateRoleUseCase *useCases.CreateRoleUseCase
UpdateRoleUseCase *useCases.UpdateRoleUseCase
DeleteRoleUseCase *useCases.DeleteRoleUseCase
ReassignRoleMembersUseCase *useCases.ReassignRoleMembersUseCase
ListBuiltinTypesUseCase *useCases.ListBuiltinTypesUseCase ListBuiltinTypesUseCase *useCases.ListBuiltinTypesUseCase
GetBuiltinTypeUseCase *useCases.GetBuiltinTypeUseCase GetBuiltinTypeUseCase *useCases.GetBuiltinTypeUseCase
LookupUserNamesUseCase *useCases.LookupUserNamesUseCase LookupUserNamesUseCase *useCases.LookupUserNamesUseCase
@@ -86,11 +110,20 @@ type UseCases struct {
RequestPasswordResetUseCase *useCases.RequestPasswordResetUseCase RequestPasswordResetUseCase *useCases.RequestPasswordResetUseCase
ResetPasswordUseCase *useCases.ResetPasswordUseCase ResetPasswordUseCase *useCases.ResetPasswordUseCase
UpdateUserProfileUseCase *useCases.UpdateUserProfileUseCase UpdateUserProfileUseCase *useCases.UpdateUserProfileUseCase
RequestEmailChangeUseCase *useCases.RequestEmailChangeUseCase
ResendEmailChangeUseCase *useCases.ResendEmailChangeUseCase
CancelEmailChangeUseCase *useCases.CancelEmailChangeUseCase
ConfirmEmailChangeUseCase *useCases.ConfirmEmailChangeUseCase
ListUsersUseCase *useCases.ListUsersUseCase ListUsersUseCase *useCases.ListUsersUseCase
CreateInviteUseCase *useCases.CreateInviteUseCase CreateInviteUseCase *useCases.CreateInviteUseCase
CancelInviteUseCase *useCases.CancelInviteUseCase CancelInviteUseCase *useCases.CancelInviteUseCase
RenewInviteUseCase *useCases.RenewInviteUseCase RenewInviteUseCase *useCases.RenewInviteUseCase
ListUsersAndInvitesUseCase *useCases.ListUsersAndInvitesUseCase ListUsersAndInvitesUseCase *useCases.ListUsersAndInvitesUseCase
ChangeUserRoleUseCase *useCases.ChangeUserRoleUseCase
RemoveUserUseCase *useCases.RemoveUserUseCase
ExportUserDataUseCase *useCases.ExportUserDataUseCase
DeleteOwnAccountUseCase *useCases.DeleteOwnAccountUseCase
TransferOwnershipUseCase *useCases.TransferOwnershipUseCase
GetInviteUseCase *useCases.GetInviteUseCase GetInviteUseCase *useCases.GetInviteUseCase
AcceptInviteUseCase *useCases.AcceptInviteUseCase AcceptInviteUseCase *useCases.AcceptInviteUseCase
SendMailUseCase *useCases.SendMailUseCase SendMailUseCase *useCases.SendMailUseCase
@@ -139,7 +172,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
} }
@@ -153,13 +186,17 @@ func (c *UseCases) RunSchedulers(ctx context.Context) {
} }
type Repositories struct { type Repositories struct {
ArticleRepo domainArticle.Repository ArticleRepo domainArticle.ListingRepository
SiteRepo domainSite.Repository SiteRepo domainSite.Repository
LocalizationRepo domainLocalization.Repository
ContentTypeRepo domainContentType.Repository ContentTypeRepo domainContentType.Repository
EntryRepo domainEntry.Repository EntryRepo domainEntry.Repository
AuthorRepo domainAuthor.Repository AuthorRepo domainAuthor.Repository
UserRepo domainUser.Repository UserRepo domainUser.Repository
UserEraser domainUser.Eraser
RoleRepo domainRole.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 +204,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
@@ -190,6 +228,8 @@ const (
updateHelperFileName = "update-helper.json" updateHelperFileName = "update-helper.json"
updatesDirName = "updates" updatesDirName = "updates"
backupsDirName = "backups" backupsDirName = "backups"
maxConcurrentDataExports = 2
) )
func imageStorageConfig(settings config.Settings) storage.Config { func imageStorageConfig(settings config.Settings) storage.Config {
@@ -297,11 +337,15 @@ func getRepositories(connection *database.Connection, settings config.Settings)
return &Repositories{ return &Repositories{
ArticleRepo: persistence.NewArticleRepository(db), ArticleRepo: persistence.NewArticleRepository(db),
SiteRepo: persistence.NewSiteRepository(db), SiteRepo: persistence.NewSiteRepository(db),
LocalizationRepo: persistence.NewLocalizationRepository(db),
ContentTypeRepo: persistence.NewContentTypeRepository(db), ContentTypeRepo: persistence.NewContentTypeRepository(db),
EntryRepo: persistence.NewEntryRepository(db), EntryRepo: persistence.NewEntryRepository(db),
AuthorRepo: persistence.NewAuthorRepository(db), AuthorRepo: persistence.NewAuthorRepository(db),
UserRepo: persistence.NewUserRepository(db), UserRepo: persistence.NewUserRepository(db),
UserEraser: persistence.NewAccountEraser(db),
RoleRepo: persistence.NewRoleRepository(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 +353,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),
@@ -329,10 +374,13 @@ func getRepositories(connection *database.Connection, settings config.Settings)
func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings config.Settings) *UseCases { func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings config.Settings) *UseCases {
hasher := hashing.NewBcryptHasher() hasher := hashing.NewBcryptHasher()
mailDispatcher := mailer.NewAsyncDispatcher()
sessionRevocation := useCases.NewSessionRevocationUseCase(repos.SessionRepo, time.Now)
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) mediaUsage := useCases.NewGetMediaUsageUseCase(repos.ImageRepo, repos.ArticleRepo, repos.SiteRepo, repos.AuthorRepo, repos.ContentTypeRepo, repos.EntryRepo)
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)
@@ -341,68 +389,98 @@ func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings
usageTracker := usage.NewTracker(repos.VariantUsageRepo, time.Now) usageTracker := usage.NewTracker(repos.VariantUsageRepo, time.Now)
serveVariant := useCases.NewServeVariantUseCase(repos.VariantRepo, repos.VariantFileRepo, repos.ImageRepo, imageStorage, repos.VariantRenderer, useCases.ServeVariantLimits{MaxSourceBytes: settings.ImageVariantMaxSourceBytes, MaxSourcePixels: settings.ImageVariantMaxSourcePixels, MaxConcurrentRenders: settings.ImageVariantMaxConcurrentRenders}).WithUsageTracker(usageTracker) serveVariant := useCases.NewServeVariantUseCase(repos.VariantRepo, repos.VariantFileRepo, repos.ImageRepo, imageStorage, repos.VariantRenderer, useCases.ServeVariantLimits{MaxSourceBytes: settings.ImageVariantMaxSourceBytes, MaxSourcePixels: settings.ImageVariantMaxSourcePixels, MaxConcurrentRenders: settings.ImageVariantMaxConcurrentRenders}).WithUsageTracker(usageTracker)
moveStory := useCases.NewMoveStoryUseCase(repos.Transactor, repos.ArticleRepo, recorder)
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()),
CreateArticleUseCase: useCases.NewCreateArticleUseCase(repos.ArticleRepo, renderer, recorder, repos.SiteRepo, repos.AuthorRepo), Token: authtoken.New([]byte(settings.JWTSecret), authtoken.WithRevocationStore(sessionRevocation)),
CreateArticleUseCase: useCases.NewCreateArticleUseCase(repos.Transactor, 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, repos.LocalizationRepo),
UpdateArticleUseCase: useCases.NewUpdateArticleUseCase(repos.ArticleRepo, renderer, recorder, repos.SiteRepo, repos.AuthorRepo, repos.ImageRepo), UpdateArticleUseCase: useCases.NewUpdateArticleUseCase(repos.ArticleRepo, renderer, recorder, repos.SiteRepo, repos.AuthorRepo, repos.ImageRepo, repos.LocalizationRepo, moveStory),
DeleteArticleUseCase: useCases.NewDeleteArticleUseCase(repos.ArticleRepo, recorder), DeleteArticleUseCase: useCases.NewDeleteArticleUseCase(repos.ArticleRepo, recorder),
ResolveArticleSEOUseCase: useCases.NewResolveArticleSEOUseCase(repos.ArticleRepo, repos.SiteRepo, repos.ImageRepo), CreateTranslationUseCase: useCases.NewCreateTranslationUseCase(repos.Transactor, repos.ArticleRepo, repos.LocalizationRepo, renderer, recorder),
CheckArticleSEOUseCase: useCases.NewCheckArticleSEOUseCase(repos.ArticleRepo, repos.SiteRepo, repos.ImageRepo), DescribeArticleUseCase: useCases.NewDescribeArticleUseCase(repos.ArticleRepo, repos.LocalizationRepo),
ListSitemapUseCase: useCases.NewListSitemapUseCase(repos.ArticleRepo, repos.SiteRepo), MoveStoryUseCase: moveStory,
DeleteStoryUseCase: useCases.NewDeleteStoryUseCase(repos.Transactor, repos.ArticleRepo, recorder),
ResolveArticleSEOUseCase: useCases.NewResolveArticleSEOUseCase(repos.ArticleRepo, repos.SiteRepo, repos.ImageRepo, repos.LocalizationRepo),
CheckArticleSEOUseCase: useCases.NewCheckArticleSEOUseCase(repos.ArticleRepo, repos.SiteRepo, repos.ImageRepo, repos.LocalizationRepo),
ListSitemapUseCase: useCases.NewListSitemapUseCase(repos.ArticleRepo, repos.SiteRepo, repos.LocalizationRepo),
ResolvePublicArticleUseCase: useCases.NewResolvePublicArticleUseCase(repos.ArticleRepo, repos.SiteRepo, repos.LocalizationRepo, renderer),
ListAuthorsUseCase: useCases.NewListAuthorsUseCase(repos.AuthorRepo, repos.UserRepo), ListAuthorsUseCase: useCases.NewListAuthorsUseCase(repos.AuthorRepo, repos.UserRepo),
CreateAuthorUseCase: useCases.NewCreateAuthorUseCase(repos.AuthorRepo, repos.UserRepo, repos.ImageRepo, recorder), CreateAuthorUseCase: useCases.NewCreateAuthorUseCase(repos.AuthorRepo, repos.UserRepo, repos.ImageRepo, recorder),
CreateMyAuthorUseCase: useCases.NewCreateMyAuthorUseCase(repos.AuthorRepo, repos.UserRepo, recorder), CreateMyAuthorUseCase: useCases.NewCreateMyAuthorUseCase(repos.AuthorRepo, repos.UserRepo, recorder),
UpdateAuthorUseCase: useCases.NewUpdateAuthorUseCase(repos.AuthorRepo, repos.UserRepo, repos.ImageRepo, recorder), UpdateAuthorUseCase: useCases.NewUpdateAuthorUseCase(repos.AuthorRepo, repos.UserRepo, repos.ImageRepo, recorder),
DeleteAuthorUseCase: useCases.NewDeleteAuthorUseCase(repos.AuthorRepo, recorder), DeleteAuthorUseCase: useCases.NewDeleteAuthorUseCase(repos.AuthorRepo, recorder),
GetMyAuthorUseCase: useCases.NewGetMyAuthorUseCase(repos.AuthorRepo), GetMyAuthorUseCase: useCases.NewGetMyAuthorUseCase(repos.AuthorRepo),
GetMyAccessUseCase: useCases.NewGetMyAccessUseCase(repos.RoleRepo, repos.UserRepo),
CheckPermissionUseCase: useCases.NewCheckPermissionUseCase(repos.RoleRepo),
ListPermissionsUseCase: useCases.NewListPermissionsUseCase(),
ListSitesUseCase: useCases.NewListSitesUseCase(repos.SiteRepo), ListSitesUseCase: useCases.NewListSitesUseCase(repos.SiteRepo),
CreateSiteUseCase: useCases.NewCreateSiteUseCase(repos.SiteRepo, repos.ImageRepo, recorder), CreateSiteUseCase: useCases.NewCreateSiteUseCase(repos.SiteRepo, repos.ImageRepo, recorder),
UpdateSiteUseCase: useCases.NewUpdateSiteUseCase(repos.SiteRepo, repos.ImageRepo, recorder), UpdateSiteUseCase: useCases.NewUpdateSiteUseCase(repos.SiteRepo, repos.ImageRepo, recorder, repos.Transactor),
GetSiteLanguagesUseCase: useCases.NewGetSiteLanguagesUseCase(repos.SiteRepo, repos.LocalizationRepo),
UpdateSiteLanguagesUseCase: useCases.NewUpdateSiteLanguagesUseCase(repos.Transactor, recorder),
GetLanguageSetupUseCase: useCases.NewGetLanguageSetupUseCase(repos.SiteRepo, repos.LocalizationRepo),
ApplyLanguageSetupUseCase: useCases.NewApplyLanguageSetupUseCase(repos.Transactor, recorder),
SetDefaultSiteUseCase: useCases.NewSetDefaultSiteUseCase(repos.SiteRepo, recorder), SetDefaultSiteUseCase: useCases.NewSetDefaultSiteUseCase(repos.SiteRepo, recorder),
DeleteSiteUseCase: useCases.NewDeleteSiteUseCase(repos.SiteRepo, recorder), DeleteSiteUseCase: useCases.NewDeleteSiteUseCase(repos.SiteRepo, recorder),
CreateContentTypeUseCase: useCases.NewCreateContentTypeUseCase(repos.ContentTypeRepo, time.Now), CreateContentTypeUseCase: useCases.NewCreateContentTypeUseCase(repos.ContentTypeRepo, repos.RoleRepo, time.Now),
ListContentTypesUseCase: useCases.NewListContentTypesUseCase(repos.ContentTypeRepo), ListContentTypesUseCase: useCases.NewListContentTypesUseCase(repos.ContentTypeRepo),
GetContentTypeUseCase: useCases.NewGetContentTypeUseCase(repos.ContentTypeRepo), GetContentTypeUseCase: useCases.NewGetContentTypeUseCase(repos.ContentTypeRepo),
UpdateContentTypeUseCase: useCases.NewUpdateContentTypeUseCase(repos.ContentTypeRepo, repos.EntryRepo, time.Now), UpdateContentTypeUseCase: useCases.NewUpdateContentTypeUseCase(repos.ContentTypeRepo, repos.EntryRepo, time.Now),
DeleteContentTypeUseCase: useCases.NewDeleteContentTypeUseCase(repos.ContentTypeRepo, repos.EntryRepo), DeleteContentTypeUseCase: useCases.NewDeleteContentTypeUseCase(repos.ContentTypeRepo, repos.EntryRepo, repos.RoleRepo),
ListRolesUseCase: useCases.NewListRolesUseCase(repos.RoleRepo, repos.UserRepo, repos.ContentTypeRepo),
GetRoleUseCase: useCases.NewGetRoleUseCase(repos.RoleRepo, repos.UserRepo, repos.ContentTypeRepo),
CreateRoleUseCase: useCases.NewCreateRoleUseCase(repos.RoleRepo, repos.UserRepo, repos.ContentTypeRepo, recorder),
UpdateRoleUseCase: useCases.NewUpdateRoleUseCase(repos.RoleRepo, repos.UserRepo, repos.ContentTypeRepo, recorder, time.Now),
DeleteRoleUseCase: useCases.NewDeleteRoleUseCase(repos.RoleRepo, repos.UserRepo, repos.ContentTypeRepo, recorder),
ReassignRoleMembersUseCase: useCases.NewReassignRoleMembersUseCase(repos.RoleRepo, repos.UserRepo, repos.ContentTypeRepo, recorder),
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, repos.RoleRepo, hasher, repos.MailRepo, settings.PublicURL, recorder),
AuthenticateUserUseCase: useCases.NewAuthenticateUserUseCase(repos.UserRepo, hasher, recorder), AuthenticateUserUseCase: useCases.NewAuthenticateUserUseCase(repos.UserRepo, hasher, recorder),
VerifyUserUseCase: useCases.NewVerifyUserUseCase(repos.UserRepo, hasher, recorder), VerifyUserUseCase: useCases.NewVerifyUserUseCase(repos.UserRepo, hasher, recorder),
CancelRegistrationUseCase: useCases.NewCancelRegistrationUseCase(repos.UserRepo), CancelRegistrationUseCase: useCases.NewCancelRegistrationUseCase(repos.UserRepo),
RequestPasswordResetUseCase: useCases.NewRequestPasswordResetUseCase(repos.UserRepo, hasher, repos.MailRepo, settings.PublicURL, recorder), RequestPasswordResetUseCase: useCases.NewRequestPasswordResetUseCase(repos.UserRepo, hasher, repos.MailRepo, settings.PublicURL, recorder),
ResetPasswordUseCase: useCases.NewResetPasswordUseCase(repos.UserRepo, hasher, repos.APIKeyRepo, time.Now, recorder), ResetPasswordUseCase: useCases.NewResetPasswordUseCase(repos.UserRepo, hasher, repos.APIKeyRepo, time.Now, recorder),
UpdateUserProfileUseCase: useCases.NewUpdateUserProfileUseCase(repos.UserRepo, recorder), UpdateUserProfileUseCase: useCases.NewUpdateUserProfileUseCase(repos.UserRepo, recorder),
RequestEmailChangeUseCase: useCases.NewRequestEmailChangeUseCase(repos.UserRepo, hasher, repos.MailRepo, mailDispatcher, settings.PublicURL, time.Now, recorder),
ResendEmailChangeUseCase: useCases.NewResendEmailChangeUseCase(repos.UserRepo, hasher, repos.MailRepo, mailDispatcher, settings.PublicURL, time.Now, recorder),
CancelEmailChangeUseCase: useCases.NewCancelEmailChangeUseCase(repos.UserRepo, recorder),
ConfirmEmailChangeUseCase: useCases.NewConfirmEmailChangeUseCase(repos.UserRepo, hasher, time.Now, recorder),
ListUsersUseCase: useCases.NewListUsersUseCase(repos.UserRepo), ListUsersUseCase: useCases.NewListUsersUseCase(repos.UserRepo),
CreateInviteUseCase: useCases.NewCreateInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher, repos.MailRepo, settings.PublicURL, recorder), CreateInviteUseCase: useCases.NewCreateInviteUseCase(repos.UserRepo, repos.InviteRepo, repos.RoleRepo, repos.ContentTypeRepo, hasher, repos.MailRepo, settings.PublicURL, recorder),
CancelInviteUseCase: useCases.NewCancelInviteUseCase(repos.InviteRepo, recorder), CancelInviteUseCase: useCases.NewCancelInviteUseCase(repos.InviteRepo, recorder),
RenewInviteUseCase: useCases.NewRenewInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher, repos.MailRepo, settings.PublicURL, recorder), RenewInviteUseCase: useCases.NewRenewInviteUseCase(repos.UserRepo, repos.InviteRepo, repos.RoleRepo, repos.ContentTypeRepo, hasher, repos.MailRepo, settings.PublicURL, recorder),
ListUsersAndInvitesUseCase: useCases.NewListUsersAndInvitesUseCase(repos.UserRepo, repos.InviteRepo), ListUsersAndInvitesUseCase: useCases.NewListUsersAndInvitesUseCase(repos.UserRepo, repos.InviteRepo, repos.RoleRepo),
ChangeUserRoleUseCase: useCases.NewChangeUserRoleUseCase(repos.UserRepo, repos.RoleRepo, repos.ContentTypeRepo, recorder),
RemoveUserUseCase: useCases.NewRemoveUserUseCase(repos.UserRepo, repos.RoleRepo, repos.ContentTypeRepo, recorder),
ExportUserDataUseCase: useCases.NewExportUserDataUseCase(repos.UserRepo, repos.RoleRepo, repos.AuthorRepo, repos.APIKeyRepo, repos.ArticleRepo, repos.EntryRepo, repos.ContentTypeRepo, repos.ImageRepo, repos.AuditRepo, time.Now, recorder, maxConcurrentDataExports),
DeleteOwnAccountUseCase: useCases.NewDeleteOwnAccountUseCase(repos.UserRepo, repos.RoleRepo, hasher, repos.UserEraser, sessionRevocation, repos.MailRepo, mailDispatcher, settings.PublicURL, recorder, repos.AuthorRepo, repos.ImageRepo, mediaUsage, imageStorage, repos.VariantFileRepo),
TransferOwnershipUseCase: useCases.NewTransferOwnershipUseCase(repos.UserRepo, repos.RoleRepo, recorder),
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, repos.RoleRepo, 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: mediaUsage,
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),
@@ -412,7 +490,7 @@ func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings
RecordRunningInfoUseCase: useCases.NewRecordRunningInfoUseCase(repos.RunningInfo, settings.Version, os.Getpid(), time.Now), RecordRunningInfoUseCase: useCases.NewRecordRunningInfoUseCase(repos.RunningInfo, settings.Version, os.Getpid(), time.Now),
CreateAPIKeyUseCase: useCases.NewCreateAPIKeyUseCase(repos.APIKeyRepo, keyGenerator, time.Now, recorder), CreateAPIKeyUseCase: useCases.NewCreateAPIKeyUseCase(repos.APIKeyRepo, keyGenerator, time.Now, recorder),
ListAPIKeysUseCase: useCases.NewListAPIKeysUseCase(repos.APIKeyRepo, repos.UserRepo, time.Now), ListAPIKeysUseCase: useCases.NewListAPIKeysUseCase(repos.APIKeyRepo, repos.UserRepo, time.Now),
RevokeAPIKeyUseCase: useCases.NewRevokeAPIKeyUseCase(repos.APIKeyRepo, repos.UserRepo, time.Now, recorder), RevokeAPIKeyUseCase: useCases.NewRevokeAPIKeyUseCase(repos.APIKeyRepo, time.Now, recorder),
AuthenticateAPIKeyUseCase: useCases.NewAuthenticateAPIKeyUseCase(repos.APIKeyRepo, keyGenerator, repos.UserRepo, time.Now), AuthenticateAPIKeyUseCase: useCases.NewAuthenticateAPIKeyUseCase(repos.APIKeyRepo, keyGenerator, repos.UserRepo, time.Now),
ListActivityUseCase: useCases.NewListActivityUseCase(repos.AuditRepo, repos.UserRepo, repos.ArticleRepo, repos.ImageRepo, repos.APIKeyRepo, time.Now, repos.SiteRepo, repos.AuthorRepo), ListActivityUseCase: useCases.NewListActivityUseCase(repos.AuditRepo, repos.UserRepo, repos.ArticleRepo, repos.ImageRepo, repos.APIKeyRepo, time.Now, repos.SiteRepo, repos.AuthorRepo),
GetActivitySummaryUseCase: useCases.NewGetActivitySummaryUseCase(repos.AuditRepo, time.Now), GetActivitySummaryUseCase: useCases.NewGetActivitySummaryUseCase(repos.AuditRepo, time.Now),
@@ -475,6 +553,9 @@ func InitContainer(settings config.Settings) (*UseCases, func() error) {
if err := backfillImageMetadata(repos.ImageRepo, imageStorage, settings); err != nil { if err := backfillImageMetadata(repos.ImageRepo, imageStorage, settings); err != nil {
panic("Failed to backfill image metadata: " + err.Error()) panic("Failed to backfill image metadata: " + err.Error())
} }
if err := useCases.NewRefreshArticleSEOUseCase(repos.ArticleRepo, repos.SiteRepo, repos.LocalizationRepo).RefreshStale(); err != nil {
panic("Failed to backfill the article SEO status: " + err.Error())
}
container := getUseCases(repos, imageStorage, settings) container := getUseCases(repos, imageStorage, settings)
return container, container.runUsageTracker(connection.Close) return container, container.runUsageTracker(connection.Close)
} }
+12 -6
View File
@@ -1,11 +1,12 @@
package activity package activity
import ( import (
"RenewCMS/api/pkg/access"
"RenewCMS/api/pkg/apperr" "RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims" "RenewCMS/api/pkg/claims"
validator "RenewCMS/api/pkg/validator" validator "RenewCMS/api/pkg/validator"
"RenewCMS/internal/domain/audit" "RenewCMS/internal/domain/audit"
"RenewCMS/internal/domain/user" "RenewCMS/internal/domain/role"
"RenewCMS/internal/infrastructure/useCases" "RenewCMS/internal/infrastructure/useCases"
"encoding/json" "encoding/json"
"errors" "errors"
@@ -134,9 +135,8 @@ func writeActivityError(w http.ResponseWriter, err error) {
case errors.Is(err, audit.ErrInvalidFilter): case errors.Is(err, audit.ErrInvalidFilter):
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest) http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
case errors.Is(err, audit.ErrActorNotAllowed): case errors.Is(err, audit.ErrActorNotAllowed):
http.Error(w, apperr.OwnerOrAdminRequiredErrorMessage, http.StatusForbidden) access.WriteMissingPermission(w, role.KeyActivityView)
case errors.Is(err, user.ErrUserNotFound): case access.WriteIfMissingPermission(w, err):
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
default: default:
http.Error(w, "Internal server error", http.StatusInternalServerError) http.Error(w, "Internal server error", http.StatusInternalServerError)
} }
@@ -156,7 +156,7 @@ func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
activityQuery := toActivityQuery(query.filterQuery) activityQuery := toActivityQuery(query.filterQuery)
activityQuery.Page, activityQuery.Size = query.Page, query.Size activityQuery.Page, activityQuery.Size = query.Page, query.Size
page, err := h.ListUseCase.ListActivity(useCases.ListActivityCommand{ViewerID: viewerId, Query: activityQuery}) page, err := h.ListUseCase.ListActivity(useCases.ListActivityCommand{ViewerID: viewerId, Grants: access.Grants(r), Query: activityQuery})
if err != nil { if err != nil {
writeActivityError(w, err) writeActivityError(w, err)
return return
@@ -220,7 +220,13 @@ func (h *Handler) Export(w http.ResponseWriter, r *http.Request) {
return return
} }
prepared, err := h.ExportUseCase.Prepare(toActivityQuery(query)) viewerId, ok := claims.UserId(r)
if !ok {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return
}
prepared, err := h.ExportUseCase.Prepare(useCases.ExportActivityCommand{ViewerID: viewerId, Grants: access.Grants(r), Query: toActivityQuery(query)})
if err != nil { if err != nil {
writeActivityError(w, err) writeActivityError(w, err)
return return
+7 -2
View File
@@ -1,6 +1,7 @@
package apikey package apikey
import ( import (
"RenewCMS/api/pkg/access"
"RenewCMS/api/pkg/apperr" "RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims" "RenewCMS/api/pkg/claims"
validator "RenewCMS/api/pkg/validator" validator "RenewCMS/api/pkg/validator"
@@ -109,8 +110,11 @@ func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
return return
} }
entries, err := h.ListUseCase.ListAPIKeys(userId) entries, err := h.ListUseCase.ListAPIKeys(userId, access.Grants(r))
if err != nil { if err != nil {
if access.WriteIfMissingPermission(w, err) {
return
}
if errors.Is(err, user.ErrUserNotFound) { if errors.Is(err, user.ErrUserNotFound) {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized) http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return return
@@ -161,8 +165,9 @@ func (h *Handler) Revoke(w http.ResponseWriter, r *http.Request) {
return return
} }
if err := h.RevokeUseCase.RevokeAPIKey(r.Context(), userId, uint32(id)); err != nil { if err := h.RevokeUseCase.RevokeAPIKey(r.Context(), userId, uint32(id), access.Grants(r)); err != nil {
switch { switch {
case access.WriteIfMissingPermission(w, err):
case errors.Is(err, domain.ErrAPIKeyNotFound): case errors.Is(err, domain.ErrAPIKeyNotFound):
http.Error(w, apperr.APIKeyNotFoundErrorMessage, http.StatusNotFound) http.Error(w, apperr.APIKeyNotFoundErrorMessage, http.StatusNotFound)
case errors.Is(err, user.ErrUserNotFound): case errors.Is(err, user.ErrUserNotFound):
+326 -143
View File
@@ -1,13 +1,13 @@
package article package article
import ( import (
"RenewCMS/api/pkg/access"
"RenewCMS/api/pkg/apperr" "RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims" "RenewCMS/api/pkg/articleerr"
validator "RenewCMS/api/pkg/validator" validator "RenewCMS/api/pkg/validator"
domain "RenewCMS/internal/domain/article" domain "RenewCMS/internal/domain/article"
"RenewCMS/internal/domain/author" "RenewCMS/internal/domain/author"
"RenewCMS/internal/domain/image" "RenewCMS/internal/domain/language"
"RenewCMS/internal/domain/site"
"RenewCMS/internal/infrastructure/useCases" "RenewCMS/internal/infrastructure/useCases"
"encoding/json" "encoding/json"
"errors" "errors"
@@ -26,27 +26,41 @@ import (
) )
type Handler struct { type Handler struct {
CreateUseCase *useCases.CreateArticleUseCase createUseCase *useCases.CreateArticleUseCase
GetUseCase *useCases.GetArticleUseCase getUseCase *useCases.GetArticleUseCase
ListUseCase *useCases.ListArticlesUseCase listUseCase *useCases.ListArticlesUseCase
DeleteUseCase *useCases.DeleteArticleUseCase deleteUseCase *useCases.DeleteArticleUseCase
UpdateUseCase *useCases.UpdateArticleUseCase updateUseCase *useCases.UpdateArticleUseCase
GetUserUseCase *useCases.GetUserUseCase translationUseCase *useCases.CreateTranslationUseCase
describeUseCase *useCases.DescribeArticleUseCase
} }
type PostArticle struct { type PostArticle struct {
Title string `json:"title" validate:"required,min=3,max=200"` Title string `json:"title" validate:"required,min=3,max=200"`
Body string `json:"body"` Body string `json:"body"`
Lang *string `json:"lang"`
StoryID *uint32 `json:"story_id" validate:"omitempty,gte=1"`
SourceArticleID *uint32 `json:"source_article_id" validate:"omitempty,gte=1"`
Copy *bool `json:"copy"`
Site *string `json:"site" validate:"omitempty,sitekey"`
} }
func NewHandler(create *useCases.CreateArticleUseCase, get *useCases.GetArticleUseCase, list *useCases.ListArticlesUseCase, delete *useCases.DeleteArticleUseCase, update *useCases.UpdateArticleUseCase, getUser *useCases.GetUserUseCase) *Handler { type PostTranslation struct {
Lang string `json:"lang" validate:"required"`
Title string `json:"title" validate:"required,min=3,max=200"`
SourceArticleID *uint32 `json:"source_article_id" validate:"omitempty,gte=1"`
Copy *bool `json:"copy" validate:"required"`
}
func NewHandler(create *useCases.CreateArticleUseCase, get *useCases.GetArticleUseCase, list *useCases.ListArticlesUseCase, delete *useCases.DeleteArticleUseCase, update *useCases.UpdateArticleUseCase, translation *useCases.CreateTranslationUseCase, describe *useCases.DescribeArticleUseCase) *Handler {
return &Handler{ return &Handler{
CreateUseCase: create, createUseCase: create,
GetUseCase: get, getUseCase: get,
ListUseCase: list, listUseCase: list,
DeleteUseCase: delete, deleteUseCase: delete,
UpdateUseCase: update, updateUseCase: update,
GetUserUseCase: getUser, translationUseCase: translation,
describeUseCase: describe,
} }
} }
@@ -57,9 +71,13 @@ type baseArticleResponse struct {
BodyFormat domain.BodyFormat `json:"body_format"` BodyFormat domain.BodyFormat `json:"body_format"`
IsOnline bool `json:"is_online"` IsOnline bool `json:"is_online"`
SiteID uint32 `json:"site_id"` SiteID uint32 `json:"site_id"`
CreatedBy *uint32 `json:"created_by,omitempty"`
Authors []author.Byline `json:"authors"` Authors []author.Byline `json:"authors"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"` UpdatedAt time.Time `json:"updated_at"`
Lang string `json:"lang"`
StoryID uint32 `json:"story_id"`
Revision uint32 `json:"revision"`
} }
type articleResponse struct { type articleResponse struct {
@@ -76,6 +94,29 @@ type articleResponse struct {
CanonicalURL string `json:"canonical_url"` CanonicalURL string `json:"canonical_url"`
Noindex bool `json:"noindex"` Noindex bool `json:"noindex"`
SEODismissed []string `json:"seo_dismissed"` SEODismissed []string `json:"seo_dismissed"`
Capabilities []string `json:"capabilities"`
Translations []domain.Translation `json:"translations"`
Source *domain.Source `json:"source"`
*editorialContext
}
type editorialContext struct {
SourceUnavailable bool `json:"source_unavailable"`
MissingLangs []string `json:"missing_langs"`
ExcludedFromPublic bool `json:"excluded_from_public"`
PartialView bool `json:"partial_view"`
}
func editorialContextFor(viewer access.Caller, described useCases.ArticleContext) *editorialContext {
if viewer.UserID == 0 {
return nil
}
return &editorialContext{
SourceUnavailable: described.SourceUnavailable,
MissingLangs: described.MissingLangs,
ExcludedFromPublic: described.ExcludedFromPublic,
PartialView: described.PartialView,
}
} }
type listItemResponse struct { type listItemResponse struct {
@@ -86,7 +127,15 @@ type listItemResponse struct {
SEOSuggestions int `json:"seo_suggestions"` SEOSuggestions int `json:"seo_suggestions"`
} }
func toBaseResponse(article domain.Article, format domain.BodyFormat) (baseArticleResponse, error) { func creatorFor(article domain.Article, viewer access.Caller) *uint32 {
if viewer.UserID == 0 {
return nil
}
createdBy := article.CreatedBy
return &createdBy
}
func toBaseResponse(article domain.Article, format domain.BodyFormat, viewer access.Caller) (baseArticleResponse, error) {
body := json.RawMessage(article.Body) body := json.RawMessage(article.Body)
if format != domain.BodyFormatJSON { if format != domain.BodyFormatJSON {
encoded, err := json.Marshal(article.Body) encoded, err := json.Marshal(article.Body)
@@ -106,14 +155,18 @@ func toBaseResponse(article domain.Article, format domain.BodyFormat) (baseArtic
BodyFormat: format, BodyFormat: format,
IsOnline: article.IsOnline, IsOnline: article.IsOnline,
SiteID: article.SiteID, SiteID: article.SiteID,
CreatedBy: creatorFor(article, viewer),
Authors: authors, Authors: authors,
CreatedAt: article.CreatedAt, CreatedAt: article.CreatedAt,
UpdatedAt: article.UpdatedAt, UpdatedAt: article.UpdatedAt,
Lang: article.Lang,
StoryID: article.StoryID,
Revision: article.EditRevision,
}, nil }, nil
} }
func toArticleResponse(article domain.Article, format domain.BodyFormat) (articleResponse, error) { func toArticleResponse(article domain.Article, format domain.BodyFormat, viewer access.Caller, described useCases.ArticleContext) (articleResponse, error) {
base, err := toBaseResponse(article, format) base, err := toBaseResponse(article, format, viewer)
if err != nil { if err != nil {
return articleResponse{}, err return articleResponse{}, err
} }
@@ -135,19 +188,23 @@ func toArticleResponse(article domain.Article, format domain.BodyFormat) (articl
CanonicalURL: article.CanonicalURL, CanonicalURL: article.CanonicalURL,
Noindex: article.Noindex, Noindex: article.Noindex,
SEODismissed: dismissed, SEODismissed: dismissed,
Capabilities: described.Capabilities,
Translations: described.Translations,
Source: described.Source,
editorialContext: editorialContextFor(viewer, described),
}, nil }, nil
} }
func toListItemResponse(article domain.Article, summary domain.SEOSummary, format domain.BodyFormat) (listItemResponse, error) { func toListItemResponse(article domain.Article, summary domain.SEOSummary, format domain.BodyFormat, viewer access.Caller) (listItemResponse, error) {
base, err := toBaseResponse(article, format) base, err := toBaseResponse(article, format, viewer)
if err != nil { if err != nil {
return listItemResponse{}, err return listItemResponse{}, err
} }
return listItemResponse{baseArticleResponse: base, Excerpt: article.Excerpt, Slug: article.Slug, SEOStatus: summary.Status, SEOSuggestions: summary.Suggestions}, nil return listItemResponse{baseArticleResponse: base, Excerpt: article.Excerpt, Slug: article.Slug, SEOStatus: summary.Status, SEOSuggestions: summary.Suggestions}, nil
} }
func encodeArticle(article domain.Article, format domain.BodyFormat) ([]byte, error) { func encodeArticle(article domain.Article, format domain.BodyFormat, viewer access.Caller, described useCases.ArticleContext) ([]byte, error) {
response, err := toArticleResponse(article, format) response, err := toArticleResponse(article, format, viewer, described)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -180,30 +237,13 @@ func (h *Handler) GetArticle(w http.ResponseWriter, r *http.Request) {
return return
} }
var article domain.Article article, err := h.getUseCase.GetArticle(id, format, access.CallerOf(r))
if h.callerIsVerified(r) {
article, err = h.GetUseCase.GetArticle(id, format)
} else {
article, err = h.GetUseCase.GetOnlineArticle(id, format)
}
if err != nil { if err != nil {
if errors.Is(err, domain.ErrArticleNotFound) { writeArticleErrorResponse(w, err)
http.Error(w, apperr.ArticleNotFoundErrorMessage, http.StatusNotFound)
return
}
http.Error(w, "Internal server error", http.StatusInternalServerError)
return return
} }
articleJson, err := encodeArticle(article, format) h.writeArticle(w, r, http.StatusOK, article, format, printToStdout)
if err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}
if _, err := w.Write(articleJson); err != nil {
fmt.Printf("Failed to write response: %v", err)
}
} }
func (h *Handler) PostArticle(w http.ResponseWriter, r *http.Request) { func (h *Handler) PostArticle(w http.ResponseWriter, r *http.Request) {
@@ -219,29 +259,98 @@ func (h *Handler) PostArticle(w http.ResponseWriter, r *http.Request) {
} }
if err := validator.Validate.Struct(localArticle); err != nil { if err := validator.Validate.Struct(localArticle); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest) writeValidationError(w, err)
return return
} }
creatorId, _ := claims.UserId(r) if localArticle.StoryID != nil {
createdArticle, err := h.CreateUseCase.CreateArticle(r.Context(), useCases.CreateArticleCommand{ if localArticle.Site != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
h.postTranslation(w, r, format, localArticle)
return
}
if localArticle.SourceArticleID != nil || localArticle.Copy != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
lang := ""
if localArticle.Lang != nil {
lang = *localArticle.Lang
}
createdArticle, err := h.createUseCase.CreateArticle(r.Context(), useCases.CreateArticleCommand{
Title: localArticle.Title, Title: localArticle.Title,
Body: localArticle.Body, Body: localArticle.Body,
Format: format, Format: format,
CreatedBy: creatorId, Lang: lang,
Site: localArticle.Site,
Caller: access.CallerOf(r),
}) })
if err != nil { if err != nil {
if errors.Is(err, domain.ErrInvalidTitle) {
http.Error(w, apperr.ArticleTitleErrorMessage, http.StatusBadRequest)
return
}
if !writeKnownArticleError(w, err) { if !writeKnownArticleError(w, err) {
http.Error(w, "Failed to create article", http.StatusInternalServerError) http.Error(w, "Failed to create article", http.StatusInternalServerError)
} }
return return
} }
writeArticleJsonResponse(w, http.StatusCreated, createdArticle, format) h.writeArticle(w, r, http.StatusCreated, createdArticle, format, log.Printf)
}
func (h *Handler) postTranslation(w http.ResponseWriter, r *http.Request, format domain.BodyFormat, request PostArticle) {
if request.Lang == nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
h.createTranslation(w, r, useCases.CreateTranslationCommand{
StoryID: *request.StoryID,
Lang: *request.Lang,
Title: request.Title,
Copy: request.Copy,
SourceArticleID: request.SourceArticleID,
Format: format,
Caller: access.CallerOf(r),
})
}
func (h *Handler) PostTranslation(w http.ResponseWriter, r *http.Request) {
id, err := parseArticleId(r)
if err != nil {
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
return
}
format, ok := parseBodyFormat(w, r)
if !ok {
return
}
var request PostTranslation
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
if err := validator.Validate.Struct(request); err != nil {
writeValidationError(w, err)
return
}
h.createTranslation(w, r, useCases.CreateTranslationCommand{
ArticleID: id,
Lang: request.Lang,
Title: request.Title,
Copy: request.Copy,
SourceArticleID: request.SourceArticleID,
Format: format,
Caller: access.CallerOf(r),
})
}
func (h *Handler) createTranslation(w http.ResponseWriter, r *http.Request, command useCases.CreateTranslationCommand) {
created, err := h.translationUseCase.CreateTranslation(r.Context(), command)
if err != nil {
writeArticleErrorResponse(w, err)
return
}
h.writeArticle(w, r, http.StatusCreated, created, command.Format, log.Printf)
} }
func writeArticleErrorResponse(w http.ResponseWriter, err error) { func writeArticleErrorResponse(w http.ResponseWriter, err error) {
@@ -251,43 +360,15 @@ func writeArticleErrorResponse(w http.ResponseWriter, err error) {
} }
func writeKnownArticleError(w http.ResponseWriter, err error) bool { func writeKnownArticleError(w http.ResponseWriter, err error) bool {
if errors.Is(err, domain.ErrArticleNotFound) { return access.WriteIfMissingPermission(w, err) || articleerr.Write(w, err)
http.Error(w, apperr.ArticleNotFoundErrorMessage, http.StatusNotFound)
return true
}
if errors.Is(err, site.ErrSiteNotFound) {
http.Error(w, apperr.SiteNotFoundErrorMessage, http.StatusNotFound)
return true
}
if errors.Is(err, author.ErrAuthorNotFound) {
http.Error(w, apperr.AuthorNotFoundErrorMessage, http.StatusNotFound)
return true
}
if errors.Is(err, domain.ErrSlugTaken) {
writeSlugTaken(w, err)
return true
}
if errors.Is(err, domain.ErrInvalidSlug) {
http.Error(w, apperr.InvalidSlugErrorMessage, http.StatusBadRequest)
return true
}
if errors.Is(err, domain.ErrInvalidCanonicalURL) {
http.Error(w, apperr.InvalidURLErrorMessage, http.StatusUnprocessableEntity)
return true
}
if errors.Is(err, image.ErrImageNotFound) {
http.Error(w, apperr.ArticleImageNotFoundErrorMessage, http.StatusBadRequest)
return true
}
return false
} }
func writeSlugTaken(w http.ResponseWriter, err error) { const siteField = "Site"
var conflict *domain.SlugTakenError
if errors.As(err, &conflict) && conflict.Suggestion != "" { var bodyMismatchFailures = map[string]string{
w.Header().Set(apperr.SlugSuggestionHeader, conflict.Suggestion) "Copy": "required",
} "IfRevision": "min",
http.Error(w, apperr.ArticleSlugTakenErrorMessage, http.StatusConflict) "AuthorIDs": "unique",
} }
func writeValidationError(w http.ResponseWriter, err error) { func writeValidationError(w http.ResponseWriter, err error) {
@@ -299,12 +380,32 @@ func writeValidationError(w http.ResponseWriter, err error) {
return return
} }
} }
for _, failure := range failures {
if failure.Field() == siteField {
http.Error(w, apperr.InvalidSiteKeyErrorMessage, http.StatusBadRequest)
return
}
}
if len(failures) > 0 && bodyMismatchFailures[failures[0].Field()] == failures[0].Tag() {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
} }
http.Error(w, err.Error(), http.StatusBadRequest) http.Error(w, err.Error(), http.StatusBadRequest)
} }
func writeArticleJsonResponse(w http.ResponseWriter, status int, article domain.Article, format domain.BodyFormat) { func printToStdout(format string, args ...any) {
articleJson, err := encodeArticle(article, format) fmt.Printf(format, args...)
}
func (h *Handler) writeArticle(w http.ResponseWriter, r *http.Request, status int, article domain.Article, format domain.BodyFormat, reportFailure func(string, ...any)) {
caller := access.CallerOf(r)
described, err := h.describeUseCase.Describe(article, caller)
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
articleJson, err := encodeArticle(article, format, caller, described)
if err != nil { if err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError) http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return return
@@ -314,7 +415,7 @@ func writeArticleJsonResponse(w http.ResponseWriter, status int, article domain.
w.WriteHeader(status) w.WriteHeader(status)
} }
if _, err := w.Write(articleJson); err != nil { if _, err := w.Write(articleJson); err != nil {
log.Printf("Failed to write response: %v", err) reportFailure("Failed to write response: %v", err)
} }
} }
@@ -330,13 +431,13 @@ func (h *Handler) setIsOnline(w http.ResponseWriter, r *http.Request, isOnline b
return return
} }
updatedArticle, err := h.UpdateUseCase.UpdateIsOnline(r.Context(), id, isOnline, format) updatedArticle, err := h.updateUseCase.UpdateIsOnline(r.Context(), id, access.CallerOf(r), isOnline, format)
if err != nil { if err != nil {
writeArticleErrorResponse(w, err) writeArticleErrorResponse(w, err)
return return
} }
writeArticleJsonResponse(w, http.StatusOK, updatedArticle, format) h.writeArticle(w, r, http.StatusOK, updatedArticle, format, log.Printf)
} }
type optionalImageID struct { type optionalImageID struct {
@@ -363,9 +464,11 @@ func (o optionalImageID) toNullable() domain.Nullable[uint32] {
} }
type UpdateArticleBody struct { type UpdateArticleBody struct {
Title *string `json:"title"`
IfRevision *uint32 `json:"if_revision" validate:"omitempty,min=1"`
Body *string `json:"body"` Body *string `json:"body"`
SiteID *uint32 `json:"site_id" validate:"omitempty,gte=1"` SiteID *uint32 `json:"site_id" validate:"omitempty,gte=1"`
AuthorIDs *[]uint32 `json:"author_ids" validate:"omitempty,dive,gte=1"` AuthorIDs *[]uint32 `json:"author_ids" validate:"omitempty,unique,dive,gte=1"`
Slug *string `json:"slug" validate:"omitempty,articleslug"` Slug *string `json:"slug" validate:"omitempty,articleslug"`
Excerpt *string `json:"excerpt" validate:"omitempty,max=300"` Excerpt *string `json:"excerpt" validate:"omitempty,max=300"`
SEOTitle *string `json:"seo_title" validate:"omitempty,max=120"` SEOTitle *string `json:"seo_title" validate:"omitempty,max=120"`
@@ -377,24 +480,13 @@ type UpdateArticleBody struct {
SocialImageID optionalImageID `json:"social_image_id"` SocialImageID optionalImageID `json:"social_image_id"`
CanonicalURL *string `json:"canonical_url" validate:"omitempty,max=2048"` CanonicalURL *string `json:"canonical_url" validate:"omitempty,max=2048"`
Noindex *bool `json:"noindex"` Noindex *bool `json:"noindex"`
SEODismissed *[]string `json:"seo_dismissed" validate:"omitempty,dive,oneof=title_long title_empty desc_short desc_long cover_alt cover_none slug_long no_au no_h body_alt short"` SEODismissed *[]string `json:"seo_dismissed" validate:"omitempty,dive,seodismissed"`
} }
var nonNullableArticleFields = []string{"body", "site_id", "author_ids", "slug", "excerpt", "seo_title", "seo_description", "cover_image_alt", "social_title", "social_description", "canonical_url", "noindex", "seo_dismissed"} var nonNullableArticleFields = []string{"title", "body", "site_id", "author_ids", "slug", "excerpt", "seo_title", "seo_description", "cover_image_alt", "social_title", "social_description", "canonical_url", "noindex", "seo_dismissed"}
var nullableArticleFields = []string{"cover_image_id", "social_image_id"} var nullableArticleFields = []string{"cover_image_id", "social_image_id"}
func hasDuplicates(ids []uint32) bool {
seen := make(map[uint32]bool, len(ids))
for _, id := range ids {
if seen[id] {
return true
}
seen[id] = true
}
return false
}
func countKnownFields(fields map[string]json.RawMessage, nonNullable []string) (int, bool) { func countKnownFields(fields map[string]json.RawMessage, nonNullable []string) (int, bool) {
known := 0 known := 0
for name, value := range fields { for name, value := range fields {
@@ -421,16 +513,13 @@ func readUpdateArticleBody(r *http.Request) (UpdateArticleBody, bool) {
return UpdateArticleBody{}, false return UpdateArticleBody{}, false
} }
known, ok := countKnownFields(fields, nonNullableArticleFields) known, ok := countKnownFields(fields, nonNullableArticleFields)
if !ok || known == 0 { if !ok || known == 0 || string(fields["if_revision"]) == "null" {
return UpdateArticleBody{}, false return UpdateArticleBody{}, false
} }
var request UpdateArticleBody var request UpdateArticleBody
if err := json.Unmarshal(raw, &request); err != nil { if err := json.Unmarshal(raw, &request); err != nil {
return UpdateArticleBody{}, false return UpdateArticleBody{}, false
} }
if request.AuthorIDs != nil && hasDuplicates(*request.AuthorIDs) {
return UpdateArticleBody{}, false
}
return request, true return request, true
} }
@@ -457,7 +546,9 @@ func (h *Handler) UpdateArticleBody(w http.ResponseWriter, r *http.Request) {
return return
} }
updatedArticle, err := h.UpdateUseCase.Update(r.Context(), id, useCases.UpdateArticleCommand{ updatedArticle, err := h.updateUseCase.Update(r.Context(), id, access.CallerOf(r), useCases.UpdateArticleCommand{
Title: request.Title,
IfRevision: request.IfRevision,
Body: request.Body, Body: request.Body,
SiteID: request.SiteID, SiteID: request.SiteID,
AuthorIDs: request.AuthorIDs, AuthorIDs: request.AuthorIDs,
@@ -480,7 +571,7 @@ func (h *Handler) UpdateArticleBody(w http.ResponseWriter, r *http.Request) {
return return
} }
writeArticleJsonResponse(w, http.StatusOK, updatedArticle, format) h.writeArticle(w, r, http.StatusOK, updatedArticle, format, log.Printf)
} }
func (h *Handler) PublishArticle(w http.ResponseWriter, r *http.Request) { func (h *Handler) PublishArticle(w http.ResponseWriter, r *http.Request) {
@@ -491,24 +582,6 @@ func (h *Handler) UnpublishArticle(w http.ResponseWriter, r *http.Request) {
h.setIsOnline(w, r, false) h.setIsOnline(w, r, false)
} }
func (h *Handler) callerIsVerified(r *http.Request) bool {
return isVerifiedCaller(r, h.GetUserUseCase)
}
func isVerifiedCaller(r *http.Request, getUser *useCases.GetUserUseCase) bool {
userId, ok := claims.UserId(r)
if !ok {
return false
}
currentUser, err := getUser.GetUser(userId)
if err != nil {
return false
}
return currentUser.IsVerified
}
const ( const (
defaultListPage = 1 defaultListPage = 1
defaultListSize = 25 defaultListSize = 25
@@ -522,6 +595,30 @@ type listQuery struct {
Site *string `validate:"omitempty,min=1"` Site *string `validate:"omitempty,min=1"`
SEO string `validate:"omitempty,oneof=ready suggestions hidden"` SEO string `validate:"omitempty,oneof=ready suggestions hidden"`
Sort string `validate:"oneof=title:asc title:desc status:asc status:desc created_at:asc created_at:desc updated_at:asc updated_at:desc"` Sort string `validate:"oneof=title:asc title:desc status:asc status:desc created_at:asc created_at:desc updated_at:asc updated_at:desc"`
Group *string `validate:"required_if=Tab missing,omitempty,eq=story"`
Tab *string `validate:"omitempty,oneof=all missing"`
Lang *string `validate:"omitempty,min=1"`
Author *uint32 `validate:"omitempty,gte=1"`
}
const groupByStory = "story"
type storyItemResponse struct {
listItemResponse
StoryUpdatedAt time.Time `json:"story_updated_at"`
StoryAuthors []author.Byline `json:"story_authors"`
Coverage []domain.Translation `json:"coverage"`
MissingLangs []string `json:"missing_langs"`
ExcludedFromPublic bool `json:"excluded_from_public"`
Capabilities []string `json:"capabilities"`
}
type storyListResponse struct {
Items []storyItemResponse `json:"items"`
Total int `json:"total"`
Page int `json:"page"`
Size int `json:"size"`
Counts domain.StoryCounts `json:"counts"`
} }
const defaultListSort = "updated_at:desc" const defaultListSort = "updated_at:desc"
@@ -575,7 +672,38 @@ func readListQuery(values url.Values) (listQuery, error) {
if values.Has("seo") && seoStatus == "" { if values.Has("seo") && seoStatus == "" {
return listQuery{}, errors.New("empty seo") return listQuery{}, errors.New("empty seo")
} }
return listQuery{Page: page, Size: size, Q: values.Get("q"), Status: status, Sort: sortValue, Site: siteKey, SEO: seoStatus}, nil query := listQuery{Page: page, Size: size, Q: values.Get("q"), Status: status, Sort: sortValue, Site: siteKey, SEO: seoStatus}
if err := readLocalizedQuery(values, &query); err != nil {
return listQuery{}, err
}
return query, nil
}
func readLocalizedQuery(values url.Values, query *listQuery) error {
if values.Has("group") {
group := values.Get("group")
query.Group = &group
}
if values.Has("tab") {
tab := values.Get("tab")
query.Tab = &tab
}
if values.Has("lang") {
tag, err := language.Normalize(values.Get("lang"))
if err != nil {
return err
}
query.Lang = &tag
}
if values.Has("author") {
id, err := strconv.ParseUint(values.Get("author"), 10, 32)
if err != nil {
return err
}
authorID := uint32(id)
query.Author = &authorID
}
return nil
} }
func (h *Handler) ListArticles(w http.ResponseWriter, r *http.Request) { func (h *Handler) ListArticles(w http.ResponseWriter, r *http.Request) {
@@ -585,14 +713,21 @@ func (h *Handler) ListArticles(w http.ResponseWriter, r *http.Request) {
} }
query, err := readListQuery(r.URL.Query()) query, err := readListQuery(r.URL.Query())
if err != nil || validator.Validate.Struct(query) != nil { if err != nil || validator.Validate.Struct(query) != nil || query.Group != nil && access.CallerOf(r).UserID == 0 {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest) http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return return
} }
page, err := h.ListUseCase.ListArticlesPage(useCases.ListArticlesCommand{ if stringOrEmpty(query.Group) == groupByStory {
h.listStories(w, r, format, query)
return
}
page, err := h.listUseCase.ListArticlesPage(useCases.ListArticlesCommand{
Format: format, Format: format,
Verified: h.callerIsVerified(r), Caller: access.CallerOf(r),
Lang: stringOrEmpty(query.Lang),
Author: query.Author,
Page: query.Page, Page: query.Page,
Size: query.Size, Size: query.Size,
Q: query.Q, Q: query.Q,
@@ -608,7 +743,7 @@ func (h *Handler) ListArticles(w http.ResponseWriter, r *http.Request) {
responses := make([]listItemResponse, 0, len(page.Items)) responses := make([]listItemResponse, 0, len(page.Items))
for _, article := range page.Items { for _, article := range page.Items {
response, err := toListItemResponse(article, page.SEO[article.ID], format) response, err := toListItemResponse(article, page.SEO[article.ID], format, access.CallerOf(r))
if err != nil { if err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError) http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return return
@@ -616,17 +751,67 @@ func (h *Handler) ListArticles(w http.ResponseWriter, r *http.Request) {
responses = append(responses, response) responses = append(responses, response)
} }
articlesJson, err := json.Marshal(listResponse{Items: responses, Total: page.Total, Page: page.Page, Size: page.Size, Counts: page.Counts}) writeListJSON(w, listResponse{Items: responses, Total: page.Total, Page: page.Page, Size: page.Size, Counts: page.Counts})
}
func writeListJSON(w http.ResponseWriter, payload any) {
body, err := json.Marshal(payload)
if err != nil { if err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError) http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return return
} }
if _, err := w.Write(body); err != nil {
if _, err := w.Write(articlesJson); err != nil {
log.Printf("Failed to write response: %v", err) log.Printf("Failed to write response: %v", err)
} }
} }
func (h *Handler) listStories(w http.ResponseWriter, r *http.Request, format domain.BodyFormat, query listQuery) {
caller := access.CallerOf(r)
page, err := h.listUseCase.ListStoriesPage(useCases.ListStoriesCommand{
Format: format,
Caller: caller,
Page: query.Page,
Size: query.Size,
Q: query.Q,
Status: query.Status,
Sort: parseSort(query.Sort),
SiteKey: query.Site,
SEO: query.SEO,
Lang: stringOrEmpty(query.Lang),
Tab: stringOrEmpty(query.Tab),
Author: query.Author,
})
if err != nil {
http.Error(w, "Failed to retrieve articles", http.StatusInternalServerError)
return
}
responses := make([]storyItemResponse, 0, len(page.Rows))
for _, row := range page.Rows {
item, err := toListItemResponse(row.Article, row.SEO, format, caller)
if err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}
responses = append(responses, storyItemResponse{
listItemResponse: item,
StoryUpdatedAt: row.UpdatedAt,
StoryAuthors: row.Authors,
Coverage: row.Coverage,
MissingLangs: row.MissingLangs,
ExcludedFromPublic: row.ExcludedFromPublic,
Capabilities: row.Capabilities,
})
}
writeListJSON(w, storyListResponse{Items: responses, Total: page.Total, Page: page.Page, Size: page.Size, Counts: page.Counts})
}
func stringOrEmpty(value *string) string {
if value == nil {
return ""
}
return *value
}
func (h *Handler) DeleteArticle(w http.ResponseWriter, r *http.Request) { func (h *Handler) DeleteArticle(w http.ResponseWriter, r *http.Request) {
id, err := parseArticleId(r) id, err := parseArticleId(r)
if err != nil { if err != nil {
@@ -634,12 +819,10 @@ func (h *Handler) DeleteArticle(w http.ResponseWriter, r *http.Request) {
return return
} }
if err := h.DeleteUseCase.DeleteArticle(r.Context(), id); err != nil { if err := h.deleteUseCase.DeleteArticle(r.Context(), id, access.CallerOf(r)); err != nil {
if errors.Is(err, domain.ErrArticleNotFound) { if !writeKnownArticleError(w, err) {
http.Error(w, apperr.ArticleNotFoundErrorMessage, http.StatusNotFound) http.Error(w, apperr.DeleteArticleFailedErrorMessage, http.StatusInternalServerError)
return
} }
http.Error(w, "Failed to delete article", http.StatusInternalServerError)
return return
} }
+138
View File
@@ -0,0 +1,138 @@
package article
import (
"RenewCMS/api/pkg/apperr"
validator "RenewCMS/api/pkg/validator"
domain "RenewCMS/internal/domain/article"
"RenewCMS/internal/domain/language"
"RenewCMS/internal/domain/site"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"errors"
"log"
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
)
type PublicHandler struct {
resolveUseCase *useCases.ResolvePublicArticleUseCase
}
func NewPublicHandler(resolve *useCases.ResolvePublicArticleUseCase) *PublicHandler {
return &PublicHandler{resolveUseCase: resolve}
}
type publicLookupResponse struct {
articleResponse
Alternates []domain.Alternate `json:"alternates"`
}
type publicStoryResponse struct {
articleResponse
Alternates []domain.Alternate `json:"alternates"`
RequestedLang string `json:"requested_lang"`
Fallback bool `json:"fallback"`
}
type publicStoryQuery struct {
Fallback *string `validate:"omitempty,eq=default"`
}
var publicErrors = []struct {
cause error
message string
status int
}{
{domain.ErrArticleNotFound, apperr.ArticleNotFoundCode, http.StatusNotFound},
{domain.ErrLanguageNotAvailable, apperr.LanguageNotAvailableCode, http.StatusNotFound},
{site.ErrSiteNotFound, apperr.SiteNotFoundCode, http.StatusNotFound},
{language.ErrInvalidLanguage, apperr.InvalidLanguageCode, http.StatusBadRequest},
}
func writePublicError(w http.ResponseWriter, err error) {
for _, known := range publicErrors {
if errors.Is(err, known.cause) {
http.Error(w, known.message, known.status)
return
}
}
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
func (h *PublicHandler) Lookup(w http.ResponseWriter, r *http.Request) {
format, ok := parseBodyFormat(w, r)
if !ok {
return
}
found, err := h.resolveUseCase.ByLangSlug(useCases.PublicLookupQuery{
SiteKey: chi.URLParam(r, "key"),
Lang: chi.URLParam(r, "lang"),
Slug: chi.URLParam(r, "slug"),
Format: format,
})
if err != nil {
writePublicError(w, err)
return
}
h.write(w, found, format, func(response articleResponse) any {
return publicLookupResponse{articleResponse: response, Alternates: found.Alternates}
})
}
func (h *PublicHandler) Story(w http.ResponseWriter, r *http.Request) {
storyID, err := strconv.ParseUint(chi.URLParam(r, "story_id"), 10, 32)
if err != nil {
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
return
}
format, ok := parseBodyFormat(w, r)
if !ok {
return
}
values := r.URL.Query()
query := publicStoryQuery{}
if values.Has("fallback") {
fallback := values.Get("fallback")
query.Fallback = &fallback
}
if validator.Validate.Struct(query) != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
command := useCases.PublicStoryQuery{
SiteKey: chi.URLParam(r, "key"),
StoryID: uint32(storyID),
FallbackDefault: query.Fallback != nil,
Format: format,
}
if values.Has("lang") {
requested := values.Get("lang")
command.Lang = &requested
}
found, err := h.resolveUseCase.ByStory(command)
if err != nil {
writePublicError(w, err)
return
}
h.write(w, found, format, func(response articleResponse) any {
return publicStoryResponse{articleResponse: response, Alternates: found.Alternates, RequestedLang: found.RequestedLang, Fallback: found.Fallback}
})
}
func (h *PublicHandler) write(w http.ResponseWriter, found useCases.PublicArticle, format domain.BodyFormat, shape func(articleResponse) any) {
response, err := toArticleResponse(found.Article, format, found.Viewer, found.Context)
if err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}
body, err := json.Marshal(shape(response))
if err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}
if _, err := w.Write(body); err != nil {
log.Printf("Failed to write response: %v", err)
}
}
+6 -6
View File
@@ -1,6 +1,7 @@
package article package article
import ( import (
"RenewCMS/api/pkg/access"
"RenewCMS/api/pkg/apperr" "RenewCMS/api/pkg/apperr"
validator "RenewCMS/api/pkg/validator" validator "RenewCMS/api/pkg/validator"
"RenewCMS/internal/infrastructure/useCases" "RenewCMS/internal/infrastructure/useCases"
@@ -14,11 +15,10 @@ import (
type SEOHandler struct { type SEOHandler struct {
ResolveUseCase *useCases.ResolveArticleSEOUseCase ResolveUseCase *useCases.ResolveArticleSEOUseCase
CheckUseCase *useCases.CheckArticleSEOUseCase CheckUseCase *useCases.CheckArticleSEOUseCase
GetUserUseCase *useCases.GetUserUseCase
} }
func NewSEOHandler(resolve *useCases.ResolveArticleSEOUseCase, check *useCases.CheckArticleSEOUseCase, getUser *useCases.GetUserUseCase) *SEOHandler { func NewSEOHandler(resolve *useCases.ResolveArticleSEOUseCase, check *useCases.CheckArticleSEOUseCase) *SEOHandler {
return &SEOHandler{ResolveUseCase: resolve, CheckUseCase: check, GetUserUseCase: getUser} return &SEOHandler{ResolveUseCase: resolve, CheckUseCase: check}
} }
type CheckArticleSEOBody struct { type CheckArticleSEOBody struct {
@@ -34,7 +34,7 @@ type CheckArticleSEOBody struct {
SocialImageID optionalImageID `json:"social_image_id"` SocialImageID optionalImageID `json:"social_image_id"`
CanonicalURL *string `json:"canonical_url" validate:"omitempty,max=2048"` CanonicalURL *string `json:"canonical_url" validate:"omitempty,max=2048"`
Noindex *bool `json:"noindex"` Noindex *bool `json:"noindex"`
SEODismissed *[]string `json:"seo_dismissed" validate:"omitempty,dive,oneof=title_long title_empty desc_short desc_long cover_alt cover_none slug_long no_au no_h body_alt short"` SEODismissed *[]string `json:"seo_dismissed" validate:"omitempty,dive,seodismissed"`
} }
var checkNonNullableFields = []string{"body", "slug", "excerpt", "seo_title", "seo_description", "cover_image_alt", "social_title", "social_description", "canonical_url", "noindex", "seo_dismissed"} var checkNonNullableFields = []string{"body", "slug", "excerpt", "seo_title", "seo_description", "cover_image_alt", "social_title", "social_description", "canonical_url", "noindex", "seo_dismissed"}
@@ -68,7 +68,7 @@ func (h *SEOHandler) Resolve(w http.ResponseWriter, r *http.Request) {
return return
} }
resolved, err := h.ResolveUseCase.Resolve(id, isVerifiedCaller(r, h.GetUserUseCase)) resolved, err := h.ResolveUseCase.Resolve(id, access.CallerOf(r))
if err != nil { if err != nil {
writeArticleErrorResponse(w, err) writeArticleErrorResponse(w, err)
return return
@@ -93,7 +93,7 @@ func (h *SEOHandler) Check(w http.ResponseWriter, r *http.Request) {
return return
} }
checked, err := h.CheckUseCase.Check(id, useCases.CheckArticleSEOCommand{ checked, err := h.CheckUseCase.Check(id, access.CallerOf(r), useCases.CheckArticleSEOCommand{
Body: request.Body, Body: request.Body,
Slug: request.Slug, Slug: request.Slug,
Excerpt: request.Excerpt, Excerpt: request.Excerpt,
+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)
} }
+151
View File
@@ -0,0 +1,151 @@
package auth
import (
"RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims"
validator "RenewCMS/api/pkg/validator"
"RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"errors"
"net/http"
)
type EmailChangeHandler struct {
RequestUseCase *useCases.RequestEmailChangeUseCase
ResendUseCase *useCases.ResendEmailChangeUseCase
CancelUseCase *useCases.CancelEmailChangeUseCase
ConfirmUseCase *useCases.ConfirmEmailChangeUseCase
}
type RequestEmailChangeCredentials struct {
NewEmail string `json:"new_email" validate:"required,max=255,inviteemail"`
CurrentPassword string `json:"current_password" validate:"required"`
}
type ConfirmEmailChangeCredentials struct {
Code string `json:"code" validate:"required"`
}
func NewEmailChangeHandler(request *useCases.RequestEmailChangeUseCase, resend *useCases.ResendEmailChangeUseCase, cancel *useCases.CancelEmailChangeUseCase, confirm *useCases.ConfirmEmailChangeUseCase) *EmailChangeHandler {
return &EmailChangeHandler{
RequestUseCase: request,
ResendUseCase: resend,
CancelUseCase: cancel,
ConfirmUseCase: confirm,
}
}
func (h *EmailChangeHandler) Request(w http.ResponseWriter, r *http.Request) {
var credentials RequestEmailChangeCredentials
if err := json.NewDecoder(r.Body).Decode(&credentials); err != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
if err := validator.Validate.Struct(credentials); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
userId, ok := claims.UserId(r)
if !ok {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return
}
pending, err := h.RequestUseCase.RequestEmailChange(r.Context(), useCases.RequestEmailChangeCommand{
UserID: userId,
NewEmail: credentials.NewEmail,
CurrentPassword: credentials.CurrentPassword,
})
if err != nil {
writeEmailChangeError(w, err)
return
}
writePendingEmail(w, pending)
}
func (h *EmailChangeHandler) Resend(w http.ResponseWriter, r *http.Request) {
userId, ok := claims.UserId(r)
if !ok {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return
}
pending, err := h.ResendUseCase.ResendEmailChange(r.Context(), userId)
if err != nil {
writeEmailChangeError(w, err)
return
}
writePendingEmail(w, pending)
}
func (h *EmailChangeHandler) Cancel(w http.ResponseWriter, r *http.Request) {
userId, ok := claims.UserId(r)
if !ok {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return
}
if err := h.CancelUseCase.CancelEmailChange(r.Context(), userId); err != nil {
writeEmailChangeError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (h *EmailChangeHandler) Confirm(w http.ResponseWriter, r *http.Request) {
var credentials ConfirmEmailChangeCredentials
if err := json.NewDecoder(r.Body).Decode(&credentials); err != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
if err := validator.Validate.Struct(credentials); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
userId, ok := claims.UserId(r)
if !ok {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return
}
email, err := h.ConfirmUseCase.ConfirmEmailChange(r.Context(), userId, credentials.Code)
if err != nil {
writeEmailChangeError(w, err)
return
}
body, err := json.Marshal(map[string]string{"email": email})
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
_, _ = w.Write(body)
}
func writePendingEmail(w http.ResponseWriter, pending string) {
body, err := json.Marshal(map[string]string{"pending_email": pending})
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
_, _ = w.Write(body)
}
func writeEmailChangeError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, user.ErrUserNotFound):
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
case errors.Is(err, user.ErrWrongPassword):
http.Error(w, apperr.WrongPasswordErrorCode, http.StatusForbidden)
case errors.Is(err, user.ErrSameEmail):
http.Error(w, apperr.SameEmailErrorCode, http.StatusBadRequest)
case errors.Is(err, user.ErrNoPendingEmailChange):
http.Error(w, apperr.NoPendingEmailChangeErrorCode, http.StatusNotFound)
case errors.Is(err, user.ErrInvalidEmailChangeCode):
http.Error(w, apperr.InvalidEmailChangeCodeErrorCode, http.StatusForbidden)
case errors.Is(err, user.ErrEmailUnavailable):
http.Error(w, apperr.EmailUnavailableErrorCode, http.StatusConflict)
default:
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}
+26 -19
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,
@@ -41,28 +40,21 @@ 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, authtoken.ExpiredCookie(isProduction))
Name: "jwt",
Value: "",
Expires: time.Now(),
MaxAge: -1,
Secure: isProduction,
HttpOnly: true,
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 +115,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
} }
@@ -134,14 +130,25 @@ func (h *LoginHandler) Register(w http.ResponseWriter, r *http.Request) {
} }
func (h *LoginHandler) RegistrationStatus(w http.ResponseWriter, _ *http.Request) { func (h *LoginHandler) RegistrationStatus(w http.ResponseWriter, _ *http.Request) {
body, _ := json.Marshal(map[string]bool{"open": h.CreateUseCase.IsRegistrationOpen()}) open, err := h.CreateUseCase.IsRegistrationOpen()
if err != nil {
http.Error(w, apperr.RegistrationFailedErrorMessage, http.StatusInternalServerError)
return
}
body, _ := json.Marshal(map[string]bool{"open": open})
w.Header().Set("Cache-Control", "no-store") w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write(body) _, _ = w.Write(body)
} }
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)
} }
+35 -2
View File
@@ -3,8 +3,10 @@ package auth
import ( import (
"RenewCMS/api/pkg/apperr" "RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims" "RenewCMS/api/pkg/claims"
"RenewCMS/api/pkg/payload"
"RenewCMS/api/pkg/publicuser" "RenewCMS/api/pkg/publicuser"
"RenewCMS/internal/domain/author" "RenewCMS/internal/domain/author"
"RenewCMS/internal/domain/role"
"RenewCMS/internal/domain/user" "RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases" "RenewCMS/internal/infrastructure/useCases"
"encoding/json" "encoding/json"
@@ -15,12 +17,14 @@ import (
type MeHandler struct { type MeHandler struct {
GetUseCase *useCases.GetUserUseCase GetUseCase *useCases.GetUserUseCase
GetAuthorUseCase *useCases.GetMyAuthorUseCase GetAuthorUseCase *useCases.GetMyAuthorUseCase
GetAccessUseCase *useCases.GetMyAccessUseCase
} }
func NewMeHandler(getUser *useCases.GetUserUseCase, getAuthor *useCases.GetMyAuthorUseCase) *MeHandler { func NewMeHandler(getUser *useCases.GetUserUseCase, getAuthor *useCases.GetMyAuthorUseCase, getAccess *useCases.GetMyAccessUseCase) *MeHandler {
return &MeHandler{ return &MeHandler{
GetUseCase: getUser, GetUseCase: getUser,
GetAuthorUseCase: getAuthor, GetAuthorUseCase: getAuthor,
GetAccessUseCase: getAccess,
} }
} }
@@ -29,9 +33,25 @@ type meAuthor struct {
ArticleCount int `json:"article_count"` ArticleCount int `json:"article_count"`
} }
type meAccess struct {
Role payload.RoleRef `json:"role"`
Permissions []role.Grant `json:"permissions"`
RoleAssignedBy *payload.RoleAssigner `json:"role_assigned_by"`
}
type meResponse struct { type meResponse struct {
publicuser.PublicUser publicuser.PublicUser
PendingEmail *string `json:"pending_email"`
Author *meAuthor `json:"author"` Author *meAuthor `json:"author"`
Access meAccess `json:"access"`
}
func toMeAccess(access useCases.Access) meAccess {
return meAccess{
Role: payload.RoleRefOf(useCases.NewRoleRef(access.Role)),
Permissions: access.Permissions,
RoleAssignedBy: payload.RoleAssignerPtrOf(access.RoleAssignedBy),
}
} }
func toMeAuthor(found *author.Author) *meAuthor { func toMeAuthor(found *author.Author) *meAuthor {
@@ -41,6 +61,13 @@ func toMeAuthor(found *author.Author) *meAuthor {
return &meAuthor{Byline: found.Byline(), ArticleCount: found.ArticleCount} return &meAuthor{Byline: found.Byline(), ArticleCount: found.ArticleCount}
} }
func pendingEmailOf(account user.User) *string {
if account.PendingEmail == "" {
return nil
}
return &account.PendingEmail
}
func (h *MeHandler) Me(w http.ResponseWriter, r *http.Request) { func (h *MeHandler) Me(w http.ResponseWriter, r *http.Request) {
userId, ok := claims.UserId(r) userId, ok := claims.UserId(r)
if !ok { if !ok {
@@ -64,7 +91,13 @@ func (h *MeHandler) Me(w http.ResponseWriter, r *http.Request) {
return return
} }
body, err := json.Marshal(meResponse{PublicUser: publicuser.New(loadedUser), Author: toMeAuthor(linked)}) access, err := h.GetAccessUseCase.Get(loadedUser)
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
body, err := json.Marshal(meResponse{PublicUser: publicuser.New(loadedUser), PendingEmail: pendingEmailOf(loadedUser), Author: toMeAuthor(linked), Access: toMeAccess(access)})
if err != nil { if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError) http.Error(w, "Internal server error", http.StatusInternalServerError)
return return
@@ -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
} }
+7 -19
View File
@@ -1,6 +1,7 @@
package author package author
import ( import (
"RenewCMS/api/pkg/access"
"RenewCMS/api/pkg/apperr" "RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims" "RenewCMS/api/pkg/claims"
validator "RenewCMS/api/pkg/validator" validator "RenewCMS/api/pkg/validator"
@@ -33,11 +34,10 @@ type Handler struct {
CreateMyUseCase *useCases.CreateMyAuthorUseCase CreateMyUseCase *useCases.CreateMyAuthorUseCase
UpdateUseCase *useCases.UpdateAuthorUseCase UpdateUseCase *useCases.UpdateAuthorUseCase
DeleteUseCase *useCases.DeleteAuthorUseCase DeleteUseCase *useCases.DeleteAuthorUseCase
GetUserUseCase *useCases.GetUserUseCase
} }
func NewHandler(list *useCases.ListAuthorsUseCase, create *useCases.CreateAuthorUseCase, createMy *useCases.CreateMyAuthorUseCase, update *useCases.UpdateAuthorUseCase, deleteUseCase *useCases.DeleteAuthorUseCase, getUser *useCases.GetUserUseCase) *Handler { func NewHandler(list *useCases.ListAuthorsUseCase, create *useCases.CreateAuthorUseCase, createMy *useCases.CreateMyAuthorUseCase, update *useCases.UpdateAuthorUseCase, deleteUseCase *useCases.DeleteAuthorUseCase) *Handler {
return &Handler{ListUseCase: list, CreateUseCase: create, CreateMyUseCase: createMy, UpdateUseCase: update, DeleteUseCase: deleteUseCase, GetUserUseCase: getUser} return &Handler{ListUseCase: list, CreateUseCase: create, CreateMyUseCase: createMy, UpdateUseCase: update, DeleteUseCase: deleteUseCase}
} }
type socialLinkRequest struct { type socialLinkRequest struct {
@@ -180,6 +180,7 @@ func writeJSON(w http.ResponseWriter, status int, payload any) {
func writeAuthorError(w http.ResponseWriter, err error) { func writeAuthorError(w http.ResponseWriter, err error) {
switch { switch {
case access.WriteIfMissingPermission(w, err):
case errors.Is(err, domain.ErrAuthorNotFound): case errors.Is(err, domain.ErrAuthorNotFound):
http.Error(w, apperr.AuthorNotFoundErrorMessage, http.StatusNotFound) http.Error(w, apperr.AuthorNotFoundErrorMessage, http.StatusNotFound)
case errors.Is(err, domain.ErrSlugTaken): case errors.Is(err, domain.ErrSlugTaken):
@@ -226,18 +227,6 @@ func writeValidationError(w http.ResponseWriter, err error) {
http.Error(w, err.Error(), http.StatusBadRequest) http.Error(w, err.Error(), http.StatusBadRequest)
} }
func (h *Handler) currentUser(r *http.Request) (user.User, bool) {
userId, ok := claims.UserId(r)
if !ok {
return user.User{}, false
}
current, err := h.GetUserUseCase.GetUser(userId)
if err != nil {
return user.User{}, false
}
return current, true
}
type listQuery struct { type listQuery struct {
Page int `validate:"gte=1"` Page int `validate:"gte=1"`
Size int `validate:"oneof=5 25 50 100"` Size int `validate:"oneof=5 25 50 100"`
@@ -277,8 +266,7 @@ func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
return return
} }
current, _ := h.currentUser(r) page, err := h.ListUseCase.List(useCases.ListAuthorsCommand{Q: query.Q, Page: query.Page, Size: query.Size, Grants: access.Grants(r)})
page, err := h.ListUseCase.List(useCases.ListAuthorsCommand{Q: query.Q, Page: query.Page, Size: query.Size, CallerRole: current.Role})
if err != nil { if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError) http.Error(w, "Internal server error", http.StatusInternalServerError)
return return
@@ -351,12 +339,12 @@ func (h *Handler) Update(w http.ResponseWriter, r *http.Request) {
return return
} }
current, ok := h.currentUser(r) callerID, ok := claims.UserId(r)
if !ok { if !ok {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized) http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return return
} }
updated, err := h.UpdateUseCase.Update(r.Context(), id, useCases.AuthorCaller{UserID: current.ID, Role: current.Role}, request.toPatch()) updated, err := h.UpdateUseCase.Update(r.Context(), id, useCases.AuthorCaller{UserID: callerID, Grants: access.Grants(r)}, request.toPatch())
if err != nil { if err != nil {
writeAuthorError(w, err) writeAuthorError(w, err)
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):
+81 -22
View File
@@ -1,8 +1,8 @@
package entry package entry
import ( import (
"RenewCMS/api/pkg/access"
"RenewCMS/api/pkg/apperr" "RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims"
"RenewCMS/api/pkg/response" "RenewCMS/api/pkg/response"
validator "RenewCMS/api/pkg/validator" validator "RenewCMS/api/pkg/validator"
"RenewCMS/internal/domain/contenttype" "RenewCMS/internal/domain/contenttype"
@@ -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),
} }
} }
@@ -106,6 +178,9 @@ func parseEntryId(r *http.Request) (uint32, error) {
} }
func writeEntryError(w http.ResponseWriter, err error) { func writeEntryError(w http.ResponseWriter, err error) {
if access.WriteIfMissingPermission(w, err) {
return
}
var fieldError domain.FieldError var fieldError domain.FieldError
switch { switch {
case errors.Is(err, contenttype.ErrContentTypeNotFound): case errors.Is(err, contenttype.ErrContentTypeNotFound):
@@ -139,21 +214,13 @@ func readBody(w http.ResponseWriter, r *http.Request) (EntryBody, bool) {
return body, true return body, true
} }
func currentUserId(w http.ResponseWriter, r *http.Request) (uint32, bool) {
userId, ok := claims.UserId(r)
if !ok {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
}
return userId, ok
}
func (h *Handler) List(w http.ResponseWriter, r *http.Request) { func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
query, err := readListQuery(r.URL.Query()) query, err := readListQuery(r.URL.Query())
if err != nil || validator.Validate.Struct(query) != nil { if err != nil || validator.Validate.Struct(query) != nil {
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"), Caller: access.CallerOf(r)})
if err != nil { if err != nil {
writeEntryError(w, err) writeEntryError(w, err)
return return
@@ -171,7 +238,7 @@ func (h *Handler) Get(w http.ResponseWriter, r *http.Request) {
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest) http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
return return
} }
found, err := h.GetUseCase.Get(chi.URLParam(r, "key"), id) found, err := h.GetUseCase.Get(chi.URLParam(r, "key"), id, access.CallerOf(r))
if err != nil { if err != nil {
writeEntryError(w, err) writeEntryError(w, err)
return return
@@ -180,15 +247,11 @@ func (h *Handler) Get(w http.ResponseWriter, r *http.Request) {
} }
func (h *Handler) Create(w http.ResponseWriter, r *http.Request) { func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
userId, ok := currentUserId(w, r)
if !ok {
return
}
body, ok := readBody(w, r) body, ok := readBody(w, r)
if !ok { if !ok {
return return
} }
created, err := h.CreateUseCase.Create(useCases.CreateEntryCommand{ContentTypeKey: chi.URLParam(r, "key"), Data: body.Data, UserID: userId}) created, err := h.CreateUseCase.Create(useCases.CreateEntryCommand{ContentTypeKey: chi.URLParam(r, "key"), Data: body.Data, Caller: access.CallerOf(r)})
if err != nil { if err != nil {
writeEntryError(w, err) writeEntryError(w, err)
return return
@@ -202,15 +265,11 @@ func (h *Handler) Update(w http.ResponseWriter, r *http.Request) {
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest) http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
return return
} }
userId, ok := currentUserId(w, r)
if !ok {
return
}
body, ok := readBody(w, r) body, ok := readBody(w, r)
if !ok { if !ok {
return return
} }
updated, err := h.UpdateUseCase.Update(useCases.UpdateEntryCommand{ContentTypeKey: chi.URLParam(r, "key"), ID: id, Data: body.Data, UserID: userId}) updated, err := h.UpdateUseCase.Update(useCases.UpdateEntryCommand{ContentTypeKey: chi.URLParam(r, "key"), ID: id, Data: body.Data, Caller: access.CallerOf(r)})
if err != nil { if err != nil {
writeEntryError(w, err) writeEntryError(w, err)
return return
@@ -224,7 +283,7 @@ func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest) http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
return return
} }
if err := h.DeleteUseCase.Delete(chi.URLParam(r, "key"), id); err != nil { if err := h.DeleteUseCase.Delete(chi.URLParam(r, "key"), id, access.CallerOf(r)); err != nil {
writeEntryError(w, err) writeEntryError(w, err)
return return
} }
+164
View File
@@ -0,0 +1,164 @@
package language
import (
"RenewCMS/api/pkg/apperr"
validator "RenewCMS/api/pkg/validator"
domainLanguage "RenewCMS/internal/domain/language"
"RenewCMS/internal/domain/localization"
"RenewCMS/internal/domain/site"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"errors"
"log"
"net/http"
"github.com/go-chi/chi/v5"
)
type SiteLanguagesHandler struct {
GetUseCase *useCases.GetSiteLanguagesUseCase
UpdateUseCase *useCases.UpdateSiteLanguagesUseCase
}
func NewSiteLanguagesHandler(get *useCases.GetSiteLanguagesUseCase, update *useCases.UpdateSiteLanguagesUseCase) *SiteLanguagesHandler {
return &SiteLanguagesHandler{GetUseCase: get, UpdateUseCase: update}
}
type PutLanguage struct {
Lang string `json:"lang"`
Enabled *bool `json:"enabled" validate:"required"`
SocialLocale *string `json:"social_locale"`
}
type PutSiteLanguages struct {
Revision *string `json:"revision" validate:"required"`
Default *string `json:"default" validate:"required"`
Languages []PutLanguage `json:"languages" validate:"required,dive"`
}
func (p PutSiteLanguages) command(key string) useCases.UpdateSiteLanguagesCommand {
entries := make([]useCases.SiteLanguageEntry, 0, len(p.Languages))
for _, entry := range p.Languages {
entries = append(entries, useCases.SiteLanguageEntry{Lang: entry.Lang, Enabled: *entry.Enabled, SocialLocale: entry.SocialLocale})
}
return useCases.UpdateSiteLanguagesCommand{Key: key, Revision: *p.Revision, Default: *p.Default, Languages: entries}
}
func (h *SiteLanguagesHandler) Get(w http.ResponseWriter, r *http.Request) {
view, err := h.GetUseCase.Get(chi.URLParam(r, "key"))
if err != nil {
writeLocalizationError(w, err)
return
}
writeJSON(w, view)
}
func (h *SiteLanguagesHandler) Update(w http.ResponseWriter, r *http.Request) {
var request PutSiteLanguages
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
if err := validator.Validate.Struct(request); err != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
view, err := h.UpdateUseCase.Update(r.Context(), request.command(chi.URLParam(r, "key")))
if err != nil {
writeLocalizationError(w, err)
return
}
writeJSON(w, view)
}
type SetupHandler struct {
GetUseCase *useCases.GetLanguageSetupUseCase
ApplyUseCase *useCases.ApplyLanguageSetupUseCase
}
func NewSetupHandler(get *useCases.GetLanguageSetupUseCase, apply *useCases.ApplyLanguageSetupUseCase) *SetupHandler {
return &SetupHandler{GetUseCase: get, ApplyUseCase: apply}
}
type PostSetupSite struct {
Key string `json:"key" validate:"required"`
Lang string `json:"lang"`
}
type PostSetup struct {
Sites []PostSetupSite `json:"sites" validate:"required,dive"`
}
func (h *SetupHandler) Get(w http.ResponseWriter, r *http.Request) {
view, err := h.GetUseCase.Get()
if err != nil {
writeLocalizationError(w, err)
return
}
writeJSON(w, view)
}
func (h *SetupHandler) Apply(w http.ResponseWriter, r *http.Request) {
var request PostSetup
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
if err := validator.Validate.Struct(request); err != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
choices := make([]localization.SetupChoice, 0, len(request.Sites))
for _, entry := range request.Sites {
choices = append(choices, localization.SetupChoice{Key: entry.Key, Lang: entry.Lang})
}
result, err := h.ApplyUseCase.Apply(r.Context(), choices)
if err != nil {
writeLocalizationError(w, err)
return
}
writeJSON(w, result)
}
func writeJSON(w http.ResponseWriter, value any) {
body, err := json.Marshal(value)
if err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}
if _, err := w.Write(body); err != nil {
log.Printf("Failed to write response: %v", err)
}
}
type localizationFailure struct {
sentinel error
status int
body string
}
var localizationFailures = []localizationFailure{
{site.ErrSiteNotFound, http.StatusNotFound, apperr.SiteNotFoundErrorMessage},
{localization.ErrSetupRequired, http.StatusConflict, apperr.SetupRequiredErrorMessage},
{localization.ErrLanguagesChanged, http.StatusConflict, apperr.LanguagesChangedErrorMessage},
{localization.ErrLanguageInUse, http.StatusConflict, apperr.LanguageInUseErrorMessage},
{localization.ErrSetupInProgress, http.StatusConflict, apperr.SetupInProgressErrorMessage},
{localization.ErrDefaultNotEnabled, http.StatusUnprocessableEntity, apperr.DefaultNotEnabledErrorMessage},
{localization.ErrNoEnabledLanguage, http.StatusUnprocessableEntity, apperr.NoEnabledLanguageErrorMessage},
{localization.ErrDuplicateLanguage, http.StatusUnprocessableEntity, apperr.DuplicateLanguageErrorMessage},
{localization.ErrInvalidSocialLocale, http.StatusUnprocessableEntity, apperr.InvalidSocialLocaleErrorMessage},
{localization.ErrSetupIncomplete, http.StatusUnprocessableEntity, apperr.SetupIncompleteErrorMessage},
{localization.ErrDuplicateSite, http.StatusUnprocessableEntity, apperr.DuplicateSiteErrorMessage},
{domainLanguage.ErrInvalidLanguage, http.StatusUnprocessableEntity, apperr.InvalidLanguageErrorMessage},
{domainLanguage.ErrUnsupportedLanguage, http.StatusUnprocessableEntity, apperr.UnsupportedLanguageErrorMessage},
}
func writeLocalizationError(w http.ResponseWriter, err error) {
for _, failure := range localizationFailures {
if errors.Is(err, failure.sentinel) {
http.Error(w, failure.body, failure.status)
return
}
}
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
+76
View File
@@ -0,0 +1,76 @@
package llms
import (
"io/fs"
"net/http"
"path"
"strings"
"github.com/go-chi/chi/v5"
)
const (
versionPlaceholder = "{{VERSION}}"
baseURLPlaceholder = "{{BASE_URL}}"
pageSuffix = ".md"
cacheControl = "public, max-age=300"
notBuiltNotice = "The LLM documentation was not generated for this build. Run `task build:llms`."
)
type Handler struct {
docs fs.FS
version string
baseURL string
}
func NewHandler(docs fs.FS, version string, publicURL string) *Handler {
return &Handler{
docs: docs,
version: version,
baseURL: strings.TrimRight(publicURL, "/"),
}
}
func (h *Handler) Register(r chi.Router) {
r.Get("/llms.txt", h.serve("llms.txt", "text/plain; charset=utf-8"))
r.Get("/llms-full.txt", h.serve("llms-full.txt", "text/plain; charset=utf-8"))
r.Get("/openapi.json", h.serve("openapi.json", "application/json"))
r.Get("/llms/{page}", h.page)
}
func (h *Handler) page(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "page")
if !strings.HasSuffix(name, pageSuffix) || strings.ContainsAny(name, "/\\") {
h.notFound(w)
return
}
h.write(w, path.Join("llms", name), "text/markdown; charset=utf-8")
}
func (h *Handler) serve(name string, contentType string) http.HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) {
h.write(w, name, contentType)
}
}
func (h *Handler) write(w http.ResponseWriter, name string, contentType string) {
if h.docs == nil {
h.notFound(w)
return
}
raw, err := fs.ReadFile(h.docs, name)
if err != nil {
h.notFound(w)
return
}
text := strings.NewReplacer(versionPlaceholder, h.version, baseURLPlaceholder, h.baseURL).Replace(string(raw))
w.Header().Set("Content-Type", contentType)
w.Header().Set("Cache-Control", cacheControl)
_, _ = w.Write([]byte(text))
}
func (h *Handler) notFound(w http.ResponseWriter) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(notBuiltNotice))
}
+22 -2
View File
@@ -92,9 +92,29 @@ 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"`
StoryID *uint32 `json:"story_id,omitempty"`
Lang *string `json:"lang,omitempty"`
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, StoryID: usage.StoryID, Lang: usage.Lang, 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 +367,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)
} }
@@ -0,0 +1,69 @@
package ownership
import (
"RenewCMS/api/pkg/access"
"RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/payload"
validator "RenewCMS/api/pkg/validator"
"RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"errors"
"net/http"
)
type Handler struct {
TransferUseCase *useCases.TransferOwnershipUseCase
}
type TransferRequest struct {
UserID uint32 `json:"user_id" validate:"required"`
ConfirmEmail string `json:"confirm_email" validate:"required"`
}
func NewHandler(transfer *useCases.TransferOwnershipUseCase) *Handler {
return &Handler{TransferUseCase: transfer}
}
func (h *Handler) Transfer(w http.ResponseWriter, r *http.Request) {
var request TransferRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
if err := validator.Validate.Struct(request); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
transferred, err := h.TransferUseCase.Transfer(r.Context(), useCases.TransferOwnershipCommand{
Caller: access.CallerOf(r),
UserID: request.UserID,
ConfirmEmail: request.ConfirmEmail,
})
if err != nil {
writeTransferError(w, err)
return
}
body, err := json.Marshal(payload.OwnershipTransferOf(transferred))
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write(body)
}
func writeTransferError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, user.ErrInvalidTransfer):
http.Error(w, apperr.InvalidTransferErrorMessage, http.StatusBadRequest)
case errors.Is(err, user.ErrConfirmationMismatch):
http.Error(w, apperr.ConfirmationMismatchErrorMessage, http.StatusBadRequest)
case errors.Is(err, user.ErrRoleChanged):
http.Error(w, apperr.UserRoleChangedErrorMessage, http.StatusConflict)
default:
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}
@@ -0,0 +1,53 @@
package permission
import (
"RenewCMS/internal/domain/role"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"net/http"
)
type Handler struct {
ListUseCase *useCases.ListPermissionsUseCase
}
func NewHandler(list *useCases.ListPermissionsUseCase) *Handler {
return &Handler{ListUseCase: list}
}
type permissionItem struct {
Key string `json:"key"`
ScopeKind role.Kind `json:"scope_kind"`
OwnerOnly bool `json:"owner_only"`
PerType bool `json:"per_type"`
}
type permissionGroup struct {
Key string `json:"key"`
Items []permissionItem `json:"items"`
}
type permissionResponse struct {
Groups []permissionGroup `json:"groups"`
}
func toResponse(groups []useCases.PermissionGroup) permissionResponse {
response := permissionResponse{Groups: make([]permissionGroup, 0, len(groups))}
for _, group := range groups {
items := make([]permissionItem, 0, len(group.Items))
for _, permission := range group.Items {
items = append(items, permissionItem{Key: permission.Key, ScopeKind: permission.Kind, OwnerOnly: permission.OwnerOnly, PerType: permission.PerType()})
}
response.Groups = append(response.Groups, permissionGroup{Key: group.Key, Items: items})
}
return response
}
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
body, err := json.Marshal(toResponse(h.ListUseCase.List()))
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
_, _ = w.Write(body)
}
+251
View File
@@ -0,0 +1,251 @@
package role
import (
"RenewCMS/api/pkg/access"
"RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/payload"
validator "RenewCMS/api/pkg/validator"
domain "RenewCMS/internal/domain/role"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"errors"
"log"
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
)
type Handler struct {
ListUseCase *useCases.ListRolesUseCase
GetUseCase *useCases.GetRoleUseCase
CreateUseCase *useCases.CreateRoleUseCase
UpdateUseCase *useCases.UpdateRoleUseCase
DeleteUseCase *useCases.DeleteRoleUseCase
ReassignUseCase *useCases.ReassignRoleMembersUseCase
}
func NewHandler(list *useCases.ListRolesUseCase, get *useCases.GetRoleUseCase, create *useCases.CreateRoleUseCase, update *useCases.UpdateRoleUseCase, deleteUseCase *useCases.DeleteRoleUseCase, reassign *useCases.ReassignRoleMembersUseCase) *Handler {
return &Handler{ListUseCase: list, GetUseCase: get, CreateUseCase: create, UpdateUseCase: update, DeleteUseCase: deleteUseCase, ReassignUseCase: reassign}
}
type GrantRequest struct {
Key string `json:"key" validate:"required,max=100"`
Scope string `json:"scope"`
}
type PostRole struct {
Name string `json:"name" validate:"required,max=100"`
Description string `json:"description" validate:"max=255"`
Grants []GrantRequest `json:"grants" validate:"dive"`
}
type PutRole struct {
Name string `json:"name" validate:"required,max=100"`
Description string `json:"description" validate:"max=255"`
Grants []GrantRequest `json:"grants" validate:"dive"`
Version uint32 `json:"version" validate:"required,min=1"`
}
type ResetRole struct {
Version uint32 `json:"version" validate:"required,min=1"`
}
type ReassignRole struct {
TargetRoleID uint32 `json:"target_role_id" validate:"required"`
}
func toGrants(requested []GrantRequest) []domain.Grant {
grants := make([]domain.Grant, 0, len(requested))
for _, grant := range requested {
grants = append(grants, domain.Grant{Key: grant.Key, Scope: domain.Scope(grant.Scope)})
}
return grants
}
func parseRoleId(r *http.Request) (uint32, error) {
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
return uint32(id), err
}
func decodeRequest(w http.ResponseWriter, r *http.Request, request any) bool {
if err := json.NewDecoder(r.Body).Decode(request); err != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return false
}
if err := validator.Validate.Struct(request); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return false
}
return true
}
func readId(w http.ResponseWriter, r *http.Request) (uint32, bool) {
id, err := parseRoleId(r)
if err != nil {
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
return 0, false
}
return id, true
}
func writeJSON(w http.ResponseWriter, status int, payload any) {
body, err := json.Marshal(payload)
if err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}
if status != http.StatusOK {
w.WriteHeader(status)
}
if _, err := w.Write(body); err != nil {
log.Printf("Failed to write response: %v", err)
}
}
type refusal struct {
cause error
status int
message string
}
var refusals = []refusal{
{domain.ErrRoleNotFound, http.StatusNotFound, apperr.RoleNotFoundErrorMessage},
{domain.ErrRoleLocked, http.StatusForbidden, apperr.RoleLockedErrorMessage},
{domain.ErrBuiltInRole, http.StatusConflict, apperr.RoleBuiltInErrorMessage},
{domain.ErrBuiltInName, http.StatusBadRequest, apperr.BuiltInNameErrorMessage},
{domain.ErrNotBuiltIn, http.StatusBadRequest, apperr.NotBuiltInErrorMessage},
{domain.ErrOwnRole, http.StatusForbidden, apperr.OwnRoleErrorMessage},
{domain.ErrRoleNameTaken, http.StatusConflict, apperr.RoleNameTakenErrorMessage},
{domain.ErrRoleConflict, http.StatusConflict, apperr.RoleConflictErrorMessage},
{domain.ErrRoleHasMembers, http.StatusConflict, apperr.RoleHasMembersErrorMessage},
{domain.ErrReassignTargetNotFound, http.StatusConflict, apperr.ReassignTargetNotFoundErrorMessage},
{domain.ErrInvalidReassign, http.StatusBadRequest, apperr.InvalidReassignErrorMessage},
{domain.ErrInvalidRoleName, http.StatusBadRequest, apperr.InvalidRoleNameErrorMessage},
{domain.ErrUnknownPermission, http.StatusBadRequest, apperr.UnknownPermissionErrorMessage},
{domain.ErrInvalidScope, http.StatusBadRequest, apperr.InvalidScopeErrorMessage},
{domain.ErrOwnerOnlyGrant, http.StatusBadRequest, apperr.OwnerOnlyPermissionErrorMessage},
{domain.ErrDuplicateGrant, http.StatusBadRequest, apperr.DuplicatePermissionErrorMessage},
{domain.ErrUnknownContentType, http.StatusBadRequest, apperr.UnknownContentTypeErrorMessage},
}
func writeRoleError(w http.ResponseWriter, err error) {
if access.WriteIfMissingPermission(w, err) {
return
}
var escalation domain.EscalationError
if errors.As(err, &escalation) {
w.Header().Set(apperr.EscalationHeader, escalation.Key)
http.Error(w, apperr.EscalationErrorMessage, http.StatusForbidden)
return
}
for _, candidate := range refusals {
if errors.Is(err, candidate.cause) {
http.Error(w, candidate.message, candidate.status)
return
}
}
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
func (h *Handler) List(w http.ResponseWriter, _ *http.Request) {
listed, err := h.ListUseCase.List()
if err != nil {
writeRoleError(w, err)
return
}
writeJSON(w, http.StatusOK, payload.RoleViewsOf(listed))
}
func (h *Handler) Get(w http.ResponseWriter, r *http.Request) {
id, ok := readId(w, r)
if !ok {
return
}
found, err := h.GetUseCase.Get(id)
if err != nil {
writeRoleError(w, err)
return
}
writeJSON(w, http.StatusOK, payload.RoleViewOf(found))
}
func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
var request PostRole
if !decodeRequest(w, r, &request) {
return
}
created, err := h.CreateUseCase.Create(r.Context(), useCases.CreateRoleCommand{
Caller: access.CallerOf(r), Name: request.Name, Description: request.Description, Grants: toGrants(request.Grants),
})
if err != nil {
writeRoleError(w, err)
return
}
writeJSON(w, http.StatusCreated, payload.RoleViewOf(created))
}
func (h *Handler) Update(w http.ResponseWriter, r *http.Request) {
id, ok := readId(w, r)
if !ok {
return
}
var request PutRole
if !decodeRequest(w, r, &request) {
return
}
updated, err := h.UpdateUseCase.Update(r.Context(), useCases.UpdateRoleCommand{
Caller: access.CallerOf(r), ID: id, Name: request.Name, Description: request.Description, Grants: toGrants(request.Grants), Version: request.Version,
})
if err != nil {
writeRoleError(w, err)
return
}
writeJSON(w, http.StatusOK, payload.RoleViewOf(updated))
}
func (h *Handler) Reset(w http.ResponseWriter, r *http.Request) {
id, ok := readId(w, r)
if !ok {
return
}
var request ResetRole
if !decodeRequest(w, r, &request) {
return
}
restored, err := h.UpdateUseCase.Reset(r.Context(), useCases.ResetRoleCommand{Caller: access.CallerOf(r), ID: id, Version: request.Version})
if err != nil {
writeRoleError(w, err)
return
}
writeJSON(w, http.StatusOK, payload.RoleViewOf(restored))
}
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
id, ok := readId(w, r)
if !ok {
return
}
if err := h.DeleteUseCase.Delete(r.Context(), useCases.DeleteRoleCommand{Caller: access.CallerOf(r), ID: id}); err != nil {
writeRoleError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (h *Handler) Reassign(w http.ResponseWriter, r *http.Request) {
id, ok := readId(w, r)
if !ok {
return
}
var request ReassignRole
if !decodeRequest(w, r, &request) {
return
}
moved, err := h.ReassignUseCase.Reassign(r.Context(), useCases.ReassignRoleMembersCommand{Caller: access.CallerOf(r), SourceID: id, TargetID: request.TargetRoleID})
if err != nil {
writeRoleError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]int{"moved": moved})
}
+14
View File
@@ -71,6 +71,7 @@ type PatchSite struct {
SiteName *string `json:"site_name" validate:"omitempty,max=100"` SiteName *string `json:"site_name" validate:"omitempty,max=100"`
TitleTemplate *string `json:"title_template" validate:"omitempty,max=200"` TitleTemplate *string `json:"title_template" validate:"omitempty,max=200"`
DefaultDescription *string `json:"default_description" validate:"omitempty,max=320"` DefaultDescription *string `json:"default_description" validate:"omitempty,max=320"`
PublicURLPattern optional[string] `json:"public_url_pattern"`
} }
func (p PatchSite) toPatch() domain.Patch { func (p PatchSite) toPatch() domain.Patch {
@@ -85,6 +86,7 @@ func (p PatchSite) toPatch() domain.Patch {
SiteName: p.SiteName, SiteName: p.SiteName,
TitleTemplate: p.TitleTemplate, TitleTemplate: p.TitleTemplate,
DefaultDescription: p.DefaultDescription, DefaultDescription: p.DefaultDescription,
PublicURLPattern: domain.Nullable[string]{Set: p.PublicURLPattern.Set, Value: p.PublicURLPattern.Value},
} }
} }
@@ -125,6 +127,18 @@ func writeSiteError(w http.ResponseWriter, err error) {
http.Error(w, apperr.InvalidTitleTemplateErrorMessage, http.StatusBadRequest) http.Error(w, apperr.InvalidTitleTemplateErrorMessage, http.StatusBadRequest)
case errors.Is(err, domain.ErrInvalidLocale): case errors.Is(err, domain.ErrInvalidLocale):
http.Error(w, apperr.InvalidLocaleErrorMessage, http.StatusBadRequest) http.Error(w, apperr.InvalidLocaleErrorMessage, http.StatusBadRequest)
case errors.Is(err, domain.ErrInvalidPublicURLPattern):
http.Error(w, apperr.InvalidPublicURLPatternErrorMessage, http.StatusUnprocessableEntity)
case errors.Is(err, domain.ErrPublicURLScheme):
http.Error(w, apperr.PublicURLSchemeErrorMessage, http.StatusUnprocessableEntity)
case errors.Is(err, domain.ErrPublicURLHost):
http.Error(w, apperr.PublicURLHostErrorMessage, http.StatusUnprocessableEntity)
case errors.Is(err, domain.ErrPublicURLPlaceholder):
http.Error(w, apperr.PublicURLPlaceholderErrorMessage, http.StatusUnprocessableEntity)
case errors.Is(err, domain.ErrPublicURLNotEncoded):
http.Error(w, apperr.PublicURLNotEncodedErrorMessage, http.StatusUnprocessableEntity)
case errors.Is(err, domain.ErrPublicURLMissingSlug):
http.Error(w, apperr.PublicURLMissingSlugErrorMessage, http.StatusUnprocessableEntity)
case errors.Is(err, image.ErrImageNotFound): case errors.Is(err, image.ErrImageNotFound):
http.Error(w, apperr.SiteImageNotFoundErrorMessage, http.StatusBadRequest) http.Error(w, apperr.SiteImageNotFoundErrorMessage, http.StatusBadRequest)
case errors.Is(err, domain.ErrUseSetDefault): case errors.Is(err, domain.ErrUseSetDefault):
+2 -1
View File
@@ -37,6 +37,7 @@ type sitemapItem struct {
URL string `json:"url"` URL string `json:"url"`
ModifiedAt string `json:"modified_at"` ModifiedAt string `json:"modified_at"`
Noindex bool `json:"noindex"` Noindex bool `json:"noindex"`
Lang string `json:"lang"`
} }
func sitemapIntParam(values url.Values, name string, fallback int) (int, error) { func sitemapIntParam(values url.Values, name string, fallback int) (int, error) {
@@ -73,7 +74,7 @@ func (h *SitemapHandler) Sitemap(w http.ResponseWriter, r *http.Request) {
items := make([]sitemapItem, 0, len(page.Entries)) items := make([]sitemapItem, 0, len(page.Entries))
for _, entry := range page.Entries { for _, entry := range page.Entries {
items = append(items, sitemapItem{URL: entry.URL, ModifiedAt: entry.ModifiedAt.UTC().Format(time.RFC3339), Noindex: entry.Noindex}) items = append(items, sitemapItem{URL: entry.URL, ModifiedAt: entry.ModifiedAt.UTC().Format(time.RFC3339), Noindex: entry.Noindex, Lang: entry.Lang})
} }
body, err := json.Marshal(items) body, err := json.Marshal(items)
if err != nil { if err != nil {
+88
View File
@@ -0,0 +1,88 @@
package story
import (
"RenewCMS/api/pkg/access"
"RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/articleerr"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"log"
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
)
type Handler struct {
MoveUseCase *useCases.MoveStoryUseCase
DeleteUseCase *useCases.DeleteStoryUseCase
}
func NewHandler(move *useCases.MoveStoryUseCase, delete *useCases.DeleteStoryUseCase) *Handler {
return &Handler{MoveUseCase: move, DeleteUseCase: delete}
}
func parseStoryID(r *http.Request) (uint32, error) {
id, err := strconv.ParseUint(chi.URLParam(r, "story_id"), 10, 32)
return uint32(id), err
}
type moveRequest struct {
Site *string `json:"site"`
}
type moveResponse struct {
StoryID uint32 `json:"story_id"`
Site string `json:"site"`
SiteID uint32 `json:"site_id"`
ArticleIDs []uint32 `json:"article_ids"`
}
func (h *Handler) Move(w http.ResponseWriter, r *http.Request) {
id, err := parseStoryID(r)
if err != nil {
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
return
}
var request moveRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil || request.Site == nil || *request.Site == "" {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
result, err := h.MoveUseCase.MoveStory(r.Context(), useCases.MoveStoryCommand{StoryID: id, SiteKey: *request.Site, Caller: access.CallerOf(r)})
if err != nil {
writeError(w, err, apperr.MoveStoryFailedErrorMessage)
return
}
body, err := json.Marshal(moveResponse{StoryID: result.StoryID, Site: result.Site.Key, SiteID: result.Site.ID, ArticleIDs: result.ArticleIDs})
if err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}
if _, err := w.Write(body); err != nil {
log.Printf("Failed to write response: %v", err)
}
}
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
id, err := parseStoryID(r)
if err != nil {
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
return
}
if err := h.DeleteUseCase.DeleteStory(r.Context(), useCases.DeleteStoryCommand{StoryID: id, Caller: access.CallerOf(r)}); err != nil {
writeError(w, err, apperr.DeleteArticleFailedErrorMessage)
return
}
w.WriteHeader(http.StatusNoContent)
}
func writeError(w http.ResponseWriter, err error, failure string) {
if access.WriteIfMissingPermission(w, err) {
return
}
if articleerr.Write(w, err) {
return
}
http.Error(w, failure, http.StatusInternalServerError)
}
+7 -30
View File
@@ -1,11 +1,12 @@
package update package update
import ( import (
"RenewCMS/api/pkg/access"
"RenewCMS/api/pkg/apperr" "RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims" "RenewCMS/api/pkg/claims"
validator "RenewCMS/api/pkg/validator" validator "RenewCMS/api/pkg/validator"
"RenewCMS/internal/domain/role"
domain "RenewCMS/internal/domain/update" domain "RenewCMS/internal/domain/update"
"RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases" "RenewCMS/internal/infrastructure/useCases"
"encoding/json" "encoding/json"
"errors" "errors"
@@ -21,29 +22,23 @@ type Handler struct {
CheckForUpdateUseCase *useCases.CheckForUpdateUseCase CheckForUpdateUseCase *useCases.CheckForUpdateUseCase
StartUpdateDownloadUseCase *useCases.StartUpdateDownloadUseCase StartUpdateDownloadUseCase *useCases.StartUpdateDownloadUseCase
RequestRestartUseCase *useCases.RequestRestartUseCase RequestRestartUseCase *useCases.RequestRestartUseCase
GetUserUseCase *useCases.GetUserUseCase
} }
type restartRequest struct { type restartRequest struct {
Kind *string `json:"kind" validate:"omitempty,oneof=update restart"` Kind *string `json:"kind" validate:"omitempty,oneof=update restart"`
} }
func NewHandler(getStatus *useCases.GetUpdateStatusUseCase, checkForUpdate *useCases.CheckForUpdateUseCase, startDownload *useCases.StartUpdateDownloadUseCase, requestRestart *useCases.RequestRestartUseCase, getUser *useCases.GetUserUseCase) *Handler { func NewHandler(getStatus *useCases.GetUpdateStatusUseCase, checkForUpdate *useCases.CheckForUpdateUseCase, startDownload *useCases.StartUpdateDownloadUseCase, requestRestart *useCases.RequestRestartUseCase) *Handler {
return &Handler{ return &Handler{
GetUpdateStatusUseCase: getStatus, GetUpdateStatusUseCase: getStatus,
CheckForUpdateUseCase: checkForUpdate, CheckForUpdateUseCase: checkForUpdate,
StartUpdateDownloadUseCase: startDownload, StartUpdateDownloadUseCase: startDownload,
RequestRestartUseCase: requestRestart, RequestRestartUseCase: requestRestart,
GetUserUseCase: getUser,
} }
} }
func (h *Handler) GetStatus(w http.ResponseWriter, r *http.Request) { func (h *Handler) GetStatus(w http.ResponseWriter, r *http.Request) {
isOwner, ok := h.isOwner(w, r) writeStatus(w, http.StatusOK, h.GetUpdateStatusUseCase.GetStatus(canApply(r)))
if !ok {
return
}
writeStatus(w, http.StatusOK, h.GetUpdateStatusUseCase.GetStatus(isOwner))
} }
func (h *Handler) Check(w http.ResponseWriter, r *http.Request) { func (h *Handler) Check(w http.ResponseWriter, r *http.Request) {
@@ -51,11 +46,7 @@ func (h *Handler) Check(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Internal server error", http.StatusInternalServerError) http.Error(w, "Internal server error", http.StatusInternalServerError)
return return
} }
isOwner, ok := h.isOwner(w, r) writeStatus(w, http.StatusOK, h.GetUpdateStatusUseCase.GetStatus(canApply(r)))
if !ok {
return
}
writeStatus(w, http.StatusOK, h.GetUpdateStatusUseCase.GetStatus(isOwner))
} }
func (h *Handler) Download(w http.ResponseWriter, r *http.Request) { func (h *Handler) Download(w http.ResponseWriter, r *http.Request) {
@@ -105,22 +96,8 @@ func decodeRestartKind(w http.ResponseWriter, r *http.Request) (string, bool) {
return *request.Kind, true return *request.Kind, true
} }
func (h *Handler) isOwner(w http.ResponseWriter, r *http.Request) (bool, bool) { func canApply(r *http.Request) bool {
userId, ok := claims.UserId(r) return access.Grants(r).Holds(role.KeySystemApplyUpdates)
if !ok {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return false, false
}
currentUser, err := h.GetUserUseCase.GetUser(userId)
if err != nil {
if errors.Is(err, user.ErrUserNotFound) {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return false, false
}
http.Error(w, "Internal server error", http.StatusInternalServerError)
return false, false
}
return currentUser.Role == user.RoleOwner, true
} }
func writeDownloadError(w http.ResponseWriter, err error) { func writeDownloadError(w http.ResponseWriter, err error) {
+81
View File
@@ -0,0 +1,81 @@
package user
import (
"RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/authtoken"
"RenewCMS/api/pkg/claims"
validator "RenewCMS/api/pkg/validator"
domain "RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"errors"
"net/http"
"time"
)
type DeleteAccountHandler struct {
DeleteUseCase *useCases.DeleteOwnAccountUseCase
IsProduction bool
}
type DeleteAccountRequest struct {
CurrentPassword string `json:"current_password" validate:"required"`
Confirmation string `json:"confirmation" validate:"required,eq=DELETE"`
}
func NewDeleteAccountHandler(deleteAccount *useCases.DeleteOwnAccountUseCase, isProduction bool) *DeleteAccountHandler {
return &DeleteAccountHandler{DeleteUseCase: deleteAccount, IsProduction: isProduction}
}
func (h *DeleteAccountHandler) Delete(w http.ResponseWriter, r *http.Request) {
var request DeleteAccountRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
if err := validator.Validate.Struct(request); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
userId, ok := claims.UserId(r)
if !ok {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return
}
command := useCases.DeleteOwnAccountCommand{UserID: userId, CurrentPassword: request.CurrentPassword}
command.SessionID, command.SessionExpiresAt = sessionOf(r)
if err := h.DeleteUseCase.Delete(r.Context(), command); err != nil {
writeDeleteAccountError(w, err)
return
}
http.SetCookie(w, authtoken.ExpiredCookie(h.IsProduction))
w.WriteHeader(http.StatusNoContent)
}
func sessionOf(r *http.Request) (string, time.Time) {
tokenClaims, err := authtoken.FromContext(r.Context())
if err != nil {
return "", time.Time{}
}
id, _ := tokenClaims["jti"].(string)
expiry, _ := tokenClaims["exp"].(float64)
return id, time.Unix(int64(expiry), 0)
}
func writeDeleteAccountError(w http.ResponseWriter, err error) {
var lastAdmin domain.LastAdminError
switch {
case errors.Is(err, domain.ErrUserNotFound):
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
case errors.Is(err, domain.ErrWrongPassword):
http.Error(w, apperr.WrongPasswordErrorCode, http.StatusForbidden)
case errors.As(err, &lastAdmin):
w.Header().Set(apperr.LastRoleHeader, lastAdmin.Role)
http.Error(w, apperr.LastAdminErrorCode, http.StatusConflict)
case errors.Is(err, domain.ErrAccountNotDeletable):
http.Error(w, apperr.AccountNotDeletableErrorCode, http.StatusConflict)
default:
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}
+44
View File
@@ -0,0 +1,44 @@
package user
import (
"RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims"
"RenewCMS/internal/infrastructure/useCases"
"context"
"errors"
"net/http"
"strconv"
)
type ExportHandler struct {
ExportUseCase *useCases.ExportUserDataUseCase
}
func NewExportHandler(export *useCases.ExportUserDataUseCase) *ExportHandler {
return &ExportHandler{ExportUseCase: export}
}
func (h *ExportHandler) Export(w http.ResponseWriter, r *http.Request) {
userId, ok := claims.UserId(r)
if !ok {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return
}
archive, err := h.ExportUseCase.Export(r.Context(), userId)
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
http.Error(w, "Service unavailable", http.StatusServiceUnavailable)
return
}
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/zip")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Content-Disposition", "attachment; filename=\""+archive.Filename+"\"")
w.Header().Set("Content-Length", strconv.Itoa(len(archive.Content)))
w.WriteHeader(http.StatusOK)
_, _ = w.Write(archive.Content)
}
+39 -17
View File
@@ -1,8 +1,10 @@
package user package user
import ( import (
"RenewCMS/api/pkg/access"
"RenewCMS/api/pkg/apperr" "RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims" "RenewCMS/api/pkg/claims"
"RenewCMS/api/pkg/payload"
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"
@@ -25,6 +27,7 @@ type InviteHandler struct {
type CreateInviteRequest struct { type CreateInviteRequest struct {
Email string `json:"email" validate:"required,inviteemail"` Email string `json:"email" validate:"required,inviteemail"`
RoleID uint32 `json:"role_id"`
} }
type inviteResponse struct { type inviteResponse struct {
@@ -32,6 +35,7 @@ type inviteResponse struct {
Kind string `json:"kind"` Kind string `json:"kind"`
Email string `json:"email"` Email string `json:"email"`
Status string `json:"status"` Status string `json:"status"`
Role payload.RoleRef `json:"role"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at"` ExpiresAt time.Time `json:"expires_at"`
} }
@@ -40,6 +44,7 @@ type inviteListItem struct {
ID uint32 `json:"id"` ID uint32 `json:"id"`
Kind string `json:"kind"` Kind string `json:"kind"`
Email string `json:"email"` Email string `json:"email"`
Role *payload.RoleRef `json:"role"`
Status string `json:"status"` Status string `json:"status"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
} }
@@ -50,7 +55,8 @@ type userListItem struct {
Username string `json:"username"` Username string `json:"username"`
DisplayName string `json:"display_name"` DisplayName string `json:"display_name"`
Email string `json:"email"` Email string `json:"email"`
Role string `json:"role"` Role *payload.RoleRef `json:"role"`
RoleAssignedBy *payload.RoleAssigner `json:"role_assigned_by"`
Status string `json:"status"` Status string `json:"status"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
} }
@@ -83,8 +89,10 @@ func (h *InviteHandler) CreateInvite(w http.ResponseWriter, r *http.Request) {
} }
created, err := h.CreateInviteUseCase.CreateInvite(r.Context(), useCases.CreateInviteCommand{ created, err := h.CreateInviteUseCase.CreateInvite(r.Context(), useCases.CreateInviteCommand{
Caller: access.CallerOf(r),
Email: request.Email, Email: request.Email,
InvitedBy: userId, InvitedBy: userId,
RoleID: request.RoleID,
}) })
if err != nil { if err != nil {
writeCreateInviteError(w, err) writeCreateInviteError(w, err)
@@ -94,12 +102,13 @@ func (h *InviteHandler) CreateInvite(w http.ResponseWriter, r *http.Request) {
writeInviteResponse(w, http.StatusCreated, created) writeInviteResponse(w, http.StatusCreated, created)
} }
func writeInviteResponse(w http.ResponseWriter, status int, entry invite.Invite) { func writeInviteResponse(w http.ResponseWriter, status int, entry useCases.InviteView) {
body, err := json.Marshal(inviteResponse{ body, err := json.Marshal(inviteResponse{
ID: entry.ID, ID: entry.ID,
Kind: useCases.EntryKindInvite, Kind: useCases.EntryKindInvite,
Email: entry.Email, Email: entry.Email,
Status: string(entry.StatusAt(time.Now())), Status: string(entry.StatusAt(time.Now())),
Role: payload.RoleRefOf(entry.Role),
CreatedAt: entry.CreatedAt, CreatedAt: entry.CreatedAt,
ExpiresAt: entry.ExpiresAt, ExpiresAt: entry.ExpiresAt,
}) })
@@ -144,7 +153,7 @@ func (h *InviteHandler) RenewInvite(w http.ResponseWriter, r *http.Request) {
return return
} }
renewed, err := h.RenewInviteUseCase.RenewInvite(r.Context(), useCases.RenewInviteCommand{ID: id, RenewedBy: userId}) renewed, err := h.RenewInviteUseCase.RenewInvite(r.Context(), useCases.RenewInviteCommand{Caller: access.CallerOf(r), ID: id, RenewedBy: userId})
if err != nil { if err != nil {
writeManageInviteError(w, err) writeManageInviteError(w, err)
return return
@@ -153,6 +162,9 @@ func (h *InviteHandler) RenewInvite(w http.ResponseWriter, r *http.Request) {
} }
func writeManageInviteError(w http.ResponseWriter, err error) { func writeManageInviteError(w http.ResponseWriter, err error) {
if writeRoleRefusal(w, err) {
return
}
switch { switch {
case errors.Is(err, invite.ErrInviteNotFound): case errors.Is(err, invite.ErrInviteNotFound):
http.Error(w, apperr.InviteNotFoundErrorMessage, http.StatusNotFound) http.Error(w, apperr.InviteNotFoundErrorMessage, http.StatusNotFound)
@@ -168,10 +180,15 @@ func writeManageInviteError(w http.ResponseWriter, err error) {
} }
func writeCreateInviteError(w http.ResponseWriter, err error) { func writeCreateInviteError(w http.ResponseWriter, err error) {
if writeRoleRefusal(w, err) {
return
}
switch { switch {
case errors.Is(err, invite.ErrEmailHasAccount): case errors.Is(err, invite.ErrEmailHasAccount):
w.Header().Set(apperr.ErrorCodeHeader, apperr.EmailHasAccountErrorCode)
http.Error(w, apperr.EmailHasAccountErrorMessage, http.StatusConflict) http.Error(w, apperr.EmailHasAccountErrorMessage, http.StatusConflict)
case errors.Is(err, invite.ErrPendingInvite): case errors.Is(err, invite.ErrPendingInvite):
w.Header().Set(apperr.ErrorCodeHeader, apperr.InvitePendingErrorCode)
http.Error(w, apperr.PendingInviteErrorMessage, http.StatusConflict) http.Error(w, apperr.PendingInviteErrorMessage, http.StatusConflict)
case errors.Is(err, invite.ErrInviteEmailNotSent): case errors.Is(err, invite.ErrInviteEmailNotSent):
http.Error(w, apperr.InviteNotSentErrorMessage, http.StatusInternalServerError) http.Error(w, apperr.InviteNotSentErrorMessage, http.StatusInternalServerError)
@@ -183,22 +200,27 @@ func writeCreateInviteError(w http.ResponseWriter, err error) {
} }
func (h *InviteHandler) ListUsers(w http.ResponseWriter, _ *http.Request) { func (h *InviteHandler) ListUsers(w http.ResponseWriter, _ *http.Request) {
entries := h.ListUsersAndInvitesUseCase.ListUsersAndInvites() entries, err := h.ListUsersAndInvitesUseCase.ListUsersAndInvites()
items := make([]any, 0, len(entries))
for _, entry := range entries {
if entry.Kind == useCases.EntryKindInvite {
items = append(items, inviteListItem{entry.ID, entry.Kind, entry.Email, entry.Status, entry.CreatedAt})
continue
}
items = append(items, userListItem{entry.ID, entry.Kind, entry.Username, entry.DisplayName, entry.Email, entry.Role, entry.Status, entry.CreatedAt})
}
body, err := json.Marshal(items)
if err != nil { if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError) http.Error(w, "Internal server error", http.StatusInternalServerError)
return return
} }
w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write(body) items := make([]any, 0, len(entries))
for _, entry := range entries {
if entry.Kind == useCases.EntryKindInvite {
items = append(items, inviteListItem{
ID: entry.ID,
Kind: entry.Kind,
Email: entry.Email,
Role: payload.RoleRefPtrOf(entry.Role),
Status: entry.Status,
CreatedAt: entry.CreatedAt,
})
continue
}
items = append(items, userListItemOf(entry))
}
writeNoStoreJSON(w, http.StatusOK, items)
} }
+62
View File
@@ -0,0 +1,62 @@
package user
import (
"RenewCMS/api/pkg/access"
"RenewCMS/api/pkg/apperr"
"RenewCMS/internal/domain/role"
domain "RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases"
"errors"
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
)
type RemoveHandler struct {
RemoveUserUseCase *useCases.RemoveUserUseCase
}
func NewRemoveHandler(removeUser *useCases.RemoveUserUseCase) *RemoveHandler {
return &RemoveHandler{RemoveUserUseCase: removeUser}
}
func (h *RemoveHandler) Remove(w http.ResponseWriter, r *http.Request) {
targetID, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
if err != nil {
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
return
}
expectedRoleID, err := strconv.ParseUint(r.URL.Query().Get("expected_role_id"), 10, 32)
if err != nil || expectedRoleID == 0 {
http.Error(w, apperr.InvalidRoleErrorMessage, http.StatusBadRequest)
return
}
err = h.RemoveUserUseCase.Remove(r.Context(), useCases.RemoveUserCommand{
Caller: access.CallerOf(r),
TargetID: uint32(targetID),
ExpectedRoleID: uint32(expectedRoleID),
})
if err != nil {
writeRemoveError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func writeRemoveError(w http.ResponseWriter, err error) {
if writeRoleRefusal(w, err) {
return
}
switch {
case errors.Is(err, role.ErrOwnRole):
http.Error(w, apperr.OwnRoleErrorMessage, http.StatusForbidden)
case errors.Is(err, domain.ErrUserNotFound):
http.Error(w, apperr.UserNotFoundErrorMessage, http.StatusNotFound)
case errors.Is(err, domain.ErrRoleChanged):
http.Error(w, apperr.UserRoleChangedErrorMessage, http.StatusConflict)
default:
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}
+73
View File
@@ -0,0 +1,73 @@
package user
import (
"RenewCMS/api/pkg/access"
"RenewCMS/api/pkg/apperr"
validator "RenewCMS/api/pkg/validator"
"RenewCMS/internal/domain/role"
domain "RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"errors"
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
)
type RoleHandler struct {
ChangeUserRoleUseCase *useCases.ChangeUserRoleUseCase
}
type ChangeRoleRequest struct {
RoleID uint32 `json:"role_id" validate:"required"`
}
func NewRoleHandler(changeRole *useCases.ChangeUserRoleUseCase) *RoleHandler {
return &RoleHandler{ChangeUserRoleUseCase: changeRole}
}
func (h *RoleHandler) Change(w http.ResponseWriter, r *http.Request) {
targetID, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
if err != nil {
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
return
}
var request ChangeRoleRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
if err := validator.Validate.Struct(request); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
changed, err := h.ChangeUserRoleUseCase.ChangeRole(r.Context(), useCases.ChangeUserRoleCommand{
Caller: access.CallerOf(r),
TargetID: uint32(targetID),
RoleID: request.RoleID,
})
if err != nil {
writeChangeRoleError(w, err)
return
}
writeNoStoreJSON(w, http.StatusOK, userListItemOf(changed))
}
func writeChangeRoleError(w http.ResponseWriter, err error) {
if writeRoleRefusal(w, err) {
return
}
switch {
case errors.Is(err, role.ErrOwnRole):
http.Error(w, apperr.OwnRoleErrorMessage, http.StatusForbidden)
case errors.Is(err, domain.ErrUserNotFound):
http.Error(w, apperr.UserNotFoundErrorMessage, http.StatusNotFound)
case errors.Is(err, domain.ErrRoleChanged):
http.Error(w, apperr.UserRoleChangedErrorMessage, http.StatusConflict)
default:
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}
+52
View File
@@ -0,0 +1,52 @@
package user
import (
"RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/payload"
"RenewCMS/internal/domain/role"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"errors"
"net/http"
)
func userListItemOf(entry useCases.DirectoryEntry) userListItem {
return userListItem{
ID: entry.ID,
Kind: entry.Kind,
Username: entry.Username,
DisplayName: entry.DisplayName,
Email: entry.Email,
Role: payload.RoleRefPtrOf(entry.Role),
RoleAssignedBy: payload.RoleAssignerPtrOf(entry.RoleAssignedBy),
Status: entry.Status,
CreatedAt: entry.CreatedAt,
}
}
func writeNoStoreJSON(w http.ResponseWriter, status int, payload any) {
body, err := json.Marshal(payload)
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(status)
_, _ = w.Write(body)
}
func writeRoleRefusal(w http.ResponseWriter, err error) bool {
var escalation role.EscalationError
switch {
case errors.As(err, &escalation):
w.Header().Set(apperr.EscalationHeader, escalation.Key)
http.Error(w, apperr.EscalationErrorMessage, http.StatusForbidden)
case errors.Is(err, role.ErrRoleLocked):
http.Error(w, apperr.RoleLockedErrorMessage, http.StatusForbidden)
case errors.Is(err, role.ErrUnknownRole):
http.Error(w, apperr.InvalidRoleErrorMessage, http.StatusBadRequest)
default:
return false
}
return true
}
+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 {
+3 -1
View File
@@ -1,6 +1,7 @@
package middleware package middleware
import ( import (
"RenewCMS/api/pkg/access"
"RenewCMS/api/pkg/claims" "RenewCMS/api/pkg/claims"
"RenewCMS/internal/domain/audit" "RenewCMS/internal/domain/audit"
"RenewCMS/internal/infrastructure/useCases" "RenewCMS/internal/infrastructure/useCases"
@@ -10,6 +11,7 @@ import (
func AuditContext(getUser *useCases.GetUserUseCase, trustedProxies []string) func(http.Handler) http.Handler { func AuditContext(getUser *useCases.GetUserUseCase, trustedProxies []string) func(http.Handler) http.Handler {
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) {
r = access.WithCurrentUser(r)
origin := audit.Origin{ origin := audit.Origin{
Actor: auditActor(getUser, r), Actor: auditActor(getUser, r),
Source: auditSource(r), Source: auditSource(r),
@@ -29,7 +31,7 @@ func auditActor(getUser *useCases.GetUserUseCase, r *http.Request) audit.Actor {
if !ok { if !ok {
return audit.AnonymousActor("") return audit.AnonymousActor("")
} }
current, err := getUser.GetUser(userId) current, err := access.LoadUser(getUser, r, userId)
if err != nil { if err != nil {
return audit.AnonymousActor("") return audit.AnonymousActor("")
} }
+4 -37
View File
@@ -1,6 +1,7 @@
package middleware package middleware
import ( import (
"RenewCMS/api/pkg/access"
"RenewCMS/api/pkg/apperr" "RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims" "RenewCMS/api/pkg/claims"
"RenewCMS/internal/domain/user" "RenewCMS/internal/domain/user"
@@ -23,7 +24,7 @@ func resolveCurrentUser(getUser *useCases.GetUserUseCase, w http.ResponseWriter,
return user.User{}, false return user.User{}, false
} }
currentUser, err := getUser.GetUser(userId) currentUser, err := access.LoadUser(getUser, r, userId)
if err != nil { if err != nil {
if errors.Is(err, user.ErrUserNotFound) { if errors.Is(err, user.ErrUserNotFound) {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized) http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
@@ -39,6 +40,7 @@ func resolveCurrentUser(getUser *useCases.GetUserUseCase, w http.ResponseWriter,
func RequireCurrentToken(getUser *useCases.GetUserUseCase) func(http.Handler) http.Handler { func RequireCurrentToken(getUser *useCases.GetUserUseCase) func(http.Handler) http.Handler {
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) {
r = access.WithCurrentUser(r)
currentUser, ok := resolveCurrentUser(getUser, w, r) currentUser, ok := resolveCurrentUser(getUser, w, r)
if !ok { if !ok {
return return
@@ -63,6 +65,7 @@ func RequireCurrentToken(getUser *useCases.GetUserUseCase) func(http.Handler) ht
func RequireVerifiedUser(getUser *useCases.GetUserUseCase) func(http.Handler) http.Handler { func RequireVerifiedUser(getUser *useCases.GetUserUseCase) func(http.Handler) http.Handler {
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) {
r = access.WithCurrentUser(r)
currentUser, ok := resolveCurrentUser(getUser, w, r) currentUser, ok := resolveCurrentUser(getUser, w, r)
if !ok { if !ok {
return return
@@ -77,39 +80,3 @@ func RequireVerifiedUser(getUser *useCases.GetUserUseCase) func(http.Handler) ht
}) })
} }
} }
func RequireOwner(getUser *useCases.GetUserUseCase) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
currentUser, ok := resolveCurrentUser(getUser, w, r)
if !ok {
return
}
if currentUser.Role != user.RoleOwner {
http.Error(w, apperr.OwnerRequiredErrorMessage, http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
}
func RequireOwnerOrAdmin(getUser *useCases.GetUserUseCase) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
currentUser, ok := resolveCurrentUser(getUser, w, r)
if !ok {
return
}
if currentUser.Role != user.RoleOwner && currentUser.Role != user.RoleAdmin {
http.Error(w, apperr.OwnerOrAdminRequiredErrorMessage, http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
}
+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
}
+53
View File
@@ -0,0 +1,53 @@
package middleware
import (
"RenewCMS/api/pkg/access"
"RenewCMS/api/pkg/claims"
"RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases"
"errors"
"net/http"
)
func OptionalAccess(getUser *useCases.GetUserUseCase, check *useCases.CheckPermissionUseCase) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r = access.WithCurrentUser(r)
account, signedIn, err := verifiedAccount(getUser, r)
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
if !signedIn {
next.ServeHTTP(w, r)
return
}
grants, err := check.Grants(account)
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
caller := access.Caller{UserID: account.ID, Grants: grants}
next.ServeHTTP(w, r.WithContext(access.WithCaller(r.Context(), caller)))
})
}
}
func verifiedAccount(getUser *useCases.GetUserUseCase, r *http.Request) (user.User, bool, error) {
userID, ok := claims.UserId(r)
if !ok {
return user.User{}, false, nil
}
account, err := access.LoadUser(getUser, r, userID)
if errors.Is(err, user.ErrUserNotFound) {
return user.User{}, false, nil
}
if err != nil {
return user.User{}, false, err
}
tokenVersion, ok := claims.TokenVersion(r)
if !ok || tokenVersion != account.TokenVersion {
return user.User{}, false, nil
}
return account, account.IsVerified, nil
}
+62
View File
@@ -0,0 +1,62 @@
package middleware
import (
"RenewCMS/api/pkg/access"
"RenewCMS/internal/domain/builtintype"
"RenewCMS/internal/domain/role"
"RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases"
"github.com/go-chi/chi/v5"
"net/http"
)
type grantCheck func(account user.User, r *http.Request) (role.GrantSet, error)
func ArticleTypeKey(*http.Request) string {
return builtintype.KeyArticle
}
func PathTypeKey(r *http.Request) string {
return chi.URLParam(r, "key")
}
func RequirePermission(getUser *useCases.GetUserUseCase, check *useCases.CheckPermissionUseCase, key string) func(http.Handler) http.Handler {
return enforce(getUser, func(account user.User, _ *http.Request) (role.GrantSet, error) {
return check.Require(account, key)
})
}
func RequireFullScope(getUser *useCases.GetUserUseCase, check *useCases.CheckPermissionUseCase, key string) func(http.Handler) http.Handler {
return enforce(getUser, func(account user.User, _ *http.Request) (role.GrantSet, error) {
return check.RequireAll(account, key)
})
}
func RequireTypedPermission(getUser *useCases.GetUserUseCase, check *useCases.CheckPermissionUseCase, key string, typeKey func(r *http.Request) string) func(http.Handler) http.Handler {
return enforce(getUser, func(account user.User, r *http.Request) (role.GrantSet, error) {
return check.RequireFor(account, key, typeKey(r))
})
}
func enforce(getUser *useCases.GetUserUseCase, verify grantCheck) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r = access.WithCurrentUser(r)
currentUser, ok := resolveCurrentUser(getUser, w, r)
if !ok {
return
}
grants, err := verify(currentUser, r)
if err != nil {
if !access.WriteIfMissingPermission(w, err) {
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
return
}
caller := access.Caller{UserID: currentUser.ID, Grants: grants}
next.ServeHTTP(w, r.WithContext(access.WithCaller(r.Context(), caller)))
})
}
}
+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'; " +
+90
View File
@@ -0,0 +1,90 @@
package middleware
import (
"RenewCMS/api/pkg/apperr"
"net/http"
"strconv"
"sync"
"time"
)
type successSlots struct {
mu sync.Mutex
window time.Duration
now func() time.Time
taken map[string]time.Time
}
func NewUserSuccessLimiter(window time.Duration) func(http.Handler) http.Handler {
return NewUserSuccessLimiterAt(window, time.Now)
}
func NewUserSuccessLimiterAt(window time.Duration, now func() time.Time) func(http.Handler) http.Handler {
slots := &successSlots{window: window, now: now, taken: make(map[string]time.Time)}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := userRateLimitKey(r)
claimed, retryAfter, granted := slots.claim(key)
if !granted {
w.Header().Set("Retry-After", strconv.Itoa(retryAfter))
http.Error(w, apperr.TooManyRequestsErrorMessage, http.StatusTooManyRequests)
return
}
recorder := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
succeeded := false
defer func() {
if !succeeded {
slots.release(key, claimed)
}
}()
next.ServeHTTP(recorder, r)
succeeded = recorder.status < http.StatusBadRequest
})
}
}
func (s *successSlots) claim(key string) (time.Time, int, bool) {
s.mu.Lock()
defer s.mu.Unlock()
now := s.now()
s.sweepExpired(now)
if claimedAt, held := s.taken[key]; held {
return time.Time{}, retryAfterSeconds(s.window - now.Sub(claimedAt)), false
}
s.taken[key] = now
return now, 0, true
}
func (s *successSlots) release(key string, claimedAt time.Time) {
s.mu.Lock()
defer s.mu.Unlock()
if current, held := s.taken[key]; held && current.Equal(claimedAt) {
delete(s.taken, key)
}
}
func (s *successSlots) sweepExpired(now time.Time) {
for key, claimedAt := range s.taken {
if now.Sub(claimedAt) >= s.window {
delete(s.taken, key)
}
}
}
type statusRecorder struct {
http.ResponseWriter
status int
}
func (s *statusRecorder) WriteHeader(status int) {
s.status = status
s.ResponseWriter.WriteHeader(status)
}
func (s *statusRecorder) Unwrap() http.ResponseWriter {
return s.ResponseWriter
}
+41
View File
@@ -0,0 +1,41 @@
package access
import (
"RenewCMS/api/pkg/apperr"
"RenewCMS/internal/domain/role"
"RenewCMS/internal/infrastructure/useCases"
"context"
"errors"
"net/http"
)
type Caller = useCases.ContentCaller
type callerContextKey struct{}
func WithCaller(ctx context.Context, caller Caller) context.Context {
return context.WithValue(ctx, callerContextKey{}, caller)
}
func CallerOf(r *http.Request) Caller {
caller, _ := r.Context().Value(callerContextKey{}).(Caller)
return caller
}
func Grants(r *http.Request) role.GrantSet {
return CallerOf(r).Grants
}
func WriteMissingPermission(w http.ResponseWriter, key string) {
w.Header().Set(apperr.MissingPermissionHeader, key)
http.Error(w, apperr.MissingPermissionErrorMessage, http.StatusForbidden)
}
func WriteIfMissingPermission(w http.ResponseWriter, err error) bool {
var missing role.MissingPermissionError
if !errors.As(err, &missing) {
return false
}
WriteMissingPermission(w, missing.Key)
return true
}
+37
View File
@@ -0,0 +1,37 @@
package access
import (
"RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases"
"context"
"net/http"
)
type currentUserContextKey struct{}
type currentUserHolder struct {
loaded bool
userID uint32
account user.User
err error
}
func WithCurrentUser(r *http.Request) *http.Request {
if _, present := r.Context().Value(currentUserContextKey{}).(*currentUserHolder); present {
return r
}
return r.WithContext(context.WithValue(r.Context(), currentUserContextKey{}, &currentUserHolder{}))
}
func LoadUser(getUser *useCases.GetUserUseCase, r *http.Request, userID uint32) (user.User, error) {
holder, present := r.Context().Value(currentUserContextKey{}).(*currentUserHolder)
if !present {
return getUser.GetUser(userID)
}
if !holder.loaded || holder.userID != userID {
holder.account, holder.err = getUser.GetUser(userID)
holder.userID = userID
holder.loaded = true
}
return holder.account, holder.err
}
+84 -2
View File
@@ -16,15 +16,19 @@ 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 ErrorCodeHeader = "X-Error-Code"
const EmailHasAccountErrorCode = "email_has_account"
const InvitePendingErrorCode = "invite_pending"
const InviteNotSentErrorMessage = "Couldn't send the invite. Try again in a moment." const InviteNotSentErrorMessage = "Couldn't send the invite. Try again in a moment."
const InviteNotFoundErrorMessage = "Invite not found" const InviteNotFoundErrorMessage = "Invite not found"
const InviteAlreadyAcceptedErrorMessage = "This invite has already been accepted." const InviteAlreadyAcceptedErrorMessage = "This invite has already been accepted."
const InviteInvalidErrorMessage = "This invite link doesn't work." 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 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."
@@ -37,8 +41,9 @@ const UpdateRestartMismatchErrorMessage = "The update state changed. Reload the
const ArticleBodyFormatErrorMessage = "The format must be one of: markdown, html, json." const ArticleBodyFormatErrorMessage = "The format must be one of: markdown, html, json."
const APIKeyNotFoundErrorMessage = "API key not found" const APIKeyNotFoundErrorMessage = "API key not found"
const APIKeyExpiryErrorMessage = "The expiry must be a date in the future." const APIKeyExpiryErrorMessage = "The expiry must be a date in the future."
const MissingPermissionErrorMessage = "missing_permission"
const MissingPermissionHeader = "X-Missing-Permission"
const SessionRequiredErrorMessage = "This action needs a real session." const SessionRequiredErrorMessage = "This action needs a real session."
const OwnerOrAdminRequiredErrorMessage = "Only owners and admins can do this."
const PurgeConflictErrorMessage = "The library changed, so nothing was purged. Check the new summary and try again." const PurgeConflictErrorMessage = "The library changed, so nothing was purged. Check the new summary and try again."
const PurgeBusyErrorMessage = "A purge is already running." const PurgeBusyErrorMessage = "A purge is already running."
const PurgeIntervalErrorMessage = "Enter a whole number of days between 1 and 365." const PurgeIntervalErrorMessage = "Enter a whole number of days between 1 and 365."
@@ -58,15 +63,36 @@ const CachePurgeTargetErrorMessage = "A variant name or an image id is required
const VariantUnknownMessage = "Unknown variant" const VariantUnknownMessage = "Unknown variant"
const VariantUnsupportedParameterMessage = "Unsupported parameter" const VariantUnsupportedParameterMessage = "Unsupported parameter"
const SiteNotFoundErrorMessage = "site_not_found" const SiteNotFoundErrorMessage = "site_not_found"
const InvalidSiteKeyErrorMessage = "invalid_site_key"
const SiteKeyTakenErrorMessage = "site_key_taken" const SiteKeyTakenErrorMessage = "site_key_taken"
const SiteHasArticlesErrorMessage = "site_has_articles" const SiteHasArticlesErrorMessage = "site_has_articles"
const DefaultSiteErrorMessage = "default_site" const DefaultSiteErrorMessage = "default_site"
const SiteKeyImmutableErrorMessage = "key_immutable" const SiteKeyImmutableErrorMessage = "key_immutable"
const InvalidSiteURLErrorMessage = "invalid_site_url" const InvalidSiteURLErrorMessage = "invalid_site_url"
const InvalidLocaleErrorMessage = "invalid_locale" const InvalidLocaleErrorMessage = "invalid_locale"
const InvalidPublicURLPatternErrorMessage = "invalid_pattern"
const PublicURLSchemeErrorMessage = "invalid_scheme"
const PublicURLHostErrorMessage = "invalid_host"
const PublicURLPlaceholderErrorMessage = "unknown_placeholder"
const PublicURLNotEncodedErrorMessage = "not_encoded"
const PublicURLMissingSlugErrorMessage = "missing_slug"
const SetupRequiredErrorMessage = "setup_required"
const LanguagesChangedErrorMessage = "languages_changed"
const LanguageInUseErrorMessage = "language_in_use"
const DefaultNotEnabledErrorMessage = "default_not_enabled"
const NoEnabledLanguageErrorMessage = "no_enabled_language"
const InvalidLanguageErrorMessage = "invalid_language"
const UnsupportedLanguageErrorMessage = "unsupported_language"
const DuplicateLanguageErrorMessage = "duplicate_language"
const InvalidSocialLocaleErrorMessage = "invalid_social_locale"
const SetupInProgressErrorMessage = "setup_in_progress"
const SetupIncompleteErrorMessage = "setup_incomplete"
const DuplicateSiteErrorMessage = "duplicate_site"
const SiteImageNotFoundErrorMessage = "image_not_found" const SiteImageNotFoundErrorMessage = "image_not_found"
const UseSetDefaultErrorMessage = "use_set_default" const UseSetDefaultErrorMessage = "use_set_default"
const InvalidReassignErrorMessage = "invalid_reassign" const InvalidReassignErrorMessage = "invalid_reassign"
const ReassignTargetNotFoundErrorMessage = "target_role_not_found"
const InvalidSocialTypeErrorMessage = "invalid_social_type" const InvalidSocialTypeErrorMessage = "invalid_social_type"
const AuthorNotFoundErrorMessage = "author_not_found" const AuthorNotFoundErrorMessage = "author_not_found"
@@ -90,6 +116,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"
@@ -97,3 +124,58 @@ const InvalidFieldErrorMessage = "invalid_field"
const SchemaIncompatibleErrorMessage = "schema_incompatible" const SchemaIncompatibleErrorMessage = "schema_incompatible"
const EntryNotFoundErrorMessage = "entry_not_found" const EntryNotFoundErrorMessage = "entry_not_found"
const InvalidEntryErrorMessage = "invalid_entry" const InvalidEntryErrorMessage = "invalid_entry"
const RoleNotFoundErrorMessage = "role_not_found"
const RoleLockedErrorMessage = "role_locked"
const RoleBuiltInErrorMessage = "role_built_in"
const BuiltInNameErrorMessage = "built_in_name"
const NotBuiltInErrorMessage = "not_built_in"
const OwnRoleErrorMessage = "own_role"
const EscalationErrorMessage = "escalation"
const EscalationHeader = "X-Escalation-Key"
const RoleNameTakenErrorMessage = "role_name_taken"
const RoleConflictErrorMessage = "role_conflict"
const RoleHasMembersErrorMessage = "role_has_members"
const InvalidRoleNameErrorMessage = "invalid_role_name"
const UnknownPermissionErrorMessage = "unknown_permission"
const InvalidScopeErrorMessage = "invalid_scope"
const OwnerOnlyPermissionErrorMessage = "owner_only_permission"
const DuplicatePermissionErrorMessage = "duplicate_permission"
const UnknownContentTypeErrorMessage = "unknown_content_type"
const InvalidRoleErrorMessage = "invalid_role"
const UserRoleChangedErrorMessage = "user_role_changed"
const InvalidTransferErrorMessage = "invalid_transfer"
const ConfirmationMismatchErrorMessage = "confirmation_mismatch"
const WrongPasswordErrorCode = "wrong_password"
const SameEmailErrorCode = "same_email"
const NoPendingEmailChangeErrorCode = "no_pending_email_change"
const InvalidEmailChangeCodeErrorCode = "invalid_email_change_code"
const EmailUnavailableErrorCode = "email_unavailable"
const LastAdminErrorCode = "last_admin"
const AccountNotDeletableErrorCode = "account_not_deletable"
const LastRoleHeader = "X-Last-Role"
const RevisionConflictErrorMessage = "revision_conflict"
const CurrentRevisionHeader = "X-Current-Revision"
const LanguageUnavailableErrorMessage = "language_unavailable"
const LanguageExistsErrorMessage = "language_exists"
const ExistingArticleHeader = "X-Existing-Article-Id"
const LanguageNotEnabledErrorMessage = "language_not_enabled"
const MissingLanguagesHeader = "X-Missing-Languages"
const LanguageDisabledErrorMessage = "language_disabled"
const SourceUnavailableErrorMessage = "source_unavailable"
const SourceOtherStoryErrorMessage = "source_other_story"
const SlugConflictErrorMessage = "slug_conflict"
const ConflictingArticlesHeader = "X-Conflicting-Articles"
const StoryMoveRequiredErrorMessage = "story_move_required"
const StoryBusyErrorMessage = "story_busy"
const TargetSiteDeletedErrorMessage = "target_site_deleted"
const MoveStoryFailedErrorMessage = "Failed to move story"
const DeleteArticleFailedErrorMessage = "Failed to delete article"
const ArticleNotFoundCode = "article_not_found"
const LanguageNotAvailableCode = "language_not_available"
const SiteNotFoundCode = "site_not_found"
const InvalidLanguageCode = "invalid_language"
+100
View File
@@ -0,0 +1,100 @@
package articleerr
import (
"RenewCMS/api/pkg/apperr"
domain "RenewCMS/internal/domain/article"
"RenewCMS/internal/domain/author"
"RenewCMS/internal/domain/image"
"RenewCMS/internal/domain/language"
"RenewCMS/internal/domain/localization"
"RenewCMS/internal/domain/site"
"RenewCMS/internal/domain/transaction"
"errors"
"net/http"
"slices"
"strconv"
"strings"
)
func Write(w http.ResponseWriter, err error) bool {
var conflict *domain.RevisionConflictError
var existing *domain.LanguageExistsError
var notEnabled *domain.LanguageNotEnabledError
var addresses *domain.SlugConflictError
var taken *domain.SlugTakenError
switch {
case errors.As(err, &conflict):
w.Header().Set(apperr.CurrentRevisionHeader, strconv.FormatUint(uint64(conflict.Current), 10))
http.Error(w, apperr.RevisionConflictErrorMessage, http.StatusConflict)
case errors.As(err, &existing):
w.Header().Set(apperr.ExistingArticleHeader, strconv.FormatUint(uint64(existing.ArticleID), 10))
http.Error(w, apperr.LanguageExistsErrorMessage, http.StatusConflict)
case errors.As(err, &notEnabled):
if len(notEnabled.Missing) > 0 {
w.Header().Set(apperr.MissingLanguagesHeader, strings.Join(notEnabled.Missing, ","))
}
http.Error(w, apperr.LanguageNotEnabledErrorMessage, http.StatusUnprocessableEntity)
case errors.As(err, &addresses):
if len(addresses.ArticleIDs) > 0 {
w.Header().Set(apperr.ConflictingArticlesHeader, joinIDs(addresses.ArticleIDs))
}
http.Error(w, apperr.SlugConflictErrorMessage, http.StatusConflict)
case errors.Is(err, domain.ErrSlugTaken):
if errors.As(err, &taken) && taken.Suggestion != "" {
w.Header().Set(apperr.SlugSuggestionHeader, taken.Suggestion)
}
http.Error(w, apperr.ArticleSlugTakenErrorMessage, http.StatusConflict)
default:
return writeSentinel(w, err)
}
return true
}
func joinIDs(ids []uint32) string {
parts := make([]string, 0, len(ids))
for _, id := range ids {
parts = append(parts, strconv.FormatUint(uint64(id), 10))
}
return strings.Join(parts, ",")
}
type sentinelResponse struct {
cause error
message string
status int
}
var articleSentinels = []sentinelResponse{
{domain.ErrInvalidTitle, apperr.ArticleTitleErrorMessage, http.StatusBadRequest},
{domain.ErrArticleNotFound, apperr.ArticleNotFoundErrorMessage, http.StatusNotFound},
{site.ErrSiteNotFound, apperr.SiteNotFoundErrorMessage, http.StatusNotFound},
{author.ErrAuthorNotFound, apperr.AuthorNotFoundErrorMessage, http.StatusNotFound},
{domain.ErrInvalidSlug, apperr.InvalidSlugErrorMessage, http.StatusBadRequest},
{domain.ErrInvalidCanonicalURL, apperr.InvalidURLErrorMessage, http.StatusUnprocessableEntity},
{image.ErrImageNotFound, apperr.ArticleImageNotFoundErrorMessage, http.StatusBadRequest},
}
var localizationSentinels = []sentinelResponse{
{domain.ErrLanguageUnavailable, apperr.LanguageUnavailableErrorMessage, http.StatusConflict},
{domain.ErrLanguageTaken, apperr.LanguageUnavailableErrorMessage, http.StatusConflict},
{domain.ErrLanguageDisabled, apperr.LanguageDisabledErrorMessage, http.StatusUnprocessableEntity},
{domain.ErrSourceUnavailable, apperr.SourceUnavailableErrorMessage, http.StatusNotFound},
{domain.ErrSourceOtherStory, apperr.SourceOtherStoryErrorMessage, http.StatusUnprocessableEntity},
{domain.ErrInvalidTranslation, apperr.BodyErrorMessage, http.StatusBadRequest},
{domain.ErrStoryMoveRequired, apperr.StoryMoveRequiredErrorMessage, http.StatusConflict},
{localization.ErrSetupRequired, apperr.SetupRequiredErrorMessage, http.StatusConflict},
{language.ErrInvalidLanguage, apperr.InvalidLanguageErrorMessage, http.StatusUnprocessableEntity},
{language.ErrUnsupportedLanguage, apperr.UnsupportedLanguageErrorMessage, http.StatusUnprocessableEntity},
{transaction.ErrLockContention, apperr.StoryBusyErrorMessage, http.StatusConflict},
{domain.ErrTargetSiteDeleted, apperr.TargetSiteDeletedErrorMessage, http.StatusConflict},
}
func writeSentinel(w http.ResponseWriter, err error) bool {
for _, candidate := range slices.Concat(articleSentinels, localizationSentinels) {
if errors.Is(err, candidate.cause) {
http.Error(w, candidate.message, candidate.status)
return true
}
}
return false
}
+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)
}
+19
View File
@@ -0,0 +1,19 @@
package authtoken
import (
"net/http"
"time"
)
func ExpiredCookie(secure bool) *http.Cookie {
return &http.Cookie{
Name: CookieName,
Value: "",
Expires: time.Now(),
MaxAge: -1,
Secure: secure,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
Path: "/",
}
}
+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
} }
+91
View File
@@ -0,0 +1,91 @@
package payload
import (
"RenewCMS/internal/domain/role"
"RenewCMS/internal/infrastructure/useCases"
"time"
)
type RoleRef struct {
ID uint32 `json:"id"`
Name string `json:"name"`
BuiltIn bool `json:"built_in"`
Locked bool `json:"locked"`
}
type RoleAssigner struct {
ID uint32 `json:"id"`
Name string `json:"name"`
}
type RoleEditor struct {
ID uint32 `json:"id"`
Name string `json:"name"`
}
type RoleView struct {
role.Role
Members int `json:"members"`
UpdatedAt *time.Time `json:"updated_at"`
UpdatedBy *RoleEditor `json:"updated_by"`
}
type OwnershipSuccessor struct {
ID uint32 `json:"id"`
Name string `json:"name"`
}
type OwnershipPredecessor struct {
ID uint32 `json:"id"`
Name string `json:"name"`
Role RoleRef `json:"role"`
}
type OwnershipTransfer struct {
Owner OwnershipSuccessor `json:"owner"`
FormerOwner OwnershipPredecessor `json:"former_owner"`
}
func RoleRefOf(ref useCases.RoleRef) RoleRef {
return RoleRef(ref)
}
func RoleRefPtrOf(ref *useCases.RoleRef) *RoleRef {
if ref == nil {
return nil
}
converted := RoleRefOf(*ref)
return &converted
}
func RoleAssignerPtrOf(assigner *useCases.RoleAssigner) *RoleAssigner {
if assigner == nil {
return nil
}
converted := RoleAssigner(*assigner)
return &converted
}
func RoleViewOf(view useCases.RoleView) RoleView {
converted := RoleView{Role: view.Role, Members: view.Members, UpdatedAt: view.UpdatedAt}
if view.UpdatedBy != nil {
editor := RoleEditor(*view.UpdatedBy)
converted.UpdatedBy = &editor
}
return converted
}
func RoleViewsOf(views []useCases.RoleView) []RoleView {
converted := make([]RoleView, 0, len(views))
for _, view := range views {
converted = append(converted, RoleViewOf(view))
}
return converted
}
func OwnershipTransferOf(transfer useCases.OwnershipTransfer) OwnershipTransfer {
return OwnershipTransfer{
Owner: OwnershipSuccessor(transfer.Owner),
FormerOwner: OwnershipPredecessor{ID: transfer.FormerOwner.ID, Name: transfer.FormerOwner.Name, Role: RoleRefOf(transfer.FormerOwner.Role)},
}
}
-2
View File
@@ -13,7 +13,6 @@ type PublicUser 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"`
DisplayName string `json:"display_name"` DisplayName string `json:"display_name"`
Role user.Role `json:"role"`
} }
func New(u user.User) PublicUser { func New(u user.User) PublicUser {
@@ -25,6 +24,5 @@ func New(u user.User) PublicUser {
CreatedAt: u.CreatedAt, CreatedAt: u.CreatedAt,
UpdatedAt: u.UpdatedAt, UpdatedAt: u.UpdatedAt,
DisplayName: u.DisplayName, DisplayName: u.DisplayName,
Role: u.Role,
} }
} }
+7
View File
@@ -7,6 +7,7 @@ import (
"RenewCMS/internal/domain/site" "RenewCMS/internal/domain/site"
"reflect" "reflect"
"regexp" "regexp"
"slices"
"github.com/go-playground/validator/v10" "github.com/go-playground/validator/v10"
) )
@@ -19,6 +20,7 @@ const AuthorNameTag = "authorname"
const AuthorSlugTag = "authorslug" const AuthorSlugTag = "authorslug"
const SocialTypeTag = "socialtype" const SocialTypeTag = "socialtype"
const ArticleSlugTag = "articleslug" const ArticleSlugTag = "articleslug"
const SEODismissedTag = "seodismissed"
var inviteEmailPattern = regexp.MustCompile(`^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$`) var inviteEmailPattern = regexp.MustCompile(`^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$`)
@@ -34,6 +36,7 @@ func InitValidator() {
_ = Validate.RegisterValidation(AuthorSlugTag, isAuthorSlug, true) _ = Validate.RegisterValidation(AuthorSlugTag, isAuthorSlug, true)
_ = Validate.RegisterValidation(SocialTypeTag, isSocialType, true) _ = Validate.RegisterValidation(SocialTypeTag, isSocialType, true)
_ = Validate.RegisterValidation(ArticleSlugTag, isArticleSlug, true) _ = Validate.RegisterValidation(ArticleSlugTag, isArticleSlug, true)
_ = Validate.RegisterValidation(SEODismissedTag, isSEODismissed)
} }
func isArticleSlug(field validator.FieldLevel) bool { func isArticleSlug(field validator.FieldLevel) bool {
@@ -44,6 +47,10 @@ func isArticleSlug(field validator.FieldLevel) bool {
return value == "" || article.IsValidSlug(value) return value == "" || article.IsValidSlug(value)
} }
func isSEODismissed(field validator.FieldLevel) bool {
return slices.Contains(article.DismissCodes(), field.Field().String())
}
func isAbsent(field validator.FieldLevel) bool { func isAbsent(field validator.FieldLevel) bool {
return field.Field().Kind() == reflect.Ptr && field.Field().IsNil() return field.Field().Kind() == reflect.Ptr && field.Field().IsNil()
} }
+339 -130
View File
@@ -11,28 +11,38 @@ import (
"RenewCMS/api/handlers/entry" "RenewCMS/api/handlers/entry"
"RenewCMS/api/handlers/frontend" "RenewCMS/api/handlers/frontend"
"RenewCMS/api/handlers/imagevariant" "RenewCMS/api/handlers/imagevariant"
languagehandler "RenewCMS/api/handlers/language"
"RenewCMS/api/handlers/llms"
"RenewCMS/api/handlers/media" "RenewCMS/api/handlers/media"
"RenewCMS/api/handlers/ownership"
"RenewCMS/api/handlers/permission"
rolehandler "RenewCMS/api/handlers/role"
"RenewCMS/api/handlers/settings" "RenewCMS/api/handlers/settings"
"RenewCMS/api/handlers/site" "RenewCMS/api/handlers/site"
"RenewCMS/api/handlers/staticimages" "RenewCMS/api/handlers/staticimages"
"RenewCMS/api/handlers/story"
"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/domain/role"
"RenewCMS/internal/infrastructure/config" "RenewCMS/internal/infrastructure/config"
"RenewCMS/internal/infrastructure/llmdocs"
"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),
}))
} }
} }
@@ -44,6 +54,17 @@ func GetHelloWorld(w http.ResponseWriter, _ *http.Request) {
const ( const (
apiKeyMaxRequests = 120 apiKeyMaxRequests = 120
apiKeyWindow = time.Minute apiKeyWindow = time.Minute
publicReadMaxRequests = apiKeyMaxRequests
publicReadWindow = apiKeyWindow
emailChangeMaxRequests = 5
emailChangeWindow = 15 * time.Minute
dataExportWindow = 15 * time.Minute
accountDeleteMaxRequests = 5
accountDeleteWindow = 15 * time.Minute
) )
func (c *UseCases) apiKeyAuth() func(http.Handler) http.Handler { func (c *UseCases) apiKeyAuth() func(http.Handler) http.Handler {
@@ -53,43 +74,105 @@ func (c *UseCases) apiKeyAuth() func(http.Handler) http.Handler {
return c.apiKeyAuthMiddleware return c.apiKeyAuthMiddleware
} }
func (c *UseCases) publicReadLimit(trustedProxies []string) func(http.Handler) http.Handler {
c.publicReadLimitOnce.Do(func() {
realIP := middleware.TrustedProxyRealIP(trustedProxies)
limiter := middleware.NewRateLimiter(publicReadMaxRequests, publicReadWindow)
c.publicReadLimitMiddleware = func(next http.Handler) http.Handler {
return realIP(limiter(next))
}
})
return c.publicReadLimitMiddleware
}
func (c *UseCases) require(key string) func(http.Handler) http.Handler {
return middleware.RequirePermission(c.GetUserUseCase, c.CheckPermissionUseCase, key)
}
func (c *UseCases) requireTyped(key string, typeKey func(*http.Request) string) func(http.Handler) http.Handler {
return middleware.RequireTypedPermission(c.GetUserUseCase, c.CheckPermissionUseCase, key, typeKey)
}
func (c *UseCases) requireArticle(key string) func(http.Handler) http.Handler {
return c.requireTyped(key, middleware.ArticleTypeKey)
}
func (c *UseCases) requireEntry(key string) func(http.Handler) http.Handler {
return c.requireTyped(key, middleware.PathTypeKey)
}
func (c *UseCases) requireAll(key string) func(http.Handler) http.Handler {
return middleware.RequireFullScope(c.GetUserUseCase, c.CheckPermissionUseCase, key)
}
func NewArticleRouter(container *UseCases, trustedProxies []string) http.Handler { func NewArticleRouter(container *UseCases, trustedProxies []string) http.Handler {
r := chi.NewRouter() r := chi.NewRouter()
r.Use(container.apiKeyAuth()) r.Use(container.apiKeyAuth())
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
articleHandler := article.NewHandler(container.CreateArticleUseCase, container.GetArticleUseCase, container.ListArticlesUseCase, container.DeleteArticleUseCase, container.UpdateArticleUseCase, container.GetUserUseCase) articleHandler := article.NewHandler(container.CreateArticleUseCase, container.GetArticleUseCase, container.ListArticlesUseCase, container.DeleteArticleUseCase, container.UpdateArticleUseCase, container.CreateTranslationUseCase, container.DescribeArticleUseCase)
seoHandler := article.NewSEOHandler(container.ResolveArticleSEOUseCase, container.CheckArticleSEOUseCase, container.GetUserUseCase) seoHandler := article.NewSEOHandler(container.ResolveArticleSEOUseCase, container.CheckArticleSEOUseCase)
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(middleware.OptionalAccess(container.GetUserUseCase, container.CheckPermissionUseCase))
r.Get("/", articleHandler.ListArticles) r.Get("/", articleHandler.ListArticles)
r.Get("/{id}", articleHandler.GetArticle) r.Get("/{id}", articleHandler.GetArticle)
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.With(container.requireArticle(role.KeyContentCreate)).Post("/", articleHandler.PostArticle)
r.Delete("/{id}", articleHandler.DeleteArticle) r.With(container.requireArticle(role.KeyContentCreate)).Post("/{id}/translations", articleHandler.PostTranslation)
r.Patch("/{id}", articleHandler.UpdateArticleBody) r.With(container.requireArticle(role.KeyContentDelete)).Delete("/{id}", articleHandler.DeleteArticle)
r.Patch("/{id}/publish", articleHandler.PublishArticle) r.With(container.requireArticle(role.KeyContentUpdate)).Patch("/{id}", articleHandler.UpdateArticleBody)
r.Patch("/{id}/unpublish", articleHandler.UnpublishArticle) r.With(container.requireArticle(role.KeyContentPublish)).Patch("/{id}/publish", articleHandler.PublishArticle)
r.Post("/{id}/seo/check", seoHandler.Check) r.With(container.requireArticle(role.KeyContentPublish)).Patch("/{id}/unpublish", articleHandler.UnpublishArticle)
r.With(container.requireArticle(role.KeyContentRead)).Post("/{id}/seo/check", seoHandler.Check)
})
return r
}
func NewPublicRouter(container *UseCases, trustedProxies []string) http.Handler {
r := chi.NewRouter()
r.Use(container.publicReadLimit(trustedProxies))
publicHandler := article.NewPublicHandler(container.ResolvePublicArticleUseCase)
r.Get("/site/{key}/lang/{lang}/article/{slug}", publicHandler.Lookup)
r.Get("/site/{key}/story/{story_id}", publicHandler.Story)
return r
}
func NewStoryRouter(container *UseCases, trustedProxies []string) http.Handler {
r := chi.NewRouter()
r.Use(container.apiKeyAuth())
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
storyHandler := story.NewHandler(container.MoveStoryUseCase, container.DeleteStoryUseCase)
r.Group(func(r chi.Router) {
r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.With(container.requireArticle(role.KeyContentUpdate)).Post("/{story_id}/move", storyHandler.Move)
r.With(container.requireArticle(role.KeyContentDelete)).Delete("/{story_id}", storyHandler.Delete)
}) })
return r return r
} }
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)
verificationHandler := auth.NewVerificationHandler(container.VerifyUserUseCase, container.CancelRegistrationUseCase, isProduction) verificationHandler := auth.NewVerificationHandler(container.VerifyUserUseCase, container.CancelRegistrationUseCase, isProduction)
meHandler := auth.NewMeHandler(container.GetUserUseCase, container.GetMyAuthorUseCase) meHandler := auth.NewMeHandler(container.GetUserUseCase, container.GetMyAuthorUseCase, container.GetMyAccessUseCase)
passwordResetHandler := auth.NewPasswordResetHandler(container.RequestPasswordResetUseCase, container.ResetPasswordUseCase) passwordResetHandler := auth.NewPasswordResetHandler(container.RequestPasswordResetUseCase, container.ResetPasswordUseCase)
emailChangeHandler := auth.NewEmailChangeHandler(container.RequestEmailChangeUseCase, container.ResendEmailChangeUseCase, container.CancelEmailChangeUseCase, container.ConfirmEmailChangeUseCase)
acceptInviteHandler := auth.NewAcceptInviteHandler(container.GetInviteUseCase, container.AcceptInviteUseCase, container.Token, isProduction) acceptInviteHandler := auth.NewAcceptInviteHandler(container.GetInviteUseCase, container.AcceptInviteUseCase, container.Token, isProduction)
r.Post("/register", loginHandler.Register) r.Post("/register", loginHandler.Register)
@@ -114,46 +197,111 @@ 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(middleware.RequireSession)
r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn)
r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Delete("/email/change", emailChangeHandler.Cancel)
r.Post("/email/confirm", emailChangeHandler.Confirm)
r.Group(func(r chi.Router) {
r.Use(middleware.NewUserRateLimiter(emailChangeMaxRequests, emailChangeWindow))
r.Post("/email/change", emailChangeHandler.Request)
r.Post("/email/resend", emailChangeHandler.Resend)
})
})
r.Group(func(r chi.Router) {
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)
}) })
return r return r
} }
func NewUserRouter(container *UseCases, rateLimit config.AuthRateLimitSettings, trustedProxies []string) http.Handler { func NewUserRouter(container *UseCases, isProduction bool, rateLimit config.AuthRateLimitSettings, trustedProxies []string) http.Handler {
r := chi.NewRouter() r := chi.NewRouter()
userHandler := user.NewHandler(container.UpdateUserProfileUseCase) userHandler := user.NewHandler(container.UpdateUserProfileUseCase)
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)
roleHandler := user.NewRoleHandler(container.ChangeUserRoleUseCase)
removeHandler := user.NewRemoveHandler(container.RemoveUserUseCase)
exportHandler := user.NewExportHandler(container.ExportUserDataUseCase)
deleteAccountHandler := user.NewDeleteAccountHandler(container.DeleteOwnAccountUseCase, isProduction)
r.Use(jwtauth.Verifier(container.Token)) r.Group(func(r chi.Router) {
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)
r.Get("/", inviteHandler.ListUsers) r.With(container.require(role.KeyUsersView)).Get("/", inviteHandler.ListUsers)
r.Get("/lookup", lookupHandler.Lookup) r.Get("/lookup", lookupHandler.Lookup)
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(middleware.RequireOwner(container.GetUserUseCase)) r.Use(container.require(role.KeyUsersInvite))
r.Use(middleware.TrustedProxyRealIP(trustedProxies)) r.Use(middleware.TrustedProxyRealIP(trustedProxies))
r.Use(middleware.NewRateLimiter(rateLimit.MaxAttempts, rateLimit.Window)) r.Use(middleware.NewRateLimiter(rateLimit.MaxAttempts, rateLimit.Window))
r.Post("/invite", inviteHandler.CreateInvite) r.Post("/invite", inviteHandler.CreateInvite)
r.Delete("/invite/{id}", inviteHandler.CancelInvite) r.Delete("/invite/{id}", inviteHandler.CancelInvite)
r.Post("/invite/{id}/renew", inviteHandler.RenewInvite) r.Post("/invite/{id}/renew", inviteHandler.RenewInvite)
}) })
})
r.Group(func(r chi.Router) {
r.Use(middleware.RequireSession)
r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn)
r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.With(middleware.NewUserSuccessLimiter(dataExportWindow)).Get("/me/export", exportHandler.Export)
})
r.Group(func(r chi.Router) {
r.Use(middleware.RequireSession)
r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn)
r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Use(middleware.NewUserRateLimiter(accountDeleteMaxRequests, accountDeleteWindow))
r.Delete("/me", deleteAccountHandler.Delete)
})
r.Group(func(r chi.Router) {
r.Use(middleware.RequireSession)
r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn)
r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Use(container.require(role.KeyUsersChangeRole))
r.Put("/{id}/role", roleHandler.Change)
})
r.Group(func(r chi.Router) {
r.Use(middleware.RequireSession)
r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn)
r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Use(container.require(role.KeyUsersRemove))
r.Delete("/{id}", removeHandler.Remove)
})
return r return r
} }
@@ -163,22 +311,23 @@ 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.Use(container.require(role.KeySettingsView))
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(container.require(role.KeySystemEditRetention))
r.Patch("/", settingsHandler.UpdateSettings) r.Patch("/", settingsHandler.UpdateSettings)
}) })
return r return r
@@ -191,28 +340,87 @@ func NewSiteRouter(container *UseCases, trustedProxies []string) http.Handler {
sitemapHandler := site.NewSitemapHandler(container.ListSitemapUseCase) sitemapHandler := site.NewSitemapHandler(container.ListSitemapUseCase)
r.Get("/{key}/sitemap", sitemapHandler.Sitemap) siteLanguagesHandler := languagehandler.NewSiteLanguagesHandler(container.GetSiteLanguagesUseCase, container.UpdateSiteLanguagesUseCase)
ownershipHandler := ownership.NewHandler(container.TransferOwnershipUseCase)
r.With(container.publicReadLimit(trustedProxies)).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.Get("/{key}/languages", siteLanguagesHandler.Get)
}) })
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.With(container.require(role.KeySettingsManageSites)).Post("/", siteHandler.Create)
r.Post("/", siteHandler.Create) r.With(container.require(role.KeySettingsManageSites)).Patch("/{id}", siteHandler.Update)
r.Patch("/{id}", siteHandler.Update) r.With(container.require(role.KeySettingsManageSites)).Patch("/{id}/default", siteHandler.SetDefault)
r.Patch("/{id}/default", siteHandler.SetDefault) r.With(container.require(role.KeySettingsManageSites)).Put("/{key}/languages", siteLanguagesHandler.Update)
r.Delete("/{id}", siteHandler.Delete) r.With(container.require(role.KeySettingsDeleteSite)).Delete("/{id}", siteHandler.Delete)
r.With(container.require(role.KeySystemTransferOwnership)).Post("/transfer-ownership", ownershipHandler.Transfer)
})
return r
}
func NewLanguageRouter(container *UseCases, trustedProxies []string) http.Handler {
r := chi.NewRouter()
setupHandler := languagehandler.NewSetupHandler(container.GetLanguageSetupUseCase, container.ApplyLanguageSetupUseCase)
r.Group(func(r chi.Router) {
r.Use(middleware.RequireSession)
r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn)
r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Use(container.require(role.KeySettingsManageSites))
r.Get("/setup", setupHandler.Get)
r.Post("/setup", setupHandler.Apply)
})
return r
}
func NewRoleRouter(container *UseCases, trustedProxies []string) http.Handler {
r := chi.NewRouter()
roleHandler := rolehandler.NewHandler(container.ListRolesUseCase, container.GetRoleUseCase, container.CreateRoleUseCase, container.UpdateRoleUseCase, container.DeleteRoleUseCase, container.ReassignRoleMembersUseCase)
r.Group(func(r chi.Router) {
r.Use(authtoken.Verifier(container.Token))
r.Use(container.apiKeyAuth())
r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Use(container.require(role.KeyRolesView))
r.Get("/", roleHandler.List)
r.Get("/{id}", roleHandler.Get)
})
r.Group(func(r chi.Router) {
r.Use(middleware.RequireSession)
r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn)
r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Use(container.require(role.KeyRolesManage))
r.Post("/", roleHandler.Create)
r.Put("/{id}", roleHandler.Update)
r.Delete("/{id}", roleHandler.Delete)
r.Post("/{id}/reassign", roleHandler.Reassign)
r.Post("/{id}/reset", roleHandler.Reset)
}) })
return r return r
} }
@@ -220,31 +428,29 @@ func NewSiteRouter(container *UseCases, trustedProxies []string) http.Handler {
func NewAuthorRouter(container *UseCases, trustedProxies []string) http.Handler { func NewAuthorRouter(container *UseCases, trustedProxies []string) http.Handler {
r := chi.NewRouter() r := chi.NewRouter()
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)
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.Use(container.require(role.KeyAuthorsView))
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)
r.Patch("/{id}", authorHandler.Update) r.With(container.require(role.KeyAuthorsEdit)).Patch("/{id}", authorHandler.Update)
r.Group(func(r chi.Router) { r.With(container.require(role.KeyAuthorsCreate)).Post("/", authorHandler.Create)
r.Use(middleware.RequireOwnerOrAdmin(container.GetUserUseCase)) r.With(container.require(role.KeyAuthorsDelete)).Delete("/{id}", authorHandler.Delete)
r.Post("/", authorHandler.Create)
r.Delete("/{id}", authorHandler.Delete)
})
}) })
return r return r
} }
@@ -256,26 +462,23 @@ 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.With(container.require(role.KeySchemaView)).Get("/", contentTypeHandler.List)
r.Get("/{key}", contentTypeHandler.Get) r.With(container.require(role.KeySchemaView)).Get("/{key}", contentTypeHandler.Get)
r.Group(func(r chi.Router) { r.With(container.require(role.KeySchemaEdit)).Post("/", contentTypeHandler.Create)
r.Use(middleware.RequireOwnerOrAdmin(container.GetUserUseCase)) r.With(container.require(role.KeySchemaEdit)).Put("/{key}", contentTypeHandler.Update)
r.Post("/", contentTypeHandler.Create) r.With(container.require(role.KeySchemaDelete)).Delete("/{key}", contentTypeHandler.Delete)
r.Put("/{key}", contentTypeHandler.Update) r.With(container.requireEntry(role.KeyContentRead)).Get("/{key}/entry", entryHandler.List)
r.Delete("/{key}", contentTypeHandler.Delete) r.With(container.requireEntry(role.KeyContentCreate)).Post("/{key}/entry", entryHandler.Create)
}) r.With(container.requireEntry(role.KeyContentRead)).Get("/{key}/entry/{id}", entryHandler.Get)
r.Get("/{key}/entry", entryHandler.List) r.With(container.requireEntry(role.KeyContentUpdate)).Put("/{key}/entry/{id}", entryHandler.Update)
r.Post("/{key}/entry", entryHandler.Create) r.With(container.requireEntry(role.KeyContentDelete)).Delete("/{key}/entry/{id}", entryHandler.Delete)
r.Get("/{key}/entry/{id}", entryHandler.Get)
r.Put("/{key}/entry/{id}", entryHandler.Update)
r.Delete("/{key}/entry/{id}", entryHandler.Delete)
return r return r
} }
@@ -284,14 +487,14 @@ 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(container.require(role.KeySchemaView))
r.Get("/", builtinTypeHandler.List) r.Get("/", builtinTypeHandler.List)
r.Get("/{key}", builtinTypeHandler.Get) r.Get("/{key}", builtinTypeHandler.Get)
return r return r
@@ -303,18 +506,15 @@ 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.With(container.require(role.KeyActivityView)).Get("/", activityHandler.List)
r.Group(func(r chi.Router) { r.With(container.requireAll(role.KeyActivityView)).Get("/summary", activityHandler.Summary)
r.Use(middleware.RequireOwnerOrAdmin(container.GetUserUseCase)) r.With(container.require(role.KeyActivityExport), container.require(role.KeyActivityView)).Get("/export", activityHandler.Export)
r.Get("/summary", activityHandler.Summary)
r.Get("/export", activityHandler.Export)
})
return r return r
} }
@@ -328,27 +528,27 @@ const (
func NewSystemRouter(container *UseCases, trustedProxies []string) http.Handler { func NewSystemRouter(container *UseCases, trustedProxies []string) http.Handler {
r := chi.NewRouter() r := chi.NewRouter()
updateHandler := update.NewHandler(container.GetUpdateStatusUseCase, container.CheckForUpdateUseCase, container.StartUpdateDownloadUseCase, container.RequestRestartUseCase, container.GetUserUseCase) updateHandler := update.NewHandler(container.GetUpdateStatusUseCase, container.CheckForUpdateUseCase, container.StartUpdateDownloadUseCase, container.RequestRestartUseCase)
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.With(container.require(role.KeySettingsView)).Get("/update", updateHandler.GetStatus)
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(middleware.RequireOwner(container.GetUserUseCase)) r.Use(container.require(role.KeySystemApplyUpdates))
r.Use(middleware.NewUserRateLimiter(updateCheckMaxAttempts, updateCheckWindow)) r.Use(middleware.NewUserRateLimiter(updateCheckMaxAttempts, updateCheckWindow))
r.Post("/update/check", updateHandler.Check) r.Post("/update/check", updateHandler.Check)
}) })
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(middleware.RequireOwner(container.GetUserUseCase)) r.Use(container.require(role.KeySystemApplyUpdates))
r.Use(middleware.NewUserRateLimiter(updateDownloadMaxAttempts, updateDownloadWindow)) r.Use(middleware.NewUserRateLimiter(updateDownloadMaxAttempts, updateDownloadWindow))
r.Post("/update/download", updateHandler.Download) r.Post("/update/download", updateHandler.Download)
}) })
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(middleware.RequireOwner(container.GetUserUseCase)) r.Use(container.require(role.KeySystemApplyUpdates))
r.Post("/update/restart", updateHandler.Restart) r.Post("/update/restart", updateHandler.Restart)
}) })
return r return r
@@ -360,14 +560,28 @@ 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.With(container.require(role.KeyAPIKeysCreate)).Post("/", apiKeyHandler.Create)
r.Get("/", apiKeyHandler.List) r.With(container.require(role.KeyAPIKeysView)).Get("/", apiKeyHandler.List)
r.Delete("/{id}", apiKeyHandler.Revoke) r.With(container.require(role.KeyAPIKeysRevoke)).Delete("/{id}", apiKeyHandler.Revoke)
return r
}
func NewPermissionRouter(container *UseCases) http.Handler {
r := chi.NewRouter()
permissionHandler := permission.NewHandler(container.ListPermissionsUseCase)
r.Use(authtoken.Verifier(container.Token))
r.Use(container.apiKeyAuth())
r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Get("/", permissionHandler.List)
return r return r
} }
@@ -376,35 +590,31 @@ 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.With(container.require(role.KeySettingsView)).Get("/purge-settings", mediaHandler.GetPurgeSettings)
r.Use(middleware.RequireOwnerOrAdmin(container.GetUserUseCase)) r.With(container.require(role.KeySettingsEditGeneral)).Patch("/purge-settings", mediaHandler.UpdatePurgeSettings)
r.Get("/purge-settings", mediaHandler.GetPurgeSettings) r.With(container.requireAll(role.KeyMediaDelete)).Get("/purge-preview", mediaHandler.PreviewPurge)
r.Patch("/purge-settings", mediaHandler.UpdatePurgeSettings) r.With(container.requireAll(role.KeyMediaDelete)).Post("/purge", mediaHandler.RunPurge)
r.Get("/purge-preview", mediaHandler.PreviewPurge)
r.Post("/purge", mediaHandler.RunPurge)
})
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(middleware.RejectAPIKey) r.Use(middleware.RejectAPIKey)
r.Use(middleware.RequireOwnerOrAdmin(container.GetUserUseCase)) r.With(container.require(role.KeyMediaView)).Get("/{id}/variants", mediaHandler.ListVariants)
r.Get("/{id}/variants", mediaHandler.ListVariants) r.With(container.require(role.KeySettingsEditGeneral)).Post("/{id}/variants", mediaHandler.GenerateAllVariants)
r.Post("/{id}/variants", mediaHandler.GenerateAllVariants) r.With(container.require(role.KeySettingsEditGeneral)).Post("/{id}/variants/{name}", mediaHandler.GenerateVariant)
r.Post("/{id}/variants/{name}", mediaHandler.GenerateVariant) r.With(container.require(role.KeySettingsEditGeneral)).Delete("/{id}/variants/{name}", mediaHandler.PurgeVariant)
r.Delete("/{id}/variants/{name}", mediaHandler.PurgeVariant)
}) })
r.Get("/", mediaHandler.List) r.With(container.require(role.KeyMediaView)).Get("/", mediaHandler.List)
r.Post("/", mediaHandler.Upload) r.With(container.require(role.KeyMediaUpload)).Post("/", mediaHandler.Upload)
r.Post("/merge", mediaHandler.Merge) r.With(container.requireAll(role.KeyMediaDelete)).Post("/merge", mediaHandler.Merge)
r.Patch("/{id}", mediaHandler.Rename) r.With(container.require(role.KeyMediaUpload)).Patch("/{id}", mediaHandler.Rename)
r.Delete("/{id}", mediaHandler.Delete) r.With(container.requireAll(role.KeyMediaDelete)).Delete("/{id}", mediaHandler.Delete)
r.Get("/{id}", mediaHandler.Get) r.With(container.require(role.KeyMediaView)).Get("/{id}", mediaHandler.Get)
r.Get("/{id}/usage", mediaHandler.Usage) r.With(container.require(role.KeyMediaView)).Get("/{id}/usage", mediaHandler.Usage)
return r return r
} }
@@ -413,21 +623,20 @@ 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.With(container.require(role.KeyMediaView)).Get("/", variantHandler.List)
r.Get("/", variantHandler.List) r.With(container.require(role.KeySettingsEditGeneral)).Post("/", variantHandler.Create)
r.Post("/", variantHandler.Create) r.With(container.require(role.KeySettingsView)).Get("/cache", variantHandler.CacheStats)
r.Get("/cache", variantHandler.CacheStats) r.With(container.require(role.KeySettingsEditGeneral)).Post("/cache/purge", variantHandler.PurgeCache)
r.Post("/cache/purge", variantHandler.PurgeCache) r.With(container.require(role.KeySettingsEditGeneral)).Put("/{name}", variantHandler.Update)
r.Put("/{name}", variantHandler.Update) r.With(container.require(role.KeySettingsEditGeneral)).Patch("/{name}", variantHandler.SetEnabled)
r.Patch("/{name}", variantHandler.SetEnabled) r.With(container.require(role.KeySettingsEditGeneral)).Delete("/{name}", variantHandler.Delete)
r.Delete("/{name}", variantHandler.Delete) r.With(container.require(role.KeySettingsEditGeneral)).Post("/{name}/purge", variantHandler.Purge)
r.Post("/{name}/purge", variantHandler.Purge)
return r return r
} }
@@ -440,12 +649,16 @@ 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("/story", NewStoryRouter(container, settings.TrustedProxies))
}) })
r.Mount("/user", NewUserRouter(container, settings.AuthRateLimit, settings.TrustedProxies)) r.Mount("/public", NewPublicRouter(container, settings.TrustedProxies))
r.Mount("/user", NewUserRouter(container, settings.IsProduction(), settings.AuthRateLimit, settings.TrustedProxies))
r.Mount("/settings", NewSettingsRouter(container, settings.TrustedProxies)) r.Mount("/settings", NewSettingsRouter(container, settings.TrustedProxies))
r.Mount("/site", NewSiteRouter(container, settings.TrustedProxies)) r.Mount("/site", NewSiteRouter(container, settings.TrustedProxies))
r.Mount("/language", NewLanguageRouter(container, settings.TrustedProxies))
r.Mount("/role", NewRoleRouter(container, settings.TrustedProxies))
r.Mount("/author", NewAuthorRouter(container, settings.TrustedProxies)) r.Mount("/author", NewAuthorRouter(container, settings.TrustedProxies))
r.Mount("/content-type", NewContentTypeRouter(container, settings.TrustedProxies)) r.Mount("/content-type", NewContentTypeRouter(container, settings.TrustedProxies))
r.Mount("/builtin-type", NewBuiltinTypeRouter(container, settings.TrustedProxies)) r.Mount("/builtin-type", NewBuiltinTypeRouter(container, settings.TrustedProxies))
@@ -453,6 +666,7 @@ func InitBackendRoutes(container *UseCases, settings config.Settings) *chi.Mux {
r.Mount("/media", NewMediaRouter(container, settings.TrustedProxies)) r.Mount("/media", NewMediaRouter(container, settings.TrustedProxies))
r.Mount("/image-variants", NewImageVariantRouter(container, settings.TrustedProxies)) r.Mount("/image-variants", NewImageVariantRouter(container, settings.TrustedProxies))
r.Mount("/api-key", NewAPIKeyRouter(container, settings.TrustedProxies)) r.Mount("/api-key", NewAPIKeyRouter(container, settings.TrustedProxies))
r.Mount("/permission", NewPermissionRouter(container))
r.Mount("/system", NewSystemRouter(container, settings.TrustedProxies)) r.Mount("/system", NewSystemRouter(container, settings.TrustedProxies))
r.Mount("/auth", NewAuthRouter(container, settings.IsProduction(), settings.AuthRateLimit, settings.TrustedProxies)) r.Mount("/auth", NewAuthRouter(container, settings.IsProduction(), settings.AuthRateLimit, settings.TrustedProxies))
@@ -478,14 +692,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,8 +702,10 @@ 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)
llms.NewHandler(llmdocs.Docs, settings.Version, settings.PublicURL).Register(apiRouter)
apiRouter.Mount("/v1", backend) apiRouter.Mount("/v1", backend)
apiRouter.Mount("/static/uploadedImages", staticimages.NewHandler(container.OpenMediaUseCase, container.ServeVariantUseCase)) apiRouter.Mount("/static/uploadedImages", staticimages.NewHandler(container.OpenMediaUseCase, container.ServeVariantUseCase))
apiRouter.Mount("/", frontend) apiRouter.Mount("/", frontend)
+43
View File
@@ -0,0 +1,43 @@
package main
import (
"RenewCMS/internal/infrastructure/mcpserver"
"context"
"flag"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
var version = "dev"
func main() {
allowDestructive := flag.Bool("allow-destructive", false, "also expose delete_article and delete_media")
showVersion := flag.Bool("version", false, "print the version and exit")
flag.Parse()
if *showVersion {
fmt.Println(version)
return
}
baseURL := os.Getenv("RENEWCMS_URL")
apiKey := os.Getenv("RENEWCMS_API_KEY")
if baseURL == "" || apiKey == "" {
log.Fatal("RENEWCMS_URL and RENEWCMS_API_KEY must be set")
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
server := mcpserver.New(mcpserver.NewClient(baseURL, apiKey, nil), mcpserver.Options{
Version: version,
AllowDestructive: *allowDestructive,
})
if err := server.Run(ctx, &mcp.StdioTransport{}); err != nil {
log.Fatal(err)
}
}
+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")
} }
+283 -26
View File
@@ -3,16 +3,17 @@
The full, searchable reference is the Integration page of the running app (`/integration`). It The full, searchable reference is the Integration page of the running app (`/integration`). It
renders `web/src/data/apiCatalogue.ts`, which is the single source for this page. This file is for renders `web/src/data/apiCatalogue.ts`, which is the single source for this page. This file is for
readers without the UI. Reading articles (pagination, `format`, body schemas) has its own page, readers without the UI. Reading articles (pagination, `format`, body schemas) has its own page,
[api/articles.md](api/articles.md), and API keys are covered in [api/api-keys.md](api/api-keys.md). [api/articles.md](api/articles.md), versions, translations, the story move and the story-grouped editorial list (`GET /v1/article/?group=story`) have [api/article-localization.md](api/article-localization.md), site languages and the one-time language setup are in [api/site-languages.md](api/site-languages.md), and API keys are covered in [api/api-keys.md](api/api-keys.md).
## Base URL ## Base URL
The origin that serves the app, for example `https://cms.example`. Every path starts with `/v1`, The origin that serves the app, for example `https://cms.example`. Every path starts with `/v1`,
for example `https://cms.example/v1/article/`. for example `https://cms.example/v1/article/`.
## Authentication ## Authentication
- Public routes need nothing: `GET /v1/article/`, `GET /v1/article/{id}`, `GET /v1/article/{id}/seo` - Public routes need nothing: `GET /v1/article/`, `GET /v1/article/{id}`, `GET /v1/article/{id}/seo`,
and `GET /v1/site/{key}/sitemap`. They return online articles only; the list and the resolved SEO `GET /v1/site/{key}/sitemap`, `GET /v1/public/site/{key}/lang/{lang}/article/{slug}` and
object also answer drafts to a verified session or API key. `GET /v1/public/site/{key}/story/{story_id}` (the two language routes ignore any credential and never return a draft, see [api/article-localization.md](api/article-localization.md#public-language-routes)). They return online articles, plus the drafts the caller's role may read
(see [Content permissions](#content-permissions)); any other draft answers 404 `Article not found`.
- Everything else needs a signed-in browser session (the `jwt` cookie) or an API key: - Everything else needs a signed-in browser session (the `jwt` cookie) or an API key:
`Authorization: Bearer rcms_...`. Create keys at `/integration/api-keys`. A key acts as its `Authorization: Bearer rcms_...`. Create keys at `/integration/api-keys`. A key acts as its
creator, with that user's role, and shows in full once. creator, with that user's role, and shows in full once.
@@ -21,13 +22,19 @@ 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 (32)
| Group | Routes | | Group | Routes |
| --- | --- | | --- | --- |
| Articles | GET /v1/article/, GET /v1/article/{id}, GET /v1/article/{id}/seo, POST /v1/article/{id}/seo/check, POST /v1/article/, PATCH /v1/article/{id}, PATCH /v1/article/{id}/publish, PATCH /v1/article/{id}/unpublish, DELETE /v1/article/{id} | | Articles | GET /v1/article/, GET /v1/article/{id}, GET /v1/article/{id}/seo, POST /v1/article/{id}/seo/check, POST /v1/article/, PATCH /v1/article/{id}, PATCH /v1/article/{id}/publish, PATCH /v1/article/{id}/unpublish, DELETE /v1/article/{id}, POST /v1/article/{id}/translations, POST /v1/story/{story_id}/move |
| Media | GET /v1/media/, GET /v1/media/{id}, POST /v1/media/, PATCH /v1/media/{id}, DELETE /v1/media/{id}, POST /v1/media/merge, GET /v1/media/{id}/usage, GET /v1/media/purge-settings (owner or admin), PATCH /v1/media/purge-settings (owner or admin), GET /v1/media/purge-preview (owner or admin), POST /v1/media/purge (owner or admin), GET /v1/media/{id}/variants (owner or admin, session only), POST /v1/media/{id}/variants (owner or admin, session only), POST /v1/media/{id}/variants/{name} (owner or admin, session only), DELETE /v1/media/{id}/variants/{name} (owner or admin, session only) | | Media | GET /v1/media/, GET /v1/media/{id}, POST /v1/media/, PATCH /v1/media/{id}, DELETE /v1/media/{id}, POST /v1/media/merge, GET /v1/media/{id}/usage, GET /v1/media/purge-settings (owner or admin), PATCH /v1/media/purge-settings (owner or admin), GET /v1/media/purge-preview (owner or admin), POST /v1/media/purge (owner or admin), GET /v1/media/{id}/variants (owner or admin, session only), POST /v1/media/{id}/variants (owner or admin, session only), POST /v1/media/{id}/variants/{name} (owner or admin, session only), DELETE /v1/media/{id}/variants/{name} (owner or admin, session only) |
| Users and invites | GET /v1/user/, PATCH /v1/user/me, POST /v1/user/invite (owner only), DELETE /v1/user/invite/{id} (owner only), POST /v1/user/invite/{id}/renew (owner only), GET /v1/auth/me (with the linked `author`) | | Users and invites | GET /v1/user/ (`users.view`), PATCH /v1/user/me, GET /v1/user/me/export, DELETE /v1/user/me, POST /v1/user/invite (`users.invite`), DELETE /v1/user/invite/{id} (`users.invite`), POST /v1/user/invite/{id}/renew (`users.invite`), GET /v1/auth/me (with the linked `author`) |
| Settings | GET /v1/settings | | Settings | GET /v1/settings |
| Sites | GET /v1/site/, GET /v1/site/{key}/sitemap | | Sites | GET /v1/site/, GET /v1/site/{key}/sitemap |
| Authors | GET /v1/author/ | | Authors | GET /v1/author/ |
@@ -39,12 +46,12 @@ key never reads the audit trail. Events are append-only; there is no `POST`, `PU
| Route | Who | Purpose | | Route | Who | Purpose |
| --- | --- | --- | | --- | --- | --- |
| `GET /v1/activity` | Any verified user | Filtered, paged events. Owner and admin see every event; any other role is scoped to its own events, and `actor` set to someone else answers 403 "Only owners and admins can do this." | | `GET /v1/activity` | Any verified user | Filtered, paged events. A role with `activity.view` at all sees every event; a role at own is scoped to its own events, and `actor` set to someone else answers 403 `missing_permission`. |
| `GET /v1/activity/summary` | Owner, admin | Counts for the range, the previous period, active people and seven-bucket series. | | `GET /v1/activity/summary` | Owner, admin | Counts for the range, the previous period, active people and seven-bucket series. |
| `GET /v1/activity/export` | Owner, admin | The same filters as the list without `page` or `size`, as a `text/csv; charset=utf-8` attachment (`when,actor,action,target,outcome,source,ip`). Cells starting with `=`, `+`, `-` or `@` get a leading quote. | | `GET /v1/activity/export` | Owner, admin | The same filters as the list without `page` or `size`, as a `text/csv; charset=utf-8` attachment (`when,actor,action,target,outcome,source,ip`). Cells starting with `=`, `+`, `-` or `@` get a leading quote. |
Query: `q`, `actor` (`user:ID`, `key:ID`, `system`), `category` (`articles`, `media`, `users`, Query: `q`, `actor` (`user:ID`, `key:ID`, `system`), `category` (`articles`, `media`, `users`,
`api_keys`, `auth`, `system`, `sites`, `authors`), `outcome` (`all`, `success`, `failed`), `security` (`true`), `range` `api_keys`, `auth`, `system`, `sites`, `authors`, `roles`), `outcome` (`all`, `success`, `failed`), `security` (`true`), `range`
(`today`, `7d`, `30d`, `all`, `custom`; default `7d`), `from` and `to` (dates, with `custom`), `page` (from (`today`, `7d`, `30d`, `all`, `custom`; default `7d`), `from` and `to` (dates, with `custom`), `page` (from
1) and `size` (25, 50 or 100). Any invalid value answers 400 with the body-mismatch message. Dates 1) and `size` (25, 50 or 100). Any invalid value answers 400 with the body-mismatch message. Dates
are UTC. The list answers `{ items, total, page, size }`, newest first (`created_at`, then `id`). are UTC. The list answers `{ items, total, page, size }`, newest first (`created_at`, then `id`).
@@ -53,7 +60,7 @@ are UTC. The list answers `{ items, total, page, size }`, newest first (`created
90), `activity_retention_max_gb` (0 for no size limit), `activity_log_size_bytes`, 90), `activity_retention_max_gb` (0 for no size limit), `activity_log_size_bytes`,
`activity_last_cleanup_at` and `activity_last_cleanup_removed`. `PATCH /v1/settings` with `activity_last_cleanup_at` and `activity_last_cleanup_removed`. `PATCH /v1/settings` with
`{"activity_retention_days": 30}`, `{"activity_retention_max_gb": 5}` or both is session only and `{"activity_retention_days": 30}`, `{"activity_retention_max_gb": 5}` or both is session only and
owner only (403 "Only the owner can do this."); any other value answers 400. The daily cleanup needs `system.edit_retention` (403 `missing_permission`); any other value answers 400. The daily cleanup
removes events past the age limit, then the oldest events until the log fits the size limit. removes events past the age limit, then the oldest events until the log fits the size limit.
Whichever limit is reached first wins. Whichever limit is reached first wins.
@@ -68,15 +75,15 @@ never changes the response or the change itself.
| --- | --- | | --- | --- |
| `articles` | `article.create`, `article.edit`, `article.publish`, `article.unpublish`, `article.delete` | | `articles` | `article.create`, `article.edit`, `article.publish`, `article.unpublish`, `article.delete` |
| `media` | `media.upload`, `media.rename`, `media.delete`, `media.merge`, `media.purge`, `media.variant_create`, `media.variant_update`, `media.variant_delete`, `media.variant_enable`, `media.variant_disable`, `media.variant_purge`, `media.variant_generate_all`, `media.variant_purge_image`, `media.variant_purge_all`, `media.variant_purge_unused` | | `media` | `media.upload`, `media.rename`, `media.delete`, `media.merge`, `media.purge`, `media.variant_create`, `media.variant_update`, `media.variant_delete`, `media.variant_enable`, `media.variant_disable`, `media.variant_purge`, `media.variant_generate_all`, `media.variant_purge_image`, `media.variant_purge_all`, `media.variant_purge_unused` |
| `users` | `user.register`, `user.verify`, `user.update_profile`, `invite.create`, `invite.cancel`, `invite.renew`, `invite.accept` | | `users` | `user.register`, `user.verify`, `user.update_profile`, `user.request_email_change`, `user.resend_email_change`, `user.cancel_email_change`, `user.confirm_email_change`, `user.export_data`, `user.delete_account` (flagged `security`), `user.change_role`, `user.remove`, `user.transfer_ownership` (flagged `security`), `invite.create`, `invite.cancel`, `invite.renew`, `invite.accept` |
| `sites` | `site.create`, `site.edit`, `site.set_default`, `site.delete` | | `sites` | `site.create`, `site.edit`, `site.set_default`, `site.delete`, `site.languages_edit`, `site.language_setup` |
| `authors` | `author.create`, `author.edit`, `author.delete` | | `authors` | `author.create`, `author.edit`, `author.delete` |
| `system` | `system.media_purge` (scheduled), `system.update_checked`, `system.update_downloaded`, `system.restart_requested`, `system.activity_cleanup`, `system.activity_retention_changed` | | `system` | `system.media_purge` (scheduled), `system.update_checked`, `system.update_downloaded`, `system.restart_requested`, `system.activity_cleanup`, `system.activity_retention_changed` |
Target types: `article`, `site`, `author`, `image`, `image_variant` (id and name are the variant name), `user`, `invite`, Target types: `article`, `site`, `author`, `image`, `image_variant` (id and name are the variant name), `user`, `invite`,
`api_key` and `release` (id and name are the tag). `api_key` and `release` (id and name are the tag).
Only the fields `title`, `online`, `body`, `site`, `name`, `base_url`, `default_robots`, `locale`, `default_social_image`, `slug`, `canonical_url`, `noindex`, `cover_image`, `social_image`, `excerpt`, `seo_title`, `seo_description`, `social_title`, `social_description`, `cover_image_alt`, `site_name`, `title_template`, `default_description`, `bio`, `website`, `social_links`, `avatar`, `user`, `authors`, `filename`, `display_name`, `width`, `height`, `fit`, `format` and `quality` appear in `changes` (a site key is never a change; moving an article records `site` with the site names; changing the credited authors records `authors` with the names in order; the `user` change of an author holds usernames, never an email), with the Only the fields `title`, `online`, `body`, `site`, `name`, `base_url`, `default_robots`, `locale`, `default_social_image`, `slug`, `canonical_url`, `noindex`, `cover_image`, `social_image`, `excerpt`, `seo_title`, `seo_description`, `social_title`, `social_description`, `cover_image_alt`, `site_name`, `title_template`, `default_description`, `public_url_pattern`, `bio`, `website`, `social_links`, `avatar`, `user`, `authors`, `filename`, `display_name`, `width`, `height`, `fit`, `format` and `quality` appear in `changes` (a site key is never a change; moving an article records `site` with the site names; changing the credited authors records `authors` with the names in order; the `user` change of an author holds usernames, never an email), with the
kinds `text` and `body`; a body edit carries a signed character count delta and never the text; the free-text SEO fields (`excerpt`, `seo_title`, `seo_description`, `social_title`, `social_description`, `cover_image_alt`) do the same under their own field name, while `slug`, `canonical_url`, `noindex`, `cover_image`, `social_image` (image file names) and the site fields `site_name`, `title_template`, `default_description` carry `before` and `after`. `seo_dismissed` is not an edit and records nothing. A kinds `text` and `body`; a body edit carries a signed character count delta and never the text; the free-text SEO fields (`excerpt`, `seo_title`, `seo_description`, `social_title`, `social_description`, `cover_image_alt`) do the same under their own field name, while `slug`, `canonical_url`, `noindex`, `cover_image`, `social_image` (image file names) and the site fields `site_name`, `title_template`, `default_description`, `public_url_pattern` carry `before` and `after`. `seo_dismissed` is not an edit and records nothing. A
change that leaves a value as it was (same body, same publish state, same file name, same display change that leaves a value as it was (same body, same publish state, same file name, same display
name) records nothing. Params: `media.merge` and `media.purge` and `system.media_purge` carry name) records nothing. Params: `media.merge` and `media.purge` and `system.media_purge` carry
`merged` and `articles_updated`, plus `failed_groups` when a group failed (still outcome `success`); `merged` and `articles_updated`, plus `failed_groups` when a group failed (still outcome `success`);
@@ -132,14 +139,14 @@ dashes (`^[a-z0-9]+(-[a-z0-9]+)*$`) and never changes, `base_url` is `https` (or
stripped, uniqueness is not enforced), `default_robots` is `index` (default) or `noindex`, `locale` stripped, uniqueness is not enforced), `default_robots` is `index` (default) or `noindex`, `locale`
is `null` or a tag such as `en` or `fr-CA` (an empty string means none) and `default_social_image_id` is `null` or a tag such as `en` or `fr-CA` (an empty string means none) and `default_social_image_id`
is `null` or the id of an image. Read access needs a verified session or an API key; every write is is `null` or the id of an image. Read access needs a verified session or an API key; every write is
session only and owner only (403 "Only the owner can do this.", or "This action needs a real session only and need `settings.manage_sites` (`settings.delete_site` for DELETE): 403 `missing_permission`, or "This action needs a real
session." with a key). The role is checked before the body. session." with a key. The role is checked before the body.
| Route | Purpose | | Route | Purpose |
| --- | --- | | --- | --- |
| `GET /v1/site/` | The sites, default first and then by name, each with `article_count`. Query `q` (up to 200 characters, matched in `name`, `key` or `base_url`, ignoring case and accents, `%` and `_` literal), `page` (a whole number from 1) and `size` (5, 25, 50 or 100). Without `page` and `size` every matching site is returned; with only `page`, `size` is 25; with only `size`, `page` is 1. The body stays a JSON array (`[]` when nothing matches, never `null`) and `X-Total-Count` holds the number of matching sites before paging. A page past the end is `200 []` with the total. An invalid `page`, `size` or `q` is 400 with the body-mismatch message and no `X-Total-Count`. | | `GET /v1/site/` | The sites, default first and then by name, each with `article_count`. Query `q` (up to 200 characters, matched in `name`, `key` or `base_url`, ignoring case and accents, `%` and `_` literal), `page` (a whole number from 1) and `size` (5, 25, 50 or 100). Without `page` and `size` every matching site is returned; with only `page`, `size` is 25; with only `size`, `page` is 1. The body stays a JSON array (`[]` when nothing matches, never `null`) and `X-Total-Count` holds the number of matching sites before paging. A page past the end is `200 []` with the total. An invalid `page`, `size` or `q` is 400 with the body-mismatch message and no `X-Total-Count`. |
| `POST /v1/site/` | Create. 201 with the site. `is_default: true` makes it the default. `site_name`, `title_template` and `default_description` are optional and validated like on `PATCH`. | | `POST /v1/site/` | Create. 201 with the site. `is_default: true` makes it the default. `site_name`, `title_template` and `default_description` are optional and validated like on `PATCH`. |
| `PATCH /v1/site/{id}` | Edit `name`, `base_url`, `default_robots`, `locale`, `default_social_image_id`, `site_name`, `title_template`, `default_description`. Absent fields are untouched. `key` may only be repeated unchanged; `is_default` is refused. | | `PATCH /v1/site/{id}` | Edit `name`, `base_url`, `default_robots`, `locale`, `default_social_image_id`, `site_name`, `title_template`, `default_description`, `public_url_pattern` (see [api/site-languages.md](api/site-languages.md)). Absent fields are untouched. `key` may only be repeated unchanged; `is_default` is refused. |
| `PATCH /v1/site/{id}/default` | Make the site the default, atomically. Setting the current default is a no-op. | | `PATCH /v1/site/{id}/default` | Make the site the default, atomically. Setting the current default is a no-op. |
| `DELETE /v1/site/{id}?reassign_to={id}` | 204. A site with articles needs `reassign_to`; the articles move and the site is deleted in one transaction. `reassign_to` is ignored when the site has no article. | | `DELETE /v1/site/{id}?reassign_to={id}` | 204. A site with articles needs `reassign_to`; the articles move and the site is deleted in one transaction. `reassign_to` is ignored when the site has no article. |
@@ -155,8 +162,8 @@ A site also carries `site_name` (at most 100 characters, `""` by default), `titl
Articles carry `site_id`. A new article starts on the default site. `GET /v1/article/?site=<key>` Articles carry `site_id`. A new article starts on the default site. `GET /v1/article/?site=<key>`
keeps only the articles of that site and composes with `status`, `q`, `sort`, `size` and `page`; keeps only the articles of that site and composes with `status`, `q`, `sort`, `size` and `page`;
`counts` stay global, an unknown key answers 200 with no item and an empty `site=` is 400 with the `counts` stay global, an unknown key answers 200 with no item and an empty `site=` is 400 with the
body-mismatch message. `PATCH /v1/article/{id}` takes `body`, `site_id`, `author_ids` and the SEO body-mismatch message. `PATCH /v1/article/{id}` takes `title`, `body`, `site_id`, `author_ids`, the SEO
fields below, and nothing else, such as `title`: absent fields are untouched, an empty object, an object without fields below and `if_revision`, and nothing else: absent fields are untouched, an empty object, an object without
those fields, a `null` value (except on `cover_image_id` and `social_image_id`) or a malformed value is 400 with the body-mismatch message, `site_id: 0` is those fields, a `null` value (except on `cover_image_id` and `social_image_id`) or a malformed value is 400 with the body-mismatch message, `site_id: 0` is
400 with the validator text and an unknown site is 404 `site_not_found`. Moving an article never 400 with the validator text and an unknown site is 404 `site_not_found`. Moving an article never
changes `is_online`. `{"body": ""}` still sets an empty body, but `{}` and `{"body": null}` no longer do: they are 400. changes `is_online`. `{"body": ""}` still sets an empty body, but `{}` and `{"body": null}` no longer do: they are 400.
@@ -167,11 +174,11 @@ RenewCMS renders no page and injects no meta tag: it returns the data a frontend
| Route | Who | Purpose | | Route | Who | Purpose |
| --- | --- | --- | | --- | --- | --- |
| `GET /v1/article/{id}/seo` | public for online articles; a verified session or API key also reads drafts | The resolved object `{ title, description, canonical_url, robots, og, twitter, image, authors, published_at, modified_at, fallbacks, json_ld }`. It never carries the body, the id or `seo_dismissed`, ignores `format`, and writes nothing. An offline article for any other caller, and a missing one, is 404 `Article not found`. | | `GET /v1/article/{id}/seo` | public for online articles; a verified session or API key also reads the drafts its role may read | The resolved object `{ title, description, canonical_url, robots, og, twitter, image, authors, published_at, modified_at, fallbacks, json_ld, lang, alternates }`. It never carries the body, the id or `seo_dismissed`, ignores `format`, and writes nothing. An offline article for any other caller, and a missing one, is 404 `Article not found`. |
| `POST /v1/article/{id}/seo/check` | verified session or API key (401 without credentials, 403 unverified) | Evaluates the article without saving. The body is `{}` or any of the twelve SEO fields of `PATCH` plus `body`; each replaces the saved value for this check only. `site_id`, `author_ids`, unknown fields and `null` (except on `cover_image_id` and `social_image_id`) are 400 with the body-mismatch message. The other validation is the one of `PATCH` (`invalid_slug`, `invalid_url` as 422, `image_not_found`, validator text). Answers `{ status, suggestions, slug }` where `suggestions` is `[{ code, field, params }]` and `slug` is `{ available, suggestion }`. A taken slug is a 200 with `available: false` and the first free `<slug>-N` in `suggestion`, never a 409. | | `POST /v1/article/{id}/seo/check` | verified session or API key (401 without credentials, 403 unverified) | Evaluates the article without saving. The body is `{}` or any of the twelve SEO fields of `PATCH` plus `body`; each replaces the saved value for this check only. `site_id`, `author_ids`, unknown fields and `null` (except on `cover_image_id` and `social_image_id`) are 400 with the body-mismatch message. The other validation is the one of `PATCH` (`invalid_slug`, `invalid_url` as 422, `image_not_found`, validator text). Answers `{ status, suggestions, slug }` where `suggestions` is `[{ code, field, params }]` and `slug` is `{ available, suggestion }`. A taken slug is a 200 with `available: false` and the first free `<slug>-N` in `suggestion`, never a 409. |
| `GET /v1/site/{key}/sitemap` | public | A JSON array `[{ url, modified_at, noindex }]` of the online articles of the site with that key, by id ascending. `url` is `base_url/slug` (never the canonical override). `page` (default 1) and `size` (25, 50, 100 or 500, default 100); an invalid value is 400 with the body-mismatch message. The total is in the `X-Total-Count` header. An unknown key, an id included, is 404 `site_not_found`. | | `GET /v1/site/{key}/sitemap` | public | A JSON array `[{ url, modified_at, noindex, lang }]` of the eligible versions (published, language enabled) of the site with that key, by id ascending. `url` is the localized address when the site has a Public URL pattern, otherwise `base_url/slug` (never the canonical override). `page` (default 1) and `size` (25, 50, 100 or 500, default 100); an invalid value is 400 with the body-mismatch message. The total is in the `X-Total-Count` header. An unknown key, an id included, is 404 `site_not_found`. |
`GET /v1/article/` also takes `seo=ready|suggestions|hidden` (any other value, an empty one included, is 400 with the body-mismatch message, after the `format` check). It is applied before paging and composes with `q`, `status`, `site`, `sort`, `page` and `size`; `total` follows it and `counts` ignore it. Every item carries `seo_status` (`ready`, `suggestions` or `hidden`) and `seo_suggestions` (the number of suggestions that are not dismissed). The filter is evaluated in memory over every matching article, so its cost grows with the number of articles on the site; without it only the returned page is assessed. `GET /v1/article/` also takes `seo=ready|suggestions|hidden` (any other value, an empty one included, is 400 with the body-mismatch message, after the `format` check). It is applied before paging and composes with `q`, `status`, `site`, `sort`, `page` and `size`; `total` follows it and `counts` ignore it. Every item carries `seo_status` (`ready`, `suggestions` or `hidden`) and `seo_suggestions` (the number of suggestions that are not dismissed). The filter reads the status stored on each article (see [SEO status and suggestions](api/articles.md#seo-status-and-suggestions)), in SQL, before paging.
`X-Total-Count` is added to `Access-Control-Expose-Headers` next to `Link`, so a browser on an allowed origin can read it. `X-Total-Count` is added to `Access-Control-Expose-Headers` next to `Link`, so a browser on an allowed origin can read it.
@@ -249,8 +256,8 @@ article is allowed and never blocks publishing.
| `PATCH /v1/author/{id}` | owner or admin on any author; any verified session on the author linked to it; session only | Edit `name`, `slug`, `bio`, `avatar_id`, `website`, `social_links`, `user_id`. Absent fields are untouched, `avatar_id`, `website` and `user_id` accept `null`, `social_links` is replaced as a whole. `user_id` links or unlinks the account and is owner or admin only. | | `PATCH /v1/author/{id}` | owner or admin on any author; any verified session on the author linked to it; session only | Edit `name`, `slug`, `bio`, `avatar_id`, `website`, `social_links`, `user_id`. Absent fields are untouched, `avatar_id`, `website` and `user_id` accept `null`, `social_links` is replaced as a whole. `user_id` links or unlinks the account and is owner or admin only. |
| `DELETE /v1/author/{id}?reassign_to={id\|none}` | owner or admin, session only | 204. An author credited on articles needs `reassign_to`: an author id (that author takes the deleted one's position and is never duplicated on an article) or `none` (the credit is removed). The move and the delete are one transaction. `reassign_to` is ignored when the author has no article. The linked account is untouched. | | `DELETE /v1/author/{id}?reassign_to={id\|none}` | owner or admin, session only | 204. An author credited on articles needs `reassign_to`: an author id (that author takes the deleted one's position and is never duplicated on an article) or `none` (the credit is removed). The move and the delete are one transaction. `reassign_to` is ignored when the author has no article. The linked account is untouched. |
The role checks use the existing bodies: 403 "Only owners and admins can do this." for `POST /` and The role checks use the existing bodies: 403 `missing_permission` for `POST /` and
`DELETE`, 403 `author_rights` for a `PATCH` by an account that is not owner or admin on an author `DELETE`, 403 `author_rights` for a `PATCH` by a role that holds `authors.edit` at own on an author
that is not its own (or that sends `user_id`), and 403 "This action needs a real session." for a key. that is not its own (or that sends `user_id`), and 403 "This action needs a real session." for a key.
Errors are plain text whose body is exactly the token: 404 `author_not_found`, 404 `user_not_found`, Errors are plain text whose body is exactly the token: 404 `author_not_found`, 404 `user_not_found`,
409 `author_slug_taken`, 409 `author_has_articles`, 409 `user_already_linked`, 409 409 `author_slug_taken`, 409 `author_has_articles`, 409 `user_already_linked`, 409
@@ -278,8 +285,7 @@ repoint the avatars of the merged copies and report it as `authors_updated`.
## Image variants ## Image variants
Owners and admins manage named variants of the stored images. These routes are session only (no API Owners and admins manage named variants of the stored images. These routes are session only (no API
key) and sit behind the verified-user check; any other role gets 403 "Only owners and admins can do key) and sit behind the verified-user check; a role without the needed permission gets 403 `missing_permission`. Behaviour, caching and the public `?v=<name>` contract are in [image-variants.md](image-variants.md).
this." Behaviour, caching and the public `?v=<name>` contract are in [image-variants.md](image-variants.md).
| Route | Purpose | | Route | Purpose |
| --- | --- | | --- | --- |
@@ -348,10 +354,261 @@ disabled variant on `POST`), 413 "The source image is too large to generate this
source image can't be read, so this variant can't be generated.", 422 "Variants aren't generated for source image can't be read, so this variant can't be generated.", 422 "Variants aren't generated for
this format." and 500 "Internal server error". this format." and 500 "Internal server error".
## Roles
Routes under `/v1/role`, behind the verified chain. Reads accept a key; every write is session only (a key answers
403 "This action needs a real session."). The permission is checked before the id, the body and any lookup.
| Route | Permission | Purpose |
| --- | --- | --- |
| `GET /v1/role` | `roles.view` | Every role by id, built-ins first. |
| `GET /v1/role/{id}` | `roles.view` | One role. |
| `POST /v1/role` | `roles.manage` | Create a role (201). `built_in` and `locked` in the body are ignored. |
| `PUT /v1/role/{id}` | `roles.manage` | Replace name, description and grants. `version` is required and must match. |
| `DELETE /v1/role/{id}` | `roles.manage` | Delete a role with no members (204). |
| `POST /v1/role/{id}/reassign` | `roles.manage` | Move every member to `{"target_role_id": N}`; answers `{"moved": n}`. |
| `POST /v1/role/{id}/reset` | `roles.manage` and `roles.edit_owner_only` | Restore a built-in role to its seeded grants and description; body `{"version": N}`. |
A role is `{ id, name, description, built_in, locked, version, grants, members, updated_at, updated_by }`.
`grants` is the normalised effective list: catalogue order, unknown keys and owner-only keys on an unlocked role
dropped, duplicates resolved to the most restrictive scope, and a per-type entry (`content.update:events`, scope
`none` included) right after its wildcard. A response is always valid as the `grants` of a `PUT`. `members` counts
the users holding the role plus the open invites (pending or expired, never accepted ones) for it, counted in two
statements whatever the number of roles. A user whose `role_id` is 0 or names no role counts for nobody.
`updated_at` (RFC 3339, UTC) and `updated_by` (`{ id, name }`, the display name else the username) are `null` for a role
never edited since seeding, and `updated_by` is also `null` once the saving user is deleted.
Refusals are plain text, one snake_case code per body:
| Status | Body | When |
| --- | --- | --- |
| 400 | `unknown_permission`, `invalid_scope`, `owner_only_permission`, `duplicate_permission`, `unknown_content_type` | A grant is not valid (`unknown_content_type` for a `content.*:{type}` key that is neither `article` nor a content type). |
| 409 | `target_role_not_found` | `POST /v1/role/{id}/reassign` when the target role does not exist (any longer). |
| 400 | `invalid_role_name`, `built_in_name`, `not_built_in`, `invalid_reassign` | Blank name after trim; renaming a built-in role; resetting a custom role; a bad reassign target (self, 0, a locked role, a role the caller cannot cover). |
| 403 | `role_locked` | Editing, deleting or moving from the Owner role. |
| 403 | `missing_permission` | The usual gate, plus `X-Missing-Permission: roles.edit_owner_only` when a built-in role is edited or reset without that permission. |
| 403 | `own_role` | Editing, deleting or moving members out of the caller's own role. |
| 403 | `escalation` | The caller would grant, or touch a role holding, more than they hold. `X-Escalation-Key` names the first offending key, such as `content.publish` or `content.publish:events`. |
| 404 | `role_not_found` | Unknown role id. |
| 409 | `role_name_taken`, `role_conflict`, `role_has_members`, `role_built_in` | Name already used (case-insensitive); stale `version`; the role still has members (users or open invites); deleting or moving members out of a built-in role. |
Names are trimmed and unique case-insensitively. The order of checks on a write is: permission, id, body, role lookup,
locked, built-in rules, own role, existing role covered by the caller, version, grant validation, new grants covered
by the caller, name taken, write. Only the Owner holds `roles.edit_owner_only`, so only the Owner edits the Admin and
Writer roles; owner-only keys are refused on every role a client can write. A save with nothing changed answers 200
at the same version and records nothing. Members see an edit on their next request, and so do the keys they created.
Activity: `role.create`, `role.edit`, `role.delete` and `role.reassign` in the `roles` category, target
`{ type: "role", id, name }`. `role.edit` carries `name` and `description` changes and the params `added`, `removed`,
`changed` (`{ key, from, to }`) and `members`; `role.reassign` carries `from`, `to`, `to_name` (the destination role's name at move time; absent on older events) and `moved` (users and open invites together) and is recorded only when
`moved` is above 0. A refusal records nothing.
`GET /v1/auth/me` lists per-type entries in `access.permissions` (scope `none` included), right after their wildcard.
Deleting a content type removes its per-type rows from every role (the affected roles' `version` goes up by one), and
creating one with the key of a deleted type clears any stale row for that key.
## Changing the email address
Four session-only routes under `/v1/auth` let a verified user change their own email address. A missing or invalid
cookie is 401, an API key is 403 `This action needs a real session.` and an unverified user is 403
`You must verify your account to access this resource.`
| Route | Body | Success |
| --- | --- | --- |
| `POST /v1/auth/email/change` | `{ "new_email": "...", "current_password": "..." }` | 200 `{ "pending_email": "<new>" }` |
| `POST /v1/auth/email/resend` | none | 200 `{ "pending_email": "<new>" }` |
| `DELETE /v1/auth/email/change` | none | 204, no body |
| `POST /v1/auth/email/confirm` | `{ "code": "<raw code>" }` | 200 `{ "email": "<new>" }` |
`users.email` does not change until the link is confirmed, so the old address keeps receiving password-reset links and
the password and username keep working. A request stores `pending_email`, a bcrypt hash of a random code and an
expiration two hours ahead, then mails the raw code as a link to the new address (`verify-new-email`) and a notice to
the old one (`email-change-notice`). A new request or a resend replaces the previous code; cancelling clears it. The
link works once.
Errors are plain text and the code is the whole body: 400 `same_email` (the new address equals the current one,
whatever its case), 403 `wrong_password`, 404 `no_pending_email_change` (resend only), 403
`invalid_email_change_code` (nothing pending, wrong, expired, cancelled or issued to another user) and 409
`email_unavailable` (the address belongs to another user at confirmation time; the pending change is cleared). A body
that is not JSON is 400 with the body-mismatch message, and a failed validation is 400 with the validator text
(`new_email` must be a full address, `current_password` and `code` are required).
A request for an address that another user already holds answers exactly like a success, stores the pending change and
still sends the notice to the old address, but sends no verification mail, so the response never reveals that an account
exists. A failed send is logged without the code and does not change the response. `POST /v1/auth/email/change` and
`POST /v1/auth/email/resend` share one limit of 5 attempts per user per 15 minutes; the sixth is 429 with a
`Retry-After` header. Cancel and confirm are not limited.
Audit actions (category `users`, source `web`): `user.request_email_change`, `user.resend_email_change` and
`user.confirm_email_change` are flagged `security`; `user.cancel_email_change` is not, and cancelling with nothing
pending records nothing. A refused request, resend or confirm records a failed event of the same action, flagged `security`, with a specific reason. No email address is written into an event, and a wrong password records a failed
`user.request_email_change` with the reason `Wrong password.`
## Exporting your own data
`GET /v1/user/me/export` answers a ZIP of the caller's personal data. It needs a real, verified session: no cookie is 401,
an API key is 403 "This action needs a real session." and an unverified account is 403. There is no body and no permission
gate, since it only reads the caller's own data. The success answer is 200 with `Content-Type: application/zip`,
`Cache-Control: no-store` and `Content-Disposition: attachment; filename="renewcms-export-<username>-<YYYY-MM-DD>.zip"`;
the username is lowercased and reduced to `a-z`, `0-9` and `-`, and the date is the UTC day of the export. The archive is
built in memory first, so a failure is a plain text 500 and never a half file.
| File | Content |
| --- | --- |
| `profile.json` | `id`, `username`, `display_name`, `email`, `pending_email`, `role {id, name}`, `is_verified`, `created_at`, `updated_at`, `author` (the linked author profile or `null`), `api_keys [{id, name, prefix, created_at, last_used_at, revoked_at}]` |
| `authored-content.json` | `articles [{id, title, body, slug, site_id, is_online, created_at, updated_at, authors}]` created by the caller (drafts included) or published and crediting their author profile, with `authors [{id, name, slug}]`, and `entries [{id, content_type, data, created_at, updated_at}]` created by the caller; soft-deleted articles are left out |
| `uploaded-media.json` | `images [{id, filename, mime, size, hash, uploaded_at}]`: references only, no file bytes; soft-deleted images are left out |
| `account-activity.json` | `events [{id, created_at, action, category, target, outcome, security, source, ip, user_agent, params}]` where the caller is the actor, without events whose target is another user, an invite or another person's author profile |
The archive never holds the password hash, a verification, reset or email-change code, the token version or an API-key
hash. One export succeeds per user every 15 minutes; a second attempt is 429 "Too many requests. Please try again later."
with a `Retry-After` header in seconds. An export that fails with a 500 does not use the slot. A successful export records
one `user.export_data` audit event (category `users`, not flagged `security`).
The archive is built in memory. At most 2 exports are built at the same time across all users (the constant
`maxConcurrentDataExports` in `api/dependecyInjection.go`); another request waits for a free slot. If the request is
cancelled or times out while waiting, the answer is 503 "Service unavailable" and the user's 15-minute slot is not used.
## Deleting your own account
`DELETE /v1/user/me` deletes the caller's account and personal data. It needs a real, verified session: no cookie is 401,
an API key is 403 "This action needs a real session." and an unverified account is 403. It is not `DELETE /v1/user/{id}`,
which stays the admin action and is unchanged.
Body: `{"current_password": "...", "confirmation": "DELETE"}`. The password is required, and `confirmation` must be exactly
`DELETE` (case-sensitive, no spaces). The checks run in this order:
| Answer | Body | When |
| --- | --- | --- |
| 400 | the validator message, or "The request cannot be processed due to a mismatch in the format of the body." | the body is not JSON, the password is empty or `confirmation` is not `DELETE` |
| 403 | `wrong_password` | the password is not the account's |
| 409 | `last_admin`, with the header `X-Last-Role: Owner` or `X-Last-Role: Admin` | the caller holds the built-in Owner role and no other verified user does, or the built-in Admin role and no other verified user holds Owner or Admin. Other roles, custom ones included, are never blocked. |
| 409 | `account_not_deletable` | the holders of the role changed between the check and the removal; nothing was removed |
| 429 | "Too many requests. Please try again later." with `Retry-After` | more than 5 attempts per user in 15 minutes, counted before any check |
| 500 | "Internal server error" | the removal failed; everything is rolled back |
| 204 | none, and a `Set-Cookie` that expires `jwt` | the account is deleted |
The removal is one atomic operation: the user row, all the user's API keys, the linked author (deleted when no article
credits it, otherwise kept as "Deleted user" with the slug `deleted-user-<author id>`, no bio, avatar, website or links and
no user; the avatar image is deleted too, with its stored file after the commit, unless something else uses it), and the user's past activity events (actor and target names become "Deleted user", the IP address, user agent, `params` and `changes` are emptied, and author events on the user's own profile lose the profile name; the events stay). Articles, entries and images keep the old user id. The current session is revoked, and
one `account-deleted` mail (the site address only, no personal data) is sent to the address the account had; a failed send
is logged and does not change the 204. A successful deletion records one `user.delete_account` event (category `users`,
flagged `security`, actor and target named "Deleted user", no email in the params); a refused attempt records a failed
`user.delete_account` event with the reason `Wrong password.`, `Last Owner.` or `Last administrator.`.
## Users, invites and ownership
A user has exactly one stored role, `role_id`, and nothing else: there is no `role` string any more (the
`users.role` column of older databases stays in place, unused). `RoleRef` is the one role summary shape,
`{ id, name, built_in, locked }`. It appears as `access.role` in `GET /v1/auth/me`, as `role` on user and invite items
(`null` for a user whose role cannot be resolved) and in the responses below. `PublicUser` is exactly `id`, `username`,
`email`, `is_verified`, `created_at`, `updated_at` and `display_name` in every response that includes a user (login,
verify, register, invite accept, `GET /v1/auth/me`); `GET /v1/auth/me` adds `pending_email` (string or `null`), `author` and `access`.
`role_assigned_by` is `{ id, name }` or `null`: who last set the user's role. It is stored as the nullable column
`role_assigned_by_id` on the user (no foreign key, no backfill, existing rows are `NULL`) and the name is never stored: it
is read from the current record of that user at read time (`display_name` when set, else `username`), so a rename shows
at once. When that record is gone the whole object is `null`. It is set by `PUT /v1/user/{id}/role` to the caller (a
request with the user's current role writes nothing), by invite accept to the inviter (`NULL` when the inviter record is
missing), and by the ownership transfer: the new Owner is assigned by the former Owner, whose own value becomes `NULL`.
First-user registration and `POST /v1/role/{id}/reassign` leave it alone. The key is always present on accepted-user
items of `GET /v1/user` (gate `users.view`, unchanged; assigners are resolved from the users already loaded) and on
`access` of `GET /v1/auth/me` (own data, one extra lookup at most). Invite items never carry it, and `PublicUser` and the
login, verify, register and invite-accept bodies do not change.
| Route | Permission | Session only | Purpose |
| --- | --- | --- | --- |
| `GET /v1/user` | `users.view` | no | Users and open invites, newest first. A user is `{ id, kind: "user", username, display_name, email, role, role_assigned_by, status: "accepted", created_at }`; an invite is `{ id, kind: "invite", email, role, status, created_at }`. The roles are read with one `List` call. |
| `PUT /v1/user/{id}/role` | `users.change_role` | yes | Body `{"role_id": N}` (required). Answers 200 with the user item, whose `role_assigned_by` is the caller. |
| `DELETE /v1/user/{id}?expected_role_id=N` | `users.remove` | yes | Removes an accepted user (204, no body). `expected_role_id` is required (a whole number above 0, else 400 `invalid_role`) and must be the id of the role the target still holds: a compare-and-swap (`DeleteIfRole`), 409 `user_role_changed` otherwise. Order of checks: session, permission, id, `expected_role_id`, target (404 `user_not_found`), target is the caller (403 `own_role`), stale role (409), target role locked (403 `role_locked`), target role covered (403 `escalation`), delete. The removed user's cookie sessions and API keys answer 401 afterwards; articles, entries, media, invites and audit events they created stay. Records `user.remove` (category `users`, target the user); a refusal records nothing and a storage failure records it with outcome `failed`. Invites are cancelled with `DELETE /v1/user/invite/{id}`. |
| `POST /v1/user/invite` | `users.invite` | no | Body `{"email", "role_id"}`; `role_id` is optional and 0 or absent means the Writer role. Answers 201 `{ id, kind: "invite", email, status, role, created_at, expires_at }`. |
| `POST /v1/user/invite/{id}/renew` | `users.invite` | no | Renews an expired or pending invite; it keeps its role and the response carries it. |
| `DELETE /v1/user/invite/{id}` | `users.invite` | no | Cancels an invite (204). No coverage is needed: cancelling removes power. |
| `POST /v1/site/transfer-ownership` | `system.transfer_ownership` | yes | Body `{"user_id", "confirm_email"}` (both required). Answers 200 `{ "owner": { id, name }, "former_owner": { id, name, role } }`. |
The no-escalation rule applies to people as it does to roles: the caller must cover (`GrantSet.Covers`) the target's
current role and the new role on a role change, the role of an invite on create and renew. An API key may create and
renew invites, and the check then uses the live role of the key's creator. Nobody can give, take away or invite to the
Owner role: `PUT /v1/user/{id}/role` to or from it, and an invite for it, are 403 `role_locked`; only the transfer moves
the Owner role. Changing the role of your own account is 403 `own_role`. Giving the role a user already holds answers
200 and writes and records nothing. A role change keeps `token_version`, sessions and keys: the next request is decided
by the new grants. An unverified user may be given a role.
The order of checks on `PUT /v1/user/{id}/role` is: session, permission, id, body, target user, target holds a locked
role, `role_id` lookup, new role locked, own account, current role covered, new role covered, same role (no-op), write.
On `POST /v1/user/invite`: permission, rate limiter, body, inviter, role (default Writer), role locked, role covered,
email already has an account, pending invite, create, mail. On `POST /v1/user/invite/{id}/renew`: invite lookup (404),
already accepted (409), invite role covered, renew, mail. On `POST /v1/site/transfer-ownership`: session, permission,
body, target, `confirm_email`, write. Every refusal writes nothing, not even the deletion of an expired invite.
| Status | Body | When |
| --- | --- | --- |
| 409 | the human message | `POST /v1/user/invite` only. "This address already has an account." carries `X-Error-Code: email_has_account`; "There's already a pending invite for this address." carries `X-Error-Code: invite_pending`. |
| 400 | `invalid_role` | `role_id` names no role (user change or invite), or the invite's role no longer exists on renew. |
| 400 | `invalid_transfer` | The transfer target is unknown, yourself, unverified, or not a user (an invite id is never valid). |
| 400 | `confirmation_mismatch` | `confirm_email` differs from the target's email (exact, case-sensitive match). |
| 403 | `role_locked` | The target holds the Owner role, or the role to give is the Owner role. |
| 403 | `own_role` | The target of a role change is the caller's own account. |
| 403 | `escalation` | A role to cover is above the caller's grants; `X-Escalation-Key` names the first offending key. |
| 403 | `missing_permission` | The gate, with `X-Missing-Permission`. A key on a session-only route answers 403 "This action needs a real session." first. |
| 404 | `user_not_found` | Unknown user id on `PUT /v1/user/{id}/role`. |
| 409 | `user_role_changed` | `DELETE /v1/user/{id}` as well: the target's role changed between read and write (a compare-and-swap on the role that was read), or the caller no longer holds the Owner role on a transfer. |
Transferring ownership moves the Owner role to the target and gives the former owner the built-in Admin role in one
transaction; both keep `token_version`, cookies and API keys, so the former owner's next request is decided by the
Admin grants and the new owner's by the Owner grants. Exactly one verified user holds the Owner role afterwards, also
under two simultaneous transfers (one answers 200, the other 409).
Accepting an invite (`POST /v1/auth/invite/accept`) creates the user with the role the invite names, read at accept
time; an invite whose `role_id` is 0 or names a deleted role answers the usual invalid-invite 404 and creates nothing.
Registration creates the first user with the built-in Owner role; when the Owner role is not seeded it answers 500.
A user whose `role_id` is 0 or names no role is denied on every gated route (403 `missing_permission`) and gets 500 on
`GET /v1/auth/me`; it is never promoted.
Activity: `user.change_role` (category `users`, target the user, `changes` holds `{ field: "role", kind: "text", before,
after }` with the role names, params `from` and `to` hold the role ids) and `user.transfer_ownership` (category `users`,
`security: true`, target the new owner, params `from` and `to` hold the two user ids). `invite.create` and
`invite.accept` carry the params `role_id` and `role` (the role name); `invite.renew` is unchanged. A refusal and a
no-op record nothing; a storage failure at the write records the same event with outcome `failed`.
## Content permissions
Articles and the entries of custom content types are checked against the `content.*` permissions of the
caller's role, which is read on every request (a key follows its creator's role).
| Route | Permission | Scope check after the lookup |
| --- | --- | --- |
| `GET /v1/article/`, `GET /v1/article/{id}`, `GET /v1/article/{id}/seo` | public, `content.read` widens what drafts show | online articles, plus drafts when `content.read` is `all`, or the caller's own drafts when it is `own` |
| `POST /v1/article/{id}/seo/check` | `content.read` | the article must be visible, else 404 |
| `POST /v1/article/` | `content.create` | none; `created_by` is the caller and the article is always a draft |
| `PATCH /v1/article/{id}` | `content.update` | `own` needs `created_by` to be the caller, then the article must be readable by the caller, else 404 |
| `DELETE /v1/article/{id}` | `content.delete` | same |
| `PATCH /v1/article/{id}/publish`, `/unpublish` | `content.publish` | same; `PATCH` never changes `is_online` |
| `GET /v1/content-type/{key}/entry`, `GET .../entry/{id}` | `content.read` for `{key}` | `own` lists only the caller's entries (total, page, size and `q` follow) and answers 404 `entry_not_found` for another's entry |
| `POST /v1/content-type/{key}/entry` | `content.create` for `{key}` | `created_by` is the caller |
| `PUT`, `DELETE .../entry/{id}` | `content.update`, `content.delete` for `{key}` | `own` needs `created_by` to be the caller |
Each action reads its own permission: publish does not imply update, update does not imply read. `own`
means `created_by` equals the caller; an unattributed item (`created_by` 0) is owned by nobody. A permission
can also be set for one content type (`content.update:blog`, `content.update:article` for articles); that
row replaces the wildcard for the type, whether it lowers or raises it, and a `none` row denies. Only the
wildcard applies to a type with no row. An id that does not exist is 404 even for a caller at `own`. Article responses expose `created_by` to signed-in callers and API keys only (never to anonymous callers), so a client can tell which rows are its own; see `docs/api/articles.md`.
A refusal is 403 `missing_permission` with `X-Missing-Permission` set to the base key (`content.update`,
never `content.update:blog`). The permission is checked before the id and the body are read, then the scope
after the lookup, and a refused call writes nothing and records no activity event. The verification and
token checks still come first. Creating a content type whose key is `article`, `author`, `site`, `media`
or `user` is 409 `content_type_key_taken`. Owner-only permissions only count on the locked Owner role: the
same key placed by hand on another role is ignored and `GET /v1/auth/me` does not list it.
## Errors ## Errors
Every error is a plain-text body with one sentence; the status is in the HTTP status line. The Every error is a plain-text body with one sentence; the status is in the HTTP status line. The
statuses are 400, 401, 403, 404, 409, 429 and 500. Messages are listed on the Integration page. statuses are 400, 401, 403, 404, 409, 429 and 500. Messages are listed on the Integration page.
A caller whose role lacks the permission a route needs gets 403 with the body `missing_permission` and the
header `X-Missing-Permission` set to the permission key (for example `users.invite`). The role is read on
every request, so an API key follows the current role of its creator.
## Notes ## Notes
- Images in `body` use paths like `/static/uploadedImages/<uuid>.png`. Prefix them with the base URL. - Images in `body` use paths like `/static/uploadedImages/<uuid>.png`. Prefix them with the base URL.
- Browsers can call the API only from origins in the server's CORS setting. - Browsers can call the API only from origins in the server's CORS setting.
+387
View File
@@ -0,0 +1,387 @@
# Article versions, translations, revisions and story move
Contract for `features/article_translation_create.feature`, `features/article_edit_revision.feature` and `features/article_story_lifecycle.feature`. The SPA mocks `/v1` from this page. The article object itself is described in [articles.md](articles.md), the languages of a site in [site-languages.md](site-languages.md).
## Vocabulary
- A **story** groups the language versions of one article inside one site. A **version** is one article row: it has its own id, `lang`, title, slug, content, publication and `created_by`. A story holds at most one live version per language.
- `revision` is the edit counter of a version, starting at `1`, raised by `1` per saved change (see [What raises revision](#what-raises-revision)). An internal content counter is also kept; it is never exposed on a version, only as `source.revision`.
- A **reader** of a version is a caller who passes the existing read rule: an online version is readable by everyone, an offline one by a verified caller whose `content.read` covers it (`all`, or `own` and the caller created it).
- **Missing means no readable version.** Everything an article read says about sibling versions (translations, source, error bodies, headers, counts) is limited to the versions the caller can read. No count, placeholder, total, header or error text ever names, counts or hints at a version the caller cannot read.
## Errors
Errors are plain text. The body is the code (or an existing message) followed by a line feed, and extra data travels in response headers. A refused request changes nothing.
| Header | Set on | Value |
| --- | --- | --- |
| `X-Current-Revision` | `409 revision_conflict` | the current `revision` of the version, an integer |
| `X-Existing-Article-Id` | `409 language_exists` | id of the readable version that already holds the language |
| `X-Conflicting-Articles` | `409 slug_conflict` | ids of the readable versions whose address is taken at the destination, comma separated, in creation order. Absent when none of them is readable |
| `X-Missing-Languages` | `422 language_not_enabled` on a move or on `PATCH site_id` | tags missing or disabled at the destination, comma separated, sorted, readable versions only. Absent when empty |
| `X-Slug-Suggestion` | `409 slug_taken` | first free `<slug>-N` (existing) |
| `X-Missing-Permission` | `403 missing_permission` | the permission key (existing) |
The headers are set on those responses only. Same-origin SPA code reads them directly; cross-origin scripts do not see them (`Access-Control-Expose-Headers` is unchanged).
| Status | Body | Meaning |
| --- | --- | --- |
| 400 | `The request cannot be processed due to a mismatch in the format of the body.` | undecodable or invalid body, missing `copy`, `copy: false` with a source, `if_revision` invalid, an unknown or empty update |
| 400 | `The server expects the ID to be in the format of an unsigned 32-bit integer (uint32).` | invalid id in the path |
| 400 | the validator text (for example `Key: 'PostTranslation.Title' Error:Field validation for 'Title' failed on the 'min' tag`) | `lang` or `title` missing, title shorter than 3 or longer than 200 characters on a create, `site` that is `""` or not a site key on `POST /v1/article/` |
| 400 | `Article title must be between 3 and 200 characters.` | a `PATCH` title outside 3 to 200 runes |
| 400 | `invalid_slug` | a `PATCH` slug that is not a slug |
| 401 | `You must be logged in to access this resource.` | no valid session or key |
| 403 | `missing_permission` | the caller lacks the permission (`X-Missing-Permission`); on `DELETE /v1/story/{story_id}`, a `content.delete` that is not at scope `all` |
| 404 | `Article not found` | the version, or the story, does not exist or the caller cannot read it |
| 404 | `source_unavailable` | the chosen source does not exist or is not readable; the same answer for both |
| 404 | `site_not_found` | `POST /v1/story/{story_id}/move`, or `POST /v1/article/` with `site`, naming an unknown site key |
| 409 | `revision_conflict` | `if_revision` is not the current `revision` (`X-Current-Revision`) |
| 409 | `language_exists` | the language already has a readable version (`X-Existing-Article-Id`) |
| 409 | `language_unavailable` | one neutral answer: the language is disabled on the site (the chosen site on `POST /v1/article/` with `site`), or its version exists but is not readable by the caller, or a concurrent request created it first |
| 409 | `setup_required` | the version has no language yet (`lang` `""`): the site default is not confirmed (the chosen site on `POST /v1/article/` with `site`) |
| 409 | `slug_taken` | a `PATCH` slug used by another article of the same site and language (`X-Slug-Suggestion`) |
| 409 | `slug_conflict` | a move would put an address that already exists at the destination (`X-Conflicting-Articles`) |
| 409 | `story_move_required` | `PATCH site_id` on a version whose story holds several versions |
| 409 | `target_site_deleted` | `POST /v1/article/`: the target site was deleted after it was looked up and before the article was stored; nothing is stored, choose another site and retry. The SPA has no copy for it yet |
| 409 | `story_busy` | the database could not lock the rows in time (lock timeout, deadlock or serialization failure); retry |
| 422 | `invalid_language` | the tag is not a language tag |
| 422 | `unsupported_language` | a valid tag outside the supported list |
| 422 | `language_not_enabled` | the site (the chosen one on `POST /v1/article/` with `site`) has no language row for the tag (creation), or a destination site lacks or has disabled a language of the story (move, `X-Missing-Languages`) |
| 422 | `language_disabled` | publishing an offline version whose language is disabled on its site |
| 422 | `source_other_story` | the source belongs to another story |
## Fields added to an article read
Added to the article object of `GET /v1/article/{id}`, `POST`, `PATCH`, `publish`, `unpublish`, and for `revision` also to each item of `GET /v1/article/`. Every other key keeps its name, value and type.
```json
{
"id": 10,
"lang": "en",
"story_id": 5,
"revision": 3,
"capabilities": ["read", "edit", "publish", "delete", "create_translation"],
"translations": [
{"id": 10, "lang": "en", "title": "Renovation costs", "is_online": true, "language_enabled": true, "excluded_from_public": false, "source_article_id": null, "capabilities": ["read", "edit", "publish", "delete", "create_translation"]},
{"id": 13, "lang": "ar", "title": "Takalif", "is_online": true, "language_enabled": true, "excluded_from_public": false, "source_article_id": 10, "capabilities": ["read", "create_translation"]},
{"id": 12, "lang": "fr", "title": "Couts", "is_online": false, "language_enabled": false, "excluded_from_public": true, "source_article_id": 10, "capabilities": ["read", "edit", "publish", "delete", "create_translation"]}
],
"source": {"article_id": 10, "revision": 4},
"source_unavailable": false,
"missing_langs": ["de"],
"excluded_from_public": false,
"partial_view": false
}
```
- `revision` is a positive integer on every read and write, public reads included.
- `capabilities` lists what the caller may do with this version, always in this order and always starting with `read`: `edit` (`content.update` covers it), `publish` (`content.publish`), `delete` (`content.delete`), `create_translation` (the caller holds `content.create`). An anonymous caller gets `["read"]`.
- `translations` lists the readable versions of the story, the version being read included, with `id`, `lang`, `title`, `is_online`, `language_enabled` and their own `capabilities`. A version without language (`lang` `""`) reports `language_enabled: true`. The order is the default language of the site first, then the other tags in ascending order (`en`, `ar`, `de`, `fr`); a disabled language is still listed with `language_enabled: false`. A single-version article lists itself. An anonymous caller gets `[]`.
- `source` is `{"article_id", "revision"}` when the version was created by copying another version and that source still exists and is readable by the caller, otherwise `null` (a version created empty, a deleted source, an unreadable source, an anonymous caller). `source.revision` is the content revision of the source at the moment of the copy.
- `translations[].excluded_from_public` and `excluded_from_public` (the version being read) are `true` when the language keeps the version off the public language surfaces even once published: the language is disabled on the site, or the version has no language yet (`lang` `""`, the site default is not confirmed). The SPA reads this flag instead of re-deriving it from `language_enabled` and the site languages. A `false` flag says nothing about publication: drafts are off the public surfaces anyway.
- `translations[].source_article_id` is the id of the version this entry tracks when that source is itself listed in `translations` (so readable), otherwise `null`.
- The four keys below are sent to signed-in callers only; an anonymous read has none of them (its shape is unchanged).
- `source_unavailable`: see [Versions the caller cannot read](#versions-the-caller-cannot-read).
- `missing_langs`: the enabled languages of the site without a readable version in the story, default first then by tag, the same rule as the editorial list (`[]` when the caller cannot create, and `[]` for a story whose only versions have no language).
- `excluded_from_public`: the flag above, for the version being read.
- `partial_view`: see [Versions the caller cannot read](#versions-the-caller-cannot-read).
## Versions the caller cannot read
No answer reveals the existence, id, title or language of a version the caller cannot read. Where the editor needs to explain an absence, the API gives one neutral answer that is the same whether the version was deleted or is hidden from the caller, or a flag that depends on the caller's own permissions only.
| Need | Answer | Same for |
| --- | --- | --- |
| The tracked source of a version is gone | `"source": null` and `"source_unavailable": true`. The editor shows "The source isn't available to you" and asks to choose a new source | a deleted source and a source the caller cannot read |
| Creating from a source that is gone | `404 source_unavailable` | a deleted, unknown or unreadable source |
| Deleting a version that others track ("Review tracking will pause") | the dialog names the entries of `translations` whose `source_article_id` is the id being deleted | trackers the caller cannot read are never listed or counted, because `translations` lists readable versions only and their `source_article_id` is never sent |
| Telling the caller that some versions may be out of view ("Versions you can't read aren't listed or counted.") | `partial_view` | `true` whenever the caller's `content.read` is not at scope `all`, whether or not the story holds a version the caller cannot read |
| Deleting the whole article while some versions are out of view | `DELETE /v1/story/{story_id}` needs `content.delete` at scope `all` (`403 missing_permission` otherwise, decided before anything is read), deletes every version, readable or not, and answers `204` | a story with or without hidden versions |
| Moving or editing a story with hidden versions | `article_ids` and the `X-Missing-Languages` and `X-Conflicting-Articles` headers name readable versions only (see [Moving a story](#moving-a-story-post-v1storystory_idmove)) | |
`partial_view` never depends on the stored data, so the note "Versions you can't read aren't listed or counted." shows for such a caller on every story, also when nothing is hidden. Showing it only when a hidden version exists would reveal that version.
## What raises revision
A `PATCH` raises `revision` by exactly `1` when it changes at least one stored value, whatever the number of fields, and not at all when it changes nothing. Publishing and unpublishing never raise it.
| Changed field | `revision` | internal content revision |
| --- | --- | --- |
| `title`, `body`, `excerpt`, `slug`, `cover_image_alt`, `seo_title`, `seo_description`, `social_title`, `social_description` | +1 | +1 |
| `author_ids`, `cover_image_id`, `social_image_id`, `canonical_url`, `noindex`, `seo_dismissed`, `site_id` | +1 | unchanged |
Existing rows start at revision `1`. A story move raises each moved version by `1`.
## Editing: `PATCH /v1/article/{id}`
Verified session or API key with `content.update` on the version (`403 missing_permission` otherwise, checked first) and able to read it (`404 Article not found` otherwise, checked second), so a stale `if_revision` never reveals anything to a caller who cannot edit or read the version.
- `title`: 3 to 200 runes (a 4-byte emoji counts as one). `""`, 2 and 201 runes answer `400 Article title must be between 3 and 200 characters.`; `null` answers `400` with the body-mismatch message. Editing the title never changes the slug and never changes the publication: an online version shows the new title publicly at once.
- `slug`: changed only when sent. `""` regenerates it from the current title. There is no redirect, the old address stops resolving. Unique per site and language: the same slug in two languages of a story is allowed. A slug already used by another article of the same site and language answers `409 slug_taken` with `X-Slug-Suggestion`. Sending the current slug changes nothing.
- `if_revision`: optional integer `>= 1`. A value that is `0`, negative, a string, a fraction or `null` answers `400` (body mismatch). `if_revision` alone is not an update (`400`). When it differs from the current `revision`, nothing is stored and the answer is `409 revision_conflict` with `X-Current-Revision`, even when the rest of the request would change nothing. The compare and the write are one atomic step: of two concurrent saves with the same `if_revision`, one answers `200` and the other `409`. Without `if_revision` the last write wins. To overwrite after a conflict, send `if_revision` equal to the `X-Current-Revision` the conflict showed; if somebody saved in between, the answer is `409` again with the newer revision.
- `site_id` on a version whose story holds several versions the caller can read answers `409 story_move_required` and changes nothing (hidden versions are not counted, so the answer never reveals them). When the caller reads only this version of a larger story, `content.update` is required on every version of the story, readable or not (`403 missing_permission` otherwise, naming no version) and the request runs [the story move](#moving-a-story-post-v1storystory_idmove) rules: every version moves in one transaction, language and slug refusals roll everything back, and headers name readable versions only. The other fields of the same request (`title`, `author_ids`, `slug`, SEO fields) are part of that transaction: a refusal of any of them, an unknown author or an invalid SEO value included, leaves every version on its original site and every `revision` unchanged, and the edited version's `revision` rises by exactly 1 for the whole request. To move a story with several readable versions, use [the story move](#moving-a-story-post-v1storystory_idmove). On a story with one version it moves the version when its language is enabled at the destination (`422 language_not_enabled`, with `X-Missing-Languages`, otherwise); a version without language moves without a language check. The slug rule of the destination still applies (`409 slug_taken`).
- `lang`, `story_id`, `source_article_id` and `copy` in the body are ignored.
The `200` body is the full article object with the new `revision`.
## Publishing
`PATCH /v1/article/{id}/publish` on an offline version whose language is disabled on its site answers `422 language_disabled`. Publishing an already online version is idempotent (`200`, unchanged) even when its language is disabled; a version without language publishes as before. `unpublish` and `PATCH` stay available in a disabled language. Publishing or unpublishing one version never touches its siblings.
## Creating a translation
Two entry points share one implementation: the same result, errors, headers and stored data.
### `POST /v1/article/{id}/translations`
Verified session or API key with `content.create`; the version `{id}` must be readable by the caller.
```json
{"lang": "fr", "title": "Couts de renovation", "copy": true, "source_article_id": 11}
```
| Field | Rule |
| --- | --- |
| `lang` | required; normalized (`FR` is stored as `fr`) |
| `title` | required, 3 to 200 characters |
| `copy` | required boolean (`400` when absent) |
| `source_article_id` | optional, only with `copy: true` (`400` with `copy: false`); default is `{id}`; must be a readable version of the same story |
The new version joins the story of `{id}`, in the same site, as an offline draft created by the caller, with `revision` `1`. The slug is generated from the new title in (site, language) and gets the next free `-N` suffix when taken.
- `copy: true` copies `body`, `excerpt`, `seo_title`, `seo_description`, `social_title`, `social_description`, `cover_image_id`, `cover_image_alt`, `social_image_id` and the authors from the source, and never `slug`, `canonical_url` (empty), `noindex` (false) or `seo_dismissed` (empty). No image or file row is duplicated. The source and its content revision are captured in the same transaction as the copy: the read shows `"source": {"article_id": <source>, "revision": <content revision then>}`.
- `copy: false` starts empty: empty text, no images, `authors` is the creating user's byline, `"source": null`.
Answers `201` with the created article object. Order of checks: permission, path id, body, version readable, `copy` rules, language tag, `setup_required`, source, language configuration. A story deleted in the meantime answers `404 Article not found`. Both entry points leave the stored `lang` normalized.
### `POST /v1/article/` with `story_id` (deprecated)
Deprecated: use `POST /v1/article/{id}/translations`. Both entry points run the same use case and keep working; new clients should not send `story_id`.
```json
{"title": "Couts", "lang": "fr", "story_id": 5, "copy": true, "source_article_id": 10}
```
`story_id` selects the story (`404 Article not found` when it has no readable version, the same answer as a missing story) and the first readable version, oldest first, plays the role of `{id}`. `lang` is then required (`400`). `source_article_id` and `copy` are only valid with `story_id` (`400` otherwise).
### `POST /v1/article/` without `story_id`
It creates a new story with one offline version, on the default site unless the body names a site.
```json
{"title": "Neuf", "lang": "fr", "site": "atelier"}
```
- `site` is optional: the site key. Absent or `null`, the default site is used exactly as before. A present `site` is validated like any site key (`400` with the plain-text body `invalid_site_key` for `""` or `Bad Key!`), then looked up (`404 site_not_found` for an unknown key, a plain text body, nothing stored). A site deleted after that lookup and before the article is stored answers `409 target_site_deleted` (plain text, nothing stored). Every caller who may create articles may create on every site: `content.create` is not scoped to a site, because a role grants each permission at a scope of `none`, `own` or `all` and has no per-site scope (see [Per-site permissions](#per-site-permissions)).
- `lang` is optional. Absent, the version gets the starting language of the chosen site; present, it is normalized and must be an enabled language of the chosen site (`422 invalid_language`, `unsupported_language`, `language_not_enabled`; `409 language_unavailable` when disabled on that site; `409 setup_required` before that site's default language is confirmed). The same tag can therefore be accepted on one site and refused on another.
- The slug is generated from the title and made free within the chosen site and language only.
- `site` with `story_id`, `source_article_id` or `copy` answers `400` with the body mismatch message and stores nothing. `POST /v1/article/{id}/translations` has no `site` field: the translation keeps the site of its source and an unknown `site` key in its body is ignored.
- The response is the created article object (`201`) with the same keys as before; `site_id` is the id of the chosen site. The article is offline, so it is invisible to anonymous reads and public lists, and `GET /v1/article/?site=<key>` lists it for readers.
- `article.create` records `params.site` (the site key) on success; a refusal records one failed event with a plain reason (refusals by validation, `401` and `403` happen before the use case and record nothing).
## Deleting
`DELETE /v1/article/{id}` removes one version (`204`, empty body) and checks `content.delete` per version (`403 missing_permission`). Other versions and their story remain. Deleting the last version of a story removes the story. Nothing in the answer mentions a sibling. A deleted language can be created again in the same story; a language with a deleted version still counts as in use for removing the language from the site.
### Deleting the whole article: `DELETE /v1/story/{story_id}`
Verified session or API key with `content.delete` at scope `all` ("delete permission on every version"). Order of checks: path id (`400` with the uint32 message), `content.delete` held (`403 missing_permission`, `X-Missing-Permission: content.delete`), `content.delete` at scope `all` (`403 missing_permission`, same header; decided from the caller's role only, before any read), at least one readable version (`404 Article not found`, the same answer for an unknown story). Then every version of the story, readable or not, is deleted in one transaction under the locks of its sites, and the story row is removed: `204`, empty body.
- Atomic: a failure answers `500 Failed to delete article` and removes nothing; every version stays.
- Each version is deleted like `DELETE /v1/article/{id}` does it (slug tombstone, soft delete, credits removed), so its slug is free again and its language still counts as in use for removing the language from the site.
- Versions that tracked a deleted version read `source_unavailable: true` afterwards.
- Activity: one `article.delete` per deleted version, oldest first, with `params.lang` and `params.story_id`. A failure records one failed `article.delete` on the oldest readable version; `403` and `404` record nothing.
- A caller whose `content.delete` is at scope `own` deletes versions one by one; deleting the last one removes the story.
### Per-site permissions
Roles grant each permission at scope `none`, `own` or `all` and have no site dimension, so `content.create`, `content.delete` and the other content permissions apply to every site. A per-site permission (for example "may create on Journal only") is not supported; it needs a site scope in the role model first.
## Moving a story: `POST /v1/story/{story_id}/move`
```json
{"site": "atelier"}
```
Verified session or API key. The caller needs `content.update` on every version of the story, readable or not, and must read at least one (`404 Article not found` otherwise, also for an unknown story). `site` is the key of the destination (`400` when absent or empty, `404 site_not_found` when unknown). Answers `200`:
```json
{"story_id": 5, "site": "atelier", "site_id": 2, "article_ids": [10, 12, 11, 13]}
```
`article_ids` lists the readable versions only, oldest first. Every version moves in one transaction: `site_id` changes, slugs, languages, publication, content and authors are unchanged, `revision` of each moved version rises by 1 and its content revision does not. Moving to the current site answers `200` and changes nothing.
Everything is checked inside the transaction, under the locks of both sites, and nothing moves when something fails: every language of every version (readable or not) must be enabled at the destination (`422 language_not_enabled`, `X-Missing-Languages` limited to languages of readable versions, a language disabled at the destination counts as missing, a language disabled at the source does not matter), and no address may exist at the destination in the same language (`409 slug_conflict`, `X-Conflicting-Articles` limited to readable versions). A conflict that appears between the check and the write answers `409 slug_conflict` without the header.
## Editorial list by story: `GET /v1/article/?group=story`
An opt-in shape of the list for a signed-in, verified caller whose role resolves. Without `group` the response keeps the flat envelope `{ items, total, page, size, counts }` of the paginated list, whose `counts` are `all`, `online`, `draft` and `suggestions`. A caller without a valid session, or with an unverified user, who sends `group` gets 400 with the body-mismatch message and nothing is read.
| Parameter | Meaning |
| --- | --- |
| `group` | Only `story`. `group=`, any other value, or `group` from a public caller is 400. |
| `lang` | A supported language tag, normalized like the language of a version (`fr`, `pt-br` becomes `pt-BR`). Empty, malformed or unsupported is 400. Also narrows the flat list (`items`, `total`, `counts.all`, `counts.online`, `counts.draft`). Disabled languages can be selected. |
| `tab` | `all` (default) or `missing`. `review`, an empty value, any other value, and `missing` without `group=story` are 400. |
| `author` | A byline id, an integer of at least 1; anything else is 400. Also narrows the flat list. |
| `page`, `size`, `q`, `status`, `site`, `seo`, `sort` | Same values, defaults and validation as the flat list. |
Only versions the caller can read count: they are titled, credited, listed in `coverage`, searched and counted. A hidden version never appears, and a story whose versions are all hidden has no row.
**Rows.** With no `lang` a row is a story: `total` counts stories. With `lang` a row is the version of that language (`tab=all`), and the whole story's `coverage`, `story_authors` and `missing_langs` still ride on the row. With `tab=missing` rows are stories again: `lang=fr` lists the stories on a site that enables `fr` and that have a readable version with a language but none in `fr`; without `lang` it lists the stories that lack at least one enabled language, and a caller who cannot create (no `content.create`) gets `total` 0. A story whose readable versions all lack a language (`lang` `""`) is never listed as missing a language. A mixed story (a version without language plus at least one version with a language) is listed under Missing like any other: the version without language fills no language. A version of the story must satisfy `status`, `author`, `q` and `seo` together to make the story match; `q` ignores case and accents.
**Item.** The article list item of the representative version (the one in `lang`, otherwise the site default language version, otherwise the first readable one by language tag), plus:
| Field | Type | Meaning |
| --- | --- | --- |
| `story_updated_at` | RFC 3339 | The latest `updated_at` among the readable versions of the story |
| `story_authors` | array of bylines | The union of the bylines of the readable versions, without duplicates |
| `coverage` | array | One entry per readable version, in the order of `translations` (default language, other enabled tags, disabled tags), with the same keys as a `translations` entry: `{ id, lang, title, is_online, language_enabled, excluded_from_public, source_article_id, capabilities }` |
| `missing_langs` | array of tags | Enabled languages without a readable version, default first then by tag; `[]` when the caller cannot create or when no readable version has a language |
| `excluded_from_public` | boolean | The flag of the representative version (see [Fields added to an article read](#fields-added-to-an-article-read)) |
| `capabilities` | array | The capabilities of the representative version |
**Sort.** The whitelist is the flat one. `updated_at` uses the latest readable version of the story, `created_at` the earliest, `title` and `status` the representative; with `lang` the version itself. Ties end with `story_id` descending.
**Counts.** `{ all, online, draft, suggestions, missing }`. They follow `lang`, `q`, `author`, `seo` and `site` but never `status` or `tab`, and count the unit of the mode (stories, or versions of the selected language). `online` and `draft` count the units with a readable online or draft version. `missing` is the `total` the not-in view would give under the same filters (0 without `lang` for a caller who cannot create). `suggestions` is the number of stories with a readable version whose `seo_status` is `suggestions`, ignoring every parameter.
`seo_status`, `seo_suggestions`, the `seo` filter and `counts.suggestions` read the stored SEO status of each version (see [SEO status and suggestions](articles.md#seo-status-and-suggestions)); no request reads the bodies of the visible versions to compute them.
A repository failure at any step, counts included, answers 500 `Failed to retrieve articles`.
## Mock-ready examples
Statuses of the new and changed calls. Bodies are plain text unless shown as JSON; headers listed are the only extra ones.
| Call | Status | Headers | Body |
| --- | --- | --- | --- |
| `GET /v1/article/10` (see above) | 200 | | article object with `revision`, `capabilities`, `translations`, `source` |
| `POST /v1/article/10/translations` `{"lang":"fr","title":"Couts","copy":true}` | 201 | | article object, `lang` `"fr"`, `"is_online": false`, `"revision": 1`, `"source": {"article_id": 10, "revision": 4}` |
| `DELETE /v1/article/12` | 204 | | empty |
| `DELETE /v1/story/5` by the owner | 204 | | empty |
| `DELETE /v1/story/5` by a user holding `content.delete` at `own` | 403 | `X-Missing-Permission: content.delete` | `missing_permission` |
| `DELETE /v1/story/5` when the database fails | 500 | | `Failed to delete article` |
| `POST /v1/story/5/move` `{"site":"atelier"}` | 200 | | `{"story_id":5,"site":"atelier","site_id":2,"article_ids":[10,12,11,13]}` |
| `POST /v1/article/10/translations` `{"lang":"fr","title":"Couts"}` | 400 | | `The request cannot be processed due to a mismatch in the format of the body.` |
| `PATCH /v1/article/10` `{"title":"ab"}` | 400 | | `Article title must be between 3 and 200 characters.` |
| `POST /v1/article/10/translations` with a cookie of an anonymous client | 401 | | `You must be logged in to access this resource.` |
| `POST /v1/story/5/move` by a user holding `content.update` at `own` | 403 | `X-Missing-Permission: content.update` | `missing_permission` |
| `POST /v1/article/9999/translations` | 404 | | `Article not found` |
| `POST /v1/article/10/translations` with `"source_article_id":9999` | 404 | | `source_unavailable` |
| `POST /v1/story/5/move` `{"site":"nowhere"}` | 404 | | `site_not_found` |
| `PATCH /v1/article/10` `{"body":"x","if_revision":3}` after somebody saved | 409 | `X-Current-Revision: 4` | `revision_conflict` |
| `POST /v1/article/10/translations` `{"lang":"de","title":"Kosten","copy":true}` | 409 | `X-Existing-Article-Id: 11` | `language_exists` |
| `POST /v1/article/10/translations` `{"lang":"fr","title":"Couts","copy":true}` with fr disabled, unreadable or raced | 409 | none | `language_unavailable` |
| `POST /v1/article/30/translations` on an article without language | 409 | | `setup_required` |
| `PATCH /v1/article/10` `{"slug":"taken-en"}` | 409 | `X-Slug-Suggestion: taken-en-2` | `slug_taken` |
| `POST /v1/story/5/move` `{"site":"atelier"}` with an address taken at the destination | 409 | `X-Conflicting-Articles: 12` | `slug_conflict` |
| `PATCH /v1/article/10` `{"site_id":2}` on a story with several readable versions | 409 | | `story_move_required` |
| `POST /v1/article/10/translations` `{"lang":"pt","title":"Custos","copy":true}` with no `pt` row | 422 | | `language_not_enabled` |
| `POST /v1/story/5/move` `{"site":"atelier"}` with no `ar` at the destination | 422 | `X-Missing-Languages: ar` | `language_not_enabled` |
| `PATCH /v1/article/15/publish` with `es` disabled | 422 | | `language_disabled` |
| `POST /v1/article/10/translations` `{"lang":"xx","title":"Couts","copy":true}` | 422 | | `unsupported_language` |
| `POST /v1/article/10/translations` `{"lang":"english","title":"Couts","copy":true}` | 422 | | `invalid_language` |
| `POST /v1/article/10/translations` with `"source_article_id":20` of another story | 422 | | `source_other_story` |
## Activity
No new action code. The existing events carry `params.lang` (the language of the version, omitted for a version without language): `article.create`, `article.edit`, `article.publish`, `article.unpublish`, `article.delete`. A translation creation records `article.create` on the new version with `params.lang`, `params.story_id` and `params.source_article_id` (only when copied). A story move records one `article.edit` per moved version, with a `site` change (site names before and after) and `params.lang`; moving to the current site records nothing. A refused creation or move records one failed event with a plain reason that names no version; refusals answered `404` are not recorded.
## Public language routes
Contract for `features/localization_public_api_and_surfaces.feature`. Both routes are open to everyone: a `jwt` cookie or an API key is ignored, so a draft is never returned, whoever asks. They sit under `/v1/public` and are read only.
They are rate limited per client address together with `GET /v1/site/{key}/sitemap`: 120 requests per minute in total, the same budget an API key gets on the authenticated routes. The client address is the connection address, or `X-Real-IP` when the connection comes from one of `TRUSTED_PROXIES`. Over the budget the answer is `429` with `Retry-After` (seconds) and the body `Too many requests. Please try again later.`
A version is **published** when `is_online` is true, and **eligible** when it is published and its language is enabled on the site. A disabled language stays readable on both routes; only the alternates leave it out.
### Exact lookup: `GET /v1/public/site/{key}/lang/{lang}/article/{slug}`
Matches the site key, the language and the slug, and nothing else. It never falls back to another language, never follows an old slug and creates no redirect.
- `lang` is normalized (`FR` reads `fr`, `pt-br` reads `pt-BR`). A value that is not a language tag (`e`, `pt_BR`) is `400 invalid_language`; a valid tag with no version, or outside the supported list, is `404 article_not_found`.
- `format` behaves as on `GET /v1/article/{id}`: `markdown` (default), `html` or `json`; anything else is `400` with `The format must be one of: markdown, html, json.`
- An unassigned article (`lang` `""`), a draft, a soft-deleted version and a version of another site or language are all `404 article_not_found`, with the same body.
- Answers `200` with the body of an anonymous `GET /v1/article/{id}` (same keys and values) and one more key, `alternates`.
```json
{
"id": 12,
"lang": "fr",
"story_id": 5,
"slug": "comment-nous-chiffrons-une-renovation",
"is_online": true,
"alternates": [
{"id": 10, "lang": "en", "story_id": 5, "slug": "how-we-price-a-bathroom-renovation", "url": "https://journal.example.com/en/how-we-price-a-bathroom-renovation"},
{"id": 11, "lang": "de", "story_id": 5, "slug": "so-kalkulieren-wir-eine-badsanierung", "url": "https://journal.example.com/de/so-kalkulieren-wir-eine-badsanierung"}
]
}
```
`alternates` lists the other eligible versions of the story: the served version, drafts and versions in a disabled language are left out, and nothing in the response names them. The order is the default language of the site first, then the other tags in ascending order. Each alternate has exactly `id`, `lang`, `story_id`, `slug` and `url`. `url` is the site Public URL pattern filled with the tag and the slug, or `null` when the site has no pattern. A story with one version answers `[]`.
### Story resolution: `GET /v1/public/site/{key}/story/{story_id}`
Resolves one story of the site, optionally with an explicit fallback to the default language. No other language is ever tried.
| Query | Rule |
| --- | --- |
| `lang` | optional. Absent, the site default language is requested. A malformed tag is `400 invalid_language` |
| `fallback` | optional, only the value `default`. When the requested language has no published version, serve the published default-language version instead. Any other value, an empty one included, is `400` with the body-mismatch message |
| `format` | as on the exact lookup |
The `200` body is the exact lookup body plus `requested_lang` (the language that was asked for, or the default when `lang` is absent) and `fallback` (`true` only when the default-language version replaced the requested one). `lang` is the language of the version served.
| Request | Answer |
| --- | --- |
| `?lang=fr`, a published `fr` version exists | the `fr` version, `fallback` false |
| `?lang=fr`, none, no `fallback` | `404 language_not_available` |
| `?lang=fr&fallback=default`, `fr` missing or unpublished, `en` published | the `en` version, `requested_lang` `fr`, `fallback` true |
| `?lang=fr&fallback=default`, neither published | `404 language_not_available` (a third language is never returned) |
| `?lang=en&fallback=default`, `en` unpublished | `404 language_not_available` |
| no `lang` | the default-language version, `requested_lang` the default |
| no `lang`, the site has no confirmed default language | `404 language_not_available` |
| a story of another site, an unknown story, a story with no published version | `404 language_not_available` |
Changing the default language of a site changes only the requests that omit `lang`.
### Errors
Plain text, the body is the code followed by a line feed. `language_disabled` is not returned by these routes.
| Status | Body | When |
| --- | --- | --- |
| 400 | `invalid_language` | `lang` is not a language tag |
| 400 | `The request cannot be processed due to a mismatch in the format of the body.` | `fallback` is not `default` |
| 400 | `The server expects the ID to be in the format of an unsigned 32-bit integer (uint32).` | `story_id` is not an unsigned integer |
| 400 | `The format must be one of: markdown, html, json.` | invalid `format` |
| 404 | `article_not_found` | exact lookup: no published version for the site, language and slug |
| 404 | `language_not_available` | story resolution: no version can be served under the rules above |
| 404 | `site_not_found` | unknown site key |
| 429 | `Too many requests. Please try again later.` | more than 120 requests in a minute from one client address on the public routes and the sitemap together (`Retry-After` in seconds) |
| 500 | `Internal server error` | a repository failure |
## Resolved SEO and sitemap, language aware
`GET /v1/article/{id}/seo` keeps its keys and adds `lang`, `alternates` (same shape and order as the public alternates), `og.locale_alternates` and `fallbacks.site_text_skipped`. Every other key keeps its name and type. An unassigned article (`lang` `""`) answers `lang` `""`, `alternates` `[]` and `og.locale_alternates` `[]`, with the legacy canonical and the raw site locale.
**Canonical.** `canonical_url` and `og.url` are, in order: the version `canonical_url` override (`fallbacks.canonical` `canonical_url`); the site `public_url_pattern` with `{lang}` and `{slug}` filled (`pattern`); the legacy `base_url/slug` (`site`), when the site has no pattern or the article has no language. A region tag is kept as written (`/pt-BR/reforma`). `json_ld.mainEntityOfPage.@id` equals `canonical_url`. Saving a pattern changes no override and no article.
**og:locale**, first match wins, never invented:
1. the explicit `social_locale` of the language row;
2. the tag already has a region (`pt-BR` gives `pt_BR`);
3. `Site.Locale` has the same language part and a region (`en-GB` with `en` gives `en_GB`);
4. otherwise `""`, and `og.locale_alternates` is `[]`.
`og.locale_alternates` lists the social locales of the other eligible versions that resolve one, in the order of the alternates. `GET /v1/site/{key}/languages` reports rule 3 as `social_locale_state` `derived` (`not_set` when `Site.Locale` is bare such as `en`).
**Fallbacks in the language of the version.** The title and description chains are unchanged except for the site text: `default_description` is treated as written in the current default language of the site, so it is used only by an unassigned article or a version in that language. For any other language the description stays empty, `fallbacks.description` is `none` and `fallbacks.site_text_skipped` is `true`. Changing the default language changes which versions may use the site text. `title_template`, `site_name` and the image chain stay shared; `cover_image_alt` stays per version.
**Sitemap.** `GET /v1/site/{key}/sitemap` lists every eligible version once (published, language enabled; unassigned published articles keep their legacy entry). Each item is `{url, modified_at, noindex, lang}`; `url` is the localized address when the site has a pattern, otherwise `base_url/slug`. `X-Total-Count` counts the listed items. The route shares the rate limit of the public language routes.
**SEO check and status.** `POST /v1/article/{id}/seo/check`, the stored `seo_status` of the lists and the `seo` filter apply the same language rule as the resolved description: the site `default_description` can fill the description (and so avoid `desc_short` or raise `desc_long`) only for a version in the current default language of the site or without language.
## Media usage
`GET /v1/media/{id}/usage` article items gain `story_id` and `lang` (`""` for an unassigned article, whose `story_id` is the stored value). There is one article item per version, ordered by id; author, site and entry items carry neither key. `used_in` on `GET /v1/media/` counts a story once, so an image used by three versions of one story is one use. An unassigned article is its own group.
+24 -10
View File
@@ -1,8 +1,10 @@
# Reading articles # Reading articles
Versions, translations, `revision`, `if_revision`, capabilities and the story move: [article-localization.md](article-localization.md).
Every route that returns an article accepts the optional `format` query parameter and returns the article body in that format. Articles are stored as HTML (Tiptap output). Storage and the request bodies of `POST /v1/article/` and `PATCH /v1/article/{id}` stay HTML. Every route that returns an article accepts the optional `format` query parameter and returns the article body in that format. Articles are stored as HTML (Tiptap output). Storage and the request bodies of `POST /v1/article/` and `PATCH /v1/article/{id}` stay HTML.
`PATCH /v1/article/{id}` takes `body`, `site_id`, `author_ids` (the whole ordered list of author ids, see `docs/api.md`) and the SEO fields listed below, and nothing else. The request must contain at least one of them, and `null` answers `400` except for `cover_image_id` and `social_image_id`. Behaviour change: `{}` and `{"body": null}` used to set an empty body and now answer `400`; send `{"body": ""}` to empty a body. `PATCH /v1/article/{id}` takes `title`, `body`, `site_id`, `author_ids` (the whole ordered list of author ids, see `docs/api.md`), the SEO fields listed below and the optional `if_revision`, and nothing else. The request must contain at least one of them (`if_revision` alone is not an update), and `null` answers `400` except for `cover_image_id` and `social_image_id`. Behaviour change: `{}` and `{"body": null}` used to set an empty body and now answer `400`; send `{"body": ""}` to empty a body.
## Routes that honour `format` ## Routes that honour `format`
@@ -13,7 +15,7 @@ Every route that returns an article accepts the optional `format` query paramete
- `PATCH /v1/article/{id}/publish` - `PATCH /v1/article/{id}/publish`
- `PATCH /v1/article/{id}/unpublish` - `PATCH /v1/article/{id}/unpublish`
Visibility is unchanged: anonymous and unverified callers only see online articles, and an offline article answers `404 Article not found`. Anonymous and unverified callers only see online articles, and an offline article answers `404 Article not found`. A verified caller also sees the drafts that `content.read` covers: every draft at `all`, only their own at `own`, and none without the permission. The `all`, `online` and `draft` counts follow the same visible set.
## Pagination, search and counts ## Pagination, search and counts
@@ -42,7 +44,7 @@ Visibility is unchanged: anonymous and unverified callers only see online articl
- `items` is `[]` when empty, never `null`. Each item is the article object below. - `items` is `[]` when empty, never `null`. Each item is the article object below.
- Items follow `sort` (default `updated_at:desc`) across the whole list before paging. `title` ignores case, `status` orders on online state (`status:asc` puts drafts first), and every ordering ends with `id` descending so pages never overlap. - Items follow `sort` (default `updated_at:desc`) across the whole list before paging. `title` ignores case, `status` orders on online state (`status:asc` puts drafts first), and every ordering ends with `id` descending so pages never overlap.
- `total` is the number of visible articles matching `q` and `status`, before paging. `page` and `size` echo the values applied. - `total` is the number of visible articles matching `q` and `status`, before paging. `page` and `size` echo the values applied.
- `counts` ignores `q`, `status`, `site`, `seo`, `sort`, `page` and `size`, so tab counts do not move while searching. `suggestions` is the number of visible articles whose `seo_status` is `suggestions` (hidden and ready articles and dismissed codes are not counted); it equals the `total` of `?seo=suggestions` sent with no other filter by the same caller. For anonymous and unverified callers `all` equals `online` and `draft` is `0`, and `status=draft` answers `items: []` and `total: 0`. - `counts` ignores `q`, `status`, `site`, `seo`, `sort`, `page` and `size` (and `suggestions` also ignores `lang` and `author`), so tab counts do not move while searching. `suggestions` is the number of visible articles whose `seo_status` is `suggestions` (hidden and ready articles and dismissed codes are not counted); it equals the `total` of `?seo=suggestions` sent with no other filter by the same caller. For anonymous and unverified callers `all` equals `online` and `draft` is `0`, and `status=draft` answers `items: []` and `total: 0`.
- Each item also carries `seo_status` and `seo_suggestions` (see [SEO status and suggestions](#seo-status-and-suggestions)). `seo` filters on the status before paging, so `total` follows it while `counts` do not. - Each item also carries `seo_status` and `seo_suggestions` (see [SEO status and suggestions](#seo-status-and-suggestions)). `seo` filters on the status before paging, so `total` follows it while `counts` do not.
- A page beyond the last answers `200` with `items: []` and the real `total`. - A page beyond the last answers `200` with `items: []` and the real `total`.
- An invalid `page`, `size`, `status`, `sort` or an over-long `q` answers `400` with the plain-text message `The request cannot be processed due to a mismatch in the format of the body.` An invalid `format` is reported first. - An invalid `page`, `size`, `status`, `sort` or an over-long `q` answers `400` with the plain-text message `The request cannot be processed due to a mismatch in the format of the body.` An invalid `format` is reported first.
@@ -72,6 +74,7 @@ Breaking change: the default used to be HTML. Clients that need HTML must send `
"body_format": "markdown", "body_format": "markdown",
"is_online": true, "is_online": true,
"site_id": 1, "site_id": 1,
"created_by": 1,
"authors": [], "authors": [],
"slug": "backyard-renovation-update", "slug": "backyard-renovation-update",
"excerpt": "", "excerpt": "",
@@ -86,10 +89,16 @@ Breaking change: the default used to be HTML. Clients that need HTML must send `
"noindex": false, "noindex": false,
"seo_dismissed": [], "seo_dismissed": [],
"created_at": "2026-03-12T09:14:00Z", "created_at": "2026-03-12T09:14:00Z",
"updated_at": "2026-09-10T07:00:00Z" "updated_at": "2026-09-10T07:00:00Z",
"lang": "fr-CA",
"story_id": 5
} }
``` ```
`lang` is the full BCP 47 language tag of the article (`""` while the site default language is not confirmed) and `story_id` is the story the article belongs to. Both are present on every article object (list items, reads, create and update responses, public reads) as additive keys, and every other key is unchanged. They are read-only on `PATCH`, where `lang` and `story_id` are ignored. `POST /v1/article/` takes `title`, `body`, and optionally `lang`, `site` (a site key; the default site when absent or `null`), `story_id`, `source_article_id` and `copy` only as described in [article-localization.md](article-localization.md), which also documents `revision`, `capabilities`, `translations` and `source`, the additive keys of every article read. Supported tags: `en`, `en-GB`, `en-US`, `fr`, `fr-CA`, `pt`, `pt-BR`, `es`, `de`, `ar`. Existing articles each get their own story and `lang` `""` until the site default is confirmed.
`created_by` is the id of the user who created the article (`0` when it is attributed to nobody). It is present on every article object (list, read, create and update responses) only when the caller is signed in with a verified session or authenticates with an API key; the key acts as its creator. Anonymous callers, and unverified or stale sessions, get the same object without the field. The SPA reads it to decide which rows a role limited to `own` can edit, delete or publish.
Every single-article read (`GET /v1/article/{id}`, `POST`, `PATCH`, `publish`, `unpublish`) carries the twelve SEO fields. Each item of `GET /v1/article/` carries `slug` and `excerpt` only, and none of the other ten. Every single-article read (`GET /v1/article/{id}`, `POST`, `PATCH`, `publish`, `unpublish`) carries the twelve SEO fields. Each item of `GET /v1/article/` carries `slug` and `excerpt` only, and none of the other ten.
## SEO fields ## SEO fields
@@ -113,7 +122,7 @@ Limits are counted in characters (runes), not bytes. Absent fields are untouched
### The slug ### The slug
A slug is unique per site (`site_id`, `slug`), never globally. At creation it is generated from the title: lowercase, accents folded, every run of other characters becomes one dash, dashes trimmed, cut to 100 characters without a trailing dash, and `article` when no letter or digit is left. A slug already used on the site gets `-2`, `-3`... silently, the base being truncated so the result fits 100 characters. The same rule backfills existing articles on the first start after the upgrade, in id order within each site. A slug is unique per site and language (`site_id`, `lang`, `slug`), never globally; unassigned articles (`lang` `""`) share the empty language, so they keep the per-site rule. At creation it is generated from the title: lowercase, accents folded, every run of other characters becomes one dash, dashes trimmed, cut to 100 characters without a trailing dash, and `article` when no letter or digit is left. A slug already used on the site gets `-2`, `-3`... silently, the base being truncated so the result fits 100 characters. The same rule backfills existing articles on the first start after the upgrade, in id order within each site.
Editing a slug that another article of the target site already uses (the new site when `site_id` is sent in the same request; moving an article also re-checks its current slug there) answers `409` with the plain-text body `slug_taken`, and the response header `X-Slug-Suggestion` holds the first free `<slug>-N` from 2 on that site, fitting 100 characters. `X-Slug-Suggestion` is set on this `409` only and on no other response. A request with `slug: ""` that regenerates onto another article's slug is refused the same way and never suffixed silently. Re-sending an article's own slug is not a conflict. A refused request changes nothing. Editing a slug that another article of the target site already uses (the new site when `site_id` is sent in the same request; moving an article also re-checks its current slug there) answers `409` with the plain-text body `slug_taken`, and the response header `X-Slug-Suggestion` holds the first free `<slug>-N` from 2 on that site, fitting 100 characters. `X-Slug-Suggestion` is set on this `409` only and on no other response. A request with `slug: ""` that regenerates onto another article's slug is refused the same way and never suffixed silently. Re-sending an article's own slug is not a conflict. A refused request changes nothing.
@@ -121,22 +130,22 @@ Publishing, unpublishing and `noindex` never change a slug. A deleted article fr
## Resolved SEO object ## Resolved SEO object
`GET /v1/article/{id}/seo` answers the data a frontend renders in its `<head>`. Online articles are public; a draft needs a verified session or API key and is otherwise `404 Article not found`. The query is ignored (no `format`). Keys: `GET /v1/article/{id}/seo` answers the data a frontend renders in its `<head>`. Online articles are public; a draft needs a verified session or API key whose role may read it (see [Content permissions](../api.md#content-permissions)) and is otherwise `404 Article not found`. The query is ignored (no `format`). Keys:
`title`, `description`, `canonical_url`, `robots`, `og` (`type`, `title`, `description`, `image`, `image_alt`, `url`, `site_name`, `locale`), `twitter` (`card`, `title`, `description`, `image`, `image_alt`), `image` (`url`, `alt`, `source`), `authors` (`name`, `url`, `same_as`), `published_at`, `modified_at`, `fallbacks` and `json_ld` (a ready schema.org `Article`). `title`, `description`, `canonical_url`, `robots`, `og` (`type`, `title`, `description`, `image`, `image_alt`, `url`, `site_name`, `locale`, `locale_alternates`), `twitter` (`card`, `title`, `description`, `image`, `image_alt`), `image` (`url`, `alt`, `source`), `authors` (`name`, `url`, `same_as`), `published_at`, `modified_at`, `fallbacks` (`title`, `description`, `image`, `canonical`, `site_text_skipped`), `json_ld` (a ready schema.org `Article`), `lang` and `alternates`. The language rules (canonical from the Public URL pattern, `og:locale` order, site text only in the default language) are in [article-localization.md](article-localization.md#resolved-seo-and-sitemap-language-aware).
The fallback chain, first non-empty wins: The fallback chain, first non-empty wins:
| Output | Chain | `fallbacks` value | | Output | Chain | `fallbacks` value |
| --- | --- | --- | | --- | --- | --- |
| `title` | `seo_title`, then the article title, then the site `title_template` (`%title%`, `%site%` replaced by `site_name`, result trimmed) | `seo_title`, `title` | | `title` | `seo_title`, then the article title, then the site `title_template` (`%title%`, `%site%` replaced by `site_name`, result trimmed) | `seo_title`, `title` |
| `description` | `seo_description`, `excerpt`, the first sentence of the body (tags removed), the site `default_description` | `seo_description`, `excerpt`, `body`, `site`, `none` | | `description` | `seo_description`, `excerpt`, the first sentence of the body (tags removed), the site `default_description` (only for a version in the default language or without language) | `seo_description`, `excerpt`, `body`, `site`, `none` |
| `image` | `social_image_id`, `cover_image_id` (with `cover_image_alt`), the site `default_social_image_id`; `url` is the site `base_url` plus the image path, `""` and `none` when there is none | `social`, `cover`, `site`, `none` | | `image` | `social_image_id`, `cover_image_id` (with `cover_image_alt`), the site `default_social_image_id`; `url` is the site `base_url` plus the image path, `""` and `none` when there is none | `social`, `cover`, `site`, `none` |
| `canonical_url` | `canonical_url`, then site `base_url` + `/` + `slug` | `canonical_url`, `site` | | `canonical_url` | `canonical_url`, then the site `public_url_pattern` filled with `lang` and `slug`, then site `base_url` + `/` + `slug` (no pattern, or no language) | `canonical_url`, `pattern`, `site` |
| `robots` | `noindex, nofollow` when `noindex` is true, otherwise from the site `default_robots` (`index, follow` or `noindex, nofollow`) | none | | `robots` | `noindex, nofollow` when `noindex` is true, otherwise from the site `default_robots` (`index, follow` or `noindex, nofollow`) | none |
| `og` and `twitter` title and description | `social_title` and `social_description`, then the resolved values | none | | `og` and `twitter` title and description | `social_title` and `social_description`, then the resolved values | none |
`og.type` is `article`, `og.locale` is the site locale (`""` when none), `twitter.card` is `summary_large_image` with an image and `summary` without. `published_at` is the creation time of an online article and `null` for a draft; `modified_at` is `updated_at`. `authors[].url` is the author website (`""` when none) and `same_as` lists the social link URLs only. `json_ld.headline` is the meta title without the site template, and `author`, `image` and `datePublished` are left out when empty. `og.type` is `article`, `og.locale` is the explicit social locale of the language, else the region of the tag, else the region of the site locale with the same language, else `""`; an article without language keeps the raw site locale, `twitter.card` is `summary_large_image` with an image and `summary` without. `published_at` is the creation time of an online article and `null` for a draft; `modified_at` is `updated_at`. `authors[].url` is the author website (`""` when none) and `same_as` lists the social link URLs only. `json_ld.headline` is the meta title without the site template, and `author`, `image` and `datePublished` are left out when empty.
## SEO status and suggestions ## SEO status and suggestions
@@ -158,6 +167,10 @@ The fallback chain, first non-empty wins:
Suggestions come in that order. Codes in `seo_dismissed` are never reported or counted. The status is `hidden` when `noindex` is true, else `suggestions` when at least one suggestion remains, else `ready`. The list items carry `seo_status` and `seo_suggestions` (the count, also for a hidden article). Suggestions come in that order. Codes in `seo_dismissed` are never reported or counted. The status is `hidden` when `noindex` is true, else `suggestions` when at least one suggestion remains, else `ready`. The list items carry `seo_status` and `seo_suggestions` (the count, also for a hidden article).
The resolved description uses the site `default_description` only for a version in the current default language of its site or without language, so `desc_short` and `desc_long` follow the language of the version, in the check and in the lists alike.
**Stored status.** Each version stores its `seo_status` and `seo_suggestions`. Every write that can change them clears the stored value in the same statement: an edit of the version (title, body, slug, SEO fields, authors, site), a cover or social image deleted, restored or merged, a credited author deleted, a move to another site (story move or site deletion with reassignment), a language assigned by the setup, a change of the site `default_description`, and a change of the site default language. The lists recompute the cleared versions (and only those) before answering, and the server recomputes them at startup, so `seo_status`, `?seo=` and `counts.suggestions` always reflect the current data without reading every visible body per request. A value computed from data that changed in the meantime is never stored.
## Markdown output ## Markdown output
Headings, bold, italic, links, bullet and ordered lists, blockquotes, fenced code blocks, rules, images and inline code are converted. Anything else is reduced to its text. `script` and `style` content is removed, and the source HTML is never passed through; the only HTML in the output is the alignment wrapper described below. List indentation attributes are dropped. Links with a scheme other than http, https, mailto or tel are reduced to their text. Characters that markdown would read as formatting (`*`, `_`, `` ` ``, `[`, `]`, `<`, `\`) and line starts that would read as a heading, list, quote or rule (`#`, `-`, `+`, `>`, `1.`) are backslash-escaped, so plain text stays plain text. A line break becomes a backslash followed by a newline. Headings, bold, italic, links, bullet and ordered lists, blockquotes, fenced code blocks, rules, images and inline code are converted. Anything else is reduced to its text. `script` and `style` content is removed, and the source HTML is never passed through; the only HTML in the output is the alignment wrapper described below. List indentation attributes are dropped. Links with a scheme other than http, https, mailto or tel are reduced to their text. Characters that markdown would read as formatting (`*`, `_`, `` ` ``, `[`, `]`, `<`, `\`) and line starts that would read as a heading, list, quote or rule (`#`, `-`, `+`, `>`, `1.`) are backslash-escaped, so plain text stays plain text. A line break becomes a backslash followed by a newline.
@@ -211,6 +224,7 @@ Example for `<h2>Plan</h2><p>Replace the <strong>old</strong> deck.</p>`:
| --- | --- | | --- | --- |
| `400` | `The server expects the ID to be in the format of an unsigned 32-bit integer (uint32).` for an invalid id | | `400` | `The server expects the ID to be in the format of an unsigned 32-bit integer (uint32).` for an invalid id |
| `400` | `The format must be one of: markdown, html, json.` for an unsupported format | | `400` | `The format must be one of: markdown, html, json.` for an unsupported format |
| `400` | `invalid_site_key` for a `site` of `POST /v1/article/` that is not a valid site key |
| `400` | `invalid_slug`, `image_not_found` or the validator text for an over-long SEO field, `cover_image_id: 0` or an unknown `seo_dismissed` code | | `400` | `invalid_slug`, `image_not_found` or the validator text for an over-long SEO field, `cover_image_id: 0` or an unknown `seo_dismissed` code |
| `404` | `Article not found` | | `404` | `Article not found` |
| `409` | `slug_taken`, with the header `X-Slug-Suggestion: <first free slug>` (this response only) | | `409` | `slug_taken`, with the header `X-Slug-Suggestion: <first free slug>` (this response only) |
+145
View File
@@ -0,0 +1,145 @@
# Site languages, language setup and public URL pattern
Contract for `features/site_languages.feature`, `features/language_setup.feature` and `features/site_public_url_pattern.feature`. The SPA mocks `/v1` from this page.
Errors are plain text whose body is exactly the code, with the status below. A body that cannot be decoded, or that lacks a required key, is 400 with the body-mismatch message ("The request cannot be processed due to a mismatch in the format of the body."). An anonymous caller is 401, a verified user without `settings.manage_sites` is 403 `missing_permission`. Writes need a real session; API keys are refused.
An owner is a verified user holding `settings.manage_sites`. A reader is any other verified user.
## Visibility exception (accepted)
`version_count` and `published_count` in `GET /v1/site/{key}/languages` are site-level aggregates of every non-deleted article (soft-deleted articles are not shown but still keep their language in use) of the language, drafts and offline ones included. They are visible to every signed-in reader, whatever that reader may open. This is a deliberate exception to the per-version visibility policy of `docs/design/localization-tables.md` ("Hidden versions"), accepted for slice 2. Later slices that expose titles or links of single versions must still filter by what the caller can read.
## Languages of a site
The supported tags are the list of `internal/domain/language` (`en`, `en-GB`, `en-US`, `fr`, `fr-CA`, `pt`, `pt-BR`, `es`, `de`, `ar`). Tags are normalized: `pt-br` is stored as `pt-BR`.
### `GET /v1/site/{key}/languages`
Any verified user (session or API key). 404 `site_not_found`.
```json
{
"revision": "9f2c...",
"default": "en",
"needs_setup": false,
"languages": [
{"lang": "en", "enabled": true, "is_default": true, "version_count": 7, "published_count": 6, "social_locale": null, "social_locale_state": "not_set"},
{"lang": "fr", "enabled": true, "is_default": false, "version_count": 4, "published_count": 2, "social_locale": "fr_FR", "social_locale_state": "set"}
],
"available": [
{"lang": "pt", "substitute": null},
{"lang": "pt-PT", "substitute": "pt"}
]
}
```
- `revision` is an opaque digest of the rows (lang, default, enabled, social_locale). Counts do not change it. Send it back on `PUT`.
- `languages` lists the default first, then the other enabled languages by tag, then the disabled ones by tag.
- `social_locale_state` is `set` (an explicit `social_locale`), `derived` (no explicit value and the tag has a region: the effective value is the tag with an underscore, `en-GB` gives `en_GB`) or `not_set`. `social_locale` is only the explicit value, so the client computes the derived one from the tag.
- `available` lists the tags an owner can pick. A tag with a non-null `substitute` is not supported itself; only the broader tag is. The server refuses it with `unsupported_language`, so the client sends the substitute once the user confirms.
- `needs_setup` is true when the site has no confirmed default language. Then `default` is `null`, `languages` is `[]` and `PUT` answers 409 `setup_required`. Sites created after the migration have no language row and need setup too.
### `PUT /v1/site/{key}/languages`
Owner only. The whole set is replaced in one transaction under the site lock.
```json
{
"revision": "9f2c...",
"default": "en",
"languages": [
{"lang": "en", "enabled": true, "social_locale": null},
{"lang": "fr", "enabled": true, "social_locale": "fr_CA"}
]
}
```
`revision`, `default`, `languages` and each `enabled` are required (400 when absent). `social_locale` is optional and `null` means none. A language left out of the list is removed. The answer is 200 with the new read shape. Sending the state that is already stored changes nothing and keeps the revision.
Checks run in this order:
| Order | Status | Body | When |
| --- | --- | --- | --- |
| 1 | 404 | `site_not_found` | unknown key |
| 2 | 409 | `setup_required` | the site has no confirmed default (any body) |
| 3 | 409 | `languages_changed` | `revision` is not the current one; nothing is applied |
| 4 | 422 | `invalid_language` | a tag is not a language tag (`english`, empty) |
| 4 | 422 | `unsupported_language` | a well formed tag that is not supported (`xx`, `pt-PT`) |
| 4 | 422 | `duplicate_language` | the same tag twice, case ignored |
| 4 | 422 | `invalid_social_locale` | not `ll_RR` or `lll_RR` (letters, one underscore), empty string, or the language part differs from the tag's language |
| 5 | 422 | `no_enabled_language` | no language is enabled, `languages: []` included |
| 6 | 422 | `default_not_enabled` | `default` is not in the list, not enabled, or not a supported tag |
| 7 | 409 | `language_in_use` | a removed language still has an article, draft, offline, online or soft-deleted (the display count `version_count` stays non-deleted only) |
| any | 409 | `languages_changed` | the database could not lock the site in time because another change is running (lock contention); nothing is applied, reload and retry |
Entries are checked in list order for step 4. A rejected request changes nothing. Disabling a language never touches its articles, and no article changes `lang`, status or publication. A site always has exactly one default language: the rows are planned with one default and checked again before they are written. Changing the default language re-evaluates the stored SEO status of every article of the site, because the site `default_description` only counts for the default language (see [SEO status and suggestions](articles.md#seo-status-and-suggestions)). A `social_locale` is stored as `language_REGION` (`fr_fr` becomes `fr_FR`). The language part rule only compares with the tag; matching `Site.Locale` is deferred to slice 6.
## First-time language setup
One global setup for every site with no confirmed default language. Owner only (`GET` as well: a reader is 403).
### `GET /v1/language/setup`
```json
{
"sites": [
{"key": "journal", "name": "Journal", "locale": "en", "article_count": 8, "suggestion": {"lang": "en", "substituted": false}},
{"key": "notes", "name": "Notes", "locale": null, "article_count": 3, "suggestion": null}
],
"available": [{"lang": "en", "substitute": null}]
}
```
`sites` lists the pending sites by id. `suggestion` comes from `Site.Locale` and keeps the region (`pt-BR` stays `pt-BR`); `substituted` is true when only the broader tag is supported (`fr-BE` gives `fr`). `suggestion` is `null` without a locale or without a supported language. An empty `sites` list means nothing is pending.
### `POST /v1/language/setup`
```json
{"sites": [{"key": "journal", "lang": "en"}, {"key": "notes", "lang": "en"}]}
```
200 with `{"assigned": 16, "sites": [{"key": "journal", "lang": "en", "assigned": 8}]}`. `assigned` counts the articles that got a language (soft-deleted ones included). `sites` lists the sites confirmed by this call. The default language is created enabled and confirmed, the seeded unconfirmed row is replaced, and every article without a language takes the tag. Nothing is translated, linked or moved. Sites that already have a confirmed default are skipped, whatever tag is asked for, so a retry answers 200 with `assigned: 0`.
| Status | Body | When |
| --- | --- | --- |
| 400 | body-mismatch message | no `sites` key or malformed JSON |
| 404 | `site_not_found` | a key does not exist |
| 409 | `setup_in_progress` | another setup holds the site locks (nothing applied) |
| 422 | `invalid_language` / `unsupported_language` | a bad `lang`, empty included |
| 422 | `duplicate_site` | the same key twice |
| 422 | `setup_incomplete` | a pending site is missing from the request |
| 500 | `Internal server error` | a write failed; everything is rolled back |
All sites are applied in one transaction. Site rows are locked in ascending id order without waiting; a busy lock is `setup_in_progress`. The pending list is read again after the locks and any site that became pending in between is locked too, until the list is stable, so a site created while a setup starts is never left half handled.
The 200 body also has `skipped`: the keys, sorted, of requested sites that already had a confirmed default and were left untouched (always present, `[]` when none). Their requested `lang` is ignored, never applied.
```json
{"assigned": 3, "sites": [{"key": "notes", "lang": "fr", "assigned": 3}], "skipped": ["journal"]}
```
## Lock contention
Every locking path of `PUT /v1/site/{key}/languages` and `POST /v1/language/setup` runs inside the transactor. A lock that cannot be taken in time (SQLite `SQLITE_BUSY`/`SQLITE_LOCKED`, MySQL 3572 and 1205, PostgreSQL `55P03`) is recognised once, by the database driver, and reaches the use case as `transaction.ErrLockContention`. The PUT answers 409 `languages_changed` and the setup answers 409 `setup_in_progress`. Nothing is applied and a retry is safe. It is never a 500.
## SQLite does not lock rows
The pinned SQLite driver (`github.com/glebarez/sqlite`) drops the `FOR UPDATE` clause: the `SELECT ... FOR UPDATE [NOWAIT]` that locks a site row on MySQL and PostgreSQL is a plain read on SQLite. SQLite instead serializes writers on the whole database: a second writer waits up to the 5 s busy timeout and a transaction that read before another one committed fails with `SQLITE_BUSY` when it tries to write. Both outcomes keep the data consistent and the busy failure is answered as lock contention above. `test/localization_concurrency_test.go` pins the statuses (200 or 409, never 500) for a PUT racing a site creation and for two simultaneous setups.
## Activity log
Both writes are recorded in the `sites` category, once after the commit and never for a read or a no-op:
| Action | Target | Changes and params |
| --- | --- | --- |
| `site.languages_edit` | the site | `default_language` (before, after) when the default changed, `languages` (before, after: tags sorted, `(off)` for disabled, `[social_locale]`). A PUT that changes nothing records nothing. |
| `site.language_setup` | one event per site confirmed by the POST | `default_language` ("" to the tag), param `assigned` (articles that got the language) |
A refused call is recorded as a failed event with a plain reason (for example "The languages changed since they were read."). An unknown site key is not recorded.
## Public URL pattern
`public_url_pattern` is a string or `null` on every site JSON (`GET /v1/site/`, `POST`, `PATCH`). It is read with the existing list and written with the existing `PATCH /v1/site/{id}` (owner). No new route. A `PATCH` without the key leaves it unchanged; `null` or `""` unsets it; surrounding spaces are trimmed.
Validation, in this order, answers 422 with the code as plain text: `invalid_pattern` (more than 512 characters), `invalid_scheme` (not `https://` or `http://`), `invalid_host` (no host, for example `https:///{slug}`), `unknown_placeholder` (anything between braces other than `{lang}` and `{slug}`, or a stray brace), `not_encoded` (a space, a non-ASCII character or other character that needs URL encoding; `%XX` sequences are fine), `missing_slug` (no `{slug}`). Repeated placeholders are allowed. Saving the pattern changes no article, canonical URL or public response, and is recorded in the activity log as the `public_url_pattern` field.
+26 -5
View File
@@ -15,7 +15,7 @@ api/ ──▶ internal/infrastructure/useCases ──▶ internal/domain
| Domain | `internal/domain/<name>/` | Entities, `Err…` sentinel errors, `Repository` interfaces. Imports only the stdlib and other domain packages, with no GORM tags. | | Domain | `internal/domain/<name>/` | Entities, `Err…` sentinel errors, `Repository` interfaces. Imports only the stdlib and other domain packages, with no GORM tags. |
| Use cases | `internal/infrastructure/useCases/` | Application logic. Depends only on domain interfaces, never on persistence, mailer, GORM or `net/http`. | | Use cases | `internal/infrastructure/useCases/` | Application logic. Depends only on domain interfaces, never on persistence, mailer, GORM or `net/http`. |
| Adapters | `internal/infrastructure/persistence/{models,mappers,repositories}`, `internal/infrastructure/mailer` | Implement a domain `Repository` (assert with `var _ domain.Repository = &X{}`). GORM structs stay in `models` and are converted by `mappers`. | | Adapters | `internal/infrastructure/persistence/{models,mappers,repositories}`, `internal/infrastructure/mailer` | Implement a domain `Repository` (assert with `var _ domain.Repository = &X{}`). GORM structs stay in `models` and are converted by `mappers`. |
| Database drivers | `internal/infrastructure/persistence/database` | `database.Connect(Config{Driver, Source})` looks the driver up in a registry and returns a `Connection` (GORM handle, `NewBackup`, `Close`). A `Driver` implements `Open` and `NewBackup`, so a new database is one new file plus one registry entry. `database.Migrate` owns the `AutoMigrate` model list and the user-role backfill. Only `sqlite` exists today. | | Database drivers | `internal/infrastructure/persistence/database` | `database.Connect(Config{Driver, Source})` looks the driver up in a registry and returns a `Connection` (GORM handle, `NewBackup`, `Close`). A `Driver` implements `Open` and `NewBackup`, so a new database is one new file plus one registry entry. `database.Migrate` owns the `AutoMigrate` model list and the role backfills (legacy `users.role` into `role_id` while that column exists, invites without a role to Admin, then `created_by`). Only `sqlite` exists today. |
| Blob storage | `domain/image.Storage`, `internal/infrastructure/storage` | `Storage` (`Put`, `Open`, `Delete`) is the port for uploaded image bytes. `storage.Open(Config{Driver, Location})` picks the adapter; `local` is the only one. Repositories never touch files: use cases coordinate `Storage` and `image.Repository`. | | Blob storage | `domain/image.Storage`, `internal/infrastructure/storage` | `Storage` (`Put`, `Open`, `Delete`) is the port for uploaded image bytes. `storage.Open(Config{Driver, Location})` picks the adapter; `local` is the only one. Repositories never touch files: use cases coordinate `Storage` and `image.Repository`. |
| Delivery | `api/handlers/<name>/`, `api/router.go` | HTTP handlers receive use cases through `NewHandler(...)`. They never import persistence, mailer or GORM. | | Delivery | `api/handlers/<name>/`, `api/router.go` | HTTP handlers receive use cases through `NewHandler(...)`. They never import persistence, mailer or GORM. |
| Composition root | `api/dependecyInjection.go` | The only place that picks the database and storage drivers, builds repositories and use cases, and runs `database.Migrate` and the image metadata backfill at boot. | | Composition root | `api/dependecyInjection.go` | The only place that picks the database and storage drivers, builds repositories and use cases, and runs `database.Migrate` and the image metadata backfill at boot. |
@@ -27,7 +27,8 @@ Nothing under `internal/` imports `api/`.
| Package | Role | | Package | Role |
|---|---| |---|---|
| `api/handlers/user` | Authenticated user endpoints: profile update (`UpdateMe`) and the users list with invitations (`CreateInvite`, `ListUsers`). | | `api/handlers/user` | Authenticated user endpoints: profile update (`UpdateMe`), the users list with invitations (`CreateInvite`, `ListUsers`) and the role change (`RoleHandler.Change`). |
| `api/handlers/ownership` | `POST /v1/site/transfer-ownership`, built by `NewHandler(TransferOwnershipUseCase)` and mounted by `NewSiteRouter` in the session group. |
| `api/handlers/media` | The media library under `/v1/media` (list, upload, rename, delete, merge, usage). Images belong to the library, not to an article: deleting an article never deletes an image, and an image's "used in" is read from article bodies each time. | | `api/handlers/media` | The media library under `/v1/media` (list, upload, rename, delete, merge, usage). Images belong to the library, not to an article: deleting an article never deletes an image, and an image's "used in" is read from article bodies each time. |
| `api/pkg/upload` | Multipart `file` reading and the mapping of upload errors (415, 413, 400) shared by both upload routes. | | `api/pkg/upload` | Multipart `file` reading and the mapping of upload errors (415, 413, 400) shared by both upload routes. |
| `api/pkg/publicuser` | `PublicUser`, the JSON shape of a user with no password, codes or token version. `publicuser.New` converts a domain `user.User`, so handlers never serialise the domain struct directly. | | `api/pkg/publicuser` | `PublicUser`, the JSON shape of a user with no password, codes or token version. `publicuser.New` converts a domain `user.User`, so handlers never serialise the domain struct directly. |
@@ -55,6 +56,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.
@@ -85,9 +94,11 @@ The use cases `ListAuthors`, `CreateAuthor`, `CreateMyAuthor`, `UpdateAuthor`, `
`internal/domain/slug` holds the one slug rule (`Generate`, `WithSuffix`, `IsValid`: lowercase, accents folded, runs of other characters become one dash, 100 characters, a caller-chosen fallback). `internal/domain/article` uses it with the fallback `article` and holds the twelve SEO fields of `Article`, the `Update` fields for them (`Nullable` for the two image ids), `ValidateCanonicalURL`, the eleven dismiss codes and `NormalizeDismissed`, and the sentinels `ErrInvalidSlug`, `ErrSlugTaken` and `ErrInvalidCanonicalURL`. `*SlugTakenError` wraps `ErrSlugTaken` and carries the suggested free slug; the handler turns it into the `X-Slug-Suggestion` header of the 409. `author.GenerateSlug` delegates to the same package. `internal/domain/slug` holds the one slug rule (`Generate`, `WithSuffix`, `IsValid`: lowercase, accents folded, runs of other characters become one dash, 100 characters, a caller-chosen fallback). `internal/domain/article` uses it with the fallback `article` and holds the twelve SEO fields of `Article`, the `Update` fields for them (`Nullable` for the two image ids), `ValidateCanonicalURL`, the eleven dismiss codes and `NormalizeDismissed`, and the sentinels `ErrInvalidSlug`, `ErrSlugTaken` and `ErrInvalidCanonicalURL`. `*SlugTakenError` wraps `ErrSlugTaken` and carries the suggested free slug; the handler turns it into the `X-Slug-Suggestion` header of the 409. `author.GenerateSlug` delegates to the same package.
Slugs are unique per site, enforced by the unique index `idx_articles_site_slug` on `(site_id, slug)`. The use cases decide first: `CreateArticle` generates the slug from the title and takes the first free `-N` on the default site (retrying when the repository reports a race), `UpdateArticle` re-checks the slug on the target site for an edited slug, an empty slug (regenerated from the title) and a move, and computes the suggestion as the first free `-N` from 2, fitting 100 characters. `ArticleRepository` locks the site row, checks the slug inside the transaction and re-explains a failed write as `ErrSlugTaken`. Deleting an article replaces its slug with the tombstone `#deleted-<id>` (it can never match a valid slug) before the soft delete, so the slug is free again while the unique index keeps covering soft-deleted rows. Slugs are unique per site and language, enforced by the unique index `idx_articles_site_slug` on `(site_id, lang, slug)` (the name is kept from the earlier `(site_id, slug)` index, which the migration replaces once, tracked by the `article_slug_index_per_language` marker). Each article belongs to a story (`stories` table) and a second unique index `idx_articles_story_lang` on `(story_id, lang)` allows one version per language per story; both indexes are created after the `article_stories` backfill marker, which gives every pre-existing article its own story. `site_languages` holds one default language per site, seeded once from `Site.Locale` as an unconfirmed suggestion (`site_language_suggestions` marker). `CreateArticle` owns the rule that a new article takes the confirmed default: it runs through `transaction.Transactor`, locks the site row (`site.Repository.LockSite`), reads the site's language rows through the `localization.Repository` port, lets `localization.ConfirmedDefaultTag` pick the confirmed default tag (or `""` while it is unconfirmed), picks the free slug for that language and calls `Create` with the resulting `Lang`, all in one transaction. `localization.Repository` is the only port for site languages; the former `language.Repository` and its `SiteLanguageRepository` adapter are gone. When the site row is gone by then (deleted after the use case looked it up), the use case answers `article.ErrTargetSiteDeleted` (`409 target_site_deleted`) instead of the lookup's `404`. `ArticleRepository.Create` only stores what it receives, checks that a given story row exists and opens the new story in the same transaction (the story rolls back with the article, `content_revision` starts at 1). `ApplyLanguageSetupUseCase` confirms a default and assigns the unassigned articles under the same site locks (taken with `NOWAIT`), so no article is left unassigned once the confirmation commits. The one-default-per-site invariant lives in the domain (`localization.Plan` builds rows with one default, `localization.RequireSingleDefault` checks it before `UpdateSiteLanguagesUseCase` writes); `LocalizationRepository.Replace` only writes the rows it receives. `article.Repository.SlugTaken` takes the language, matching the index. The use cases decide first: `CreateArticle` generates the slug from the title and takes the first free `-N` on the default site (retrying when the repository reports a race), `UpdateArticle` re-checks the slug on the target site for an edited slug, an empty slug (regenerated from the title) and a move, and computes the suggestion as the first free `-N` from 2, fitting 100 characters. `ArticleRepository` locks the site row and leaves uniqueness to the two indexes: each driver says whether an error is a unique violation (`Driver.IsUniqueViolation`: SQLite extended codes `2067` and `1555`, MySQL `1062` and `1586`, PostgreSQL `23505`, behind `database.IsUniqueViolation`), and the repository then re-reads which rule was hit and returns `ErrSlugTaken` or `ErrLanguageTaken`. `PATCH /v1/article/{id}` is one atomic edit: when it moves a story (the caller reads one version of a larger story), `UpdateArticleUseCase` depends on the `StoryMover` port and runs the move of the other versions and its own field edit in the single transaction of `MoveStoryUseCase.MoveStoryThen`, so a refusal after the move step moves nobody and changes no revision. Validation that needs no lock (authors, SEO fields, slug rules and the slug of the target site) runs before the transaction. Row locks are taken site first (ascending ids), then article rows (`ArticleRepository.Update` finds the site with a read outside its transaction, because a read inside would open the snapshot that MariaDB 11 then holds against the locked row, and re-checks the site after locking the article), in `ArticleRepository.Update`, `Create`, `Delete`, `CreateTranslation` and the story move, so a slug edit cannot deadlock a move; the move re-reads and re-locks until the set of sites of the story is stable. Publish and `UpdateBody` are targeted `UPDATE`s of their own columns (plus `updated_at`), so they never overwrite a concurrent edit and never touch the revisions. Driver lock errors (PostgreSQL `55P03`, `40P01` and `40001`, MySQL `3572`, `1205` and `1213`, MariaDB `1020` raised by its snapshot isolation) all become `transaction.ErrLockContention` (`409 story_busy`). SQLite ignores `FOR UPDATE`: there the single writer plus the compare-and-set on `edit_revision` in `writeArticleColumns` are what keep concurrent edits correct, not the row locks. Deleting an article replaces its slug with the tombstone `#deleted-<id>` (it can never match a valid slug) before the soft delete, so the slug is free again while the unique index keeps covering soft-deleted rows. `DeleteStoryUseCase` (`DELETE /v1/story/{story_id}`) refuses a caller whose `content.delete` is not at scope `all` before reading anything, locks every site of the story (re-reading until the set is stabLine truncated
`database.Migrate` adds the columns with `AutoMigrate`, then runs `BackfillSiteTitleTemplates` and `BackfillArticleSlugs` (only rows with an empty slug, in id order, per site, applying the same rule and the same suffixes, with the tombstone for soft-deleted rows) and only then creates the unique index, so it is idempotent and completes a partly backfilled table. The default `title_template` is written by the backfill and the seed, not by a column default, because the SQLite migrator rebuilds the table on every start when the default contains `%` and `|`. The article persistence is split into ports by use: `article.Repository` (single versions and writes), `article.StoryReader` (the editorial list by story: pages, counts, versions of a page) and `article.SEOIndex` (the stored SEO status: `StaleSEO`, `StoreSEO`, `MarkSiteSEOStale`). `article.ListingRepository` joins the three for `ListArticlesUseCase`, the only use case that needs all of them; `ArticleRepository` implements every port, and `transaction.Repositories` exposes `ArticleSEO` so a transaction that changes the default language can clear the statuses of its site. The rules that compute the status stay in the use cases (they parse HTML through `golang.org/x/net/html`), so the repositories only clear and store it; see [performance.md](performance.md#the-seo-article-filter).
`database.Migrate` first sets `source_revision` to `0` where an older nullable column holds `NULL` (`BackfillNullSourceRevisions`, a no-op once no `NULL` is left), so `AutoMigrate` can make it `NOT NULL`; it then adds the columns with `AutoMigrate`, then runs `BackfillSiteTitleTemplates` and `BackfillArticleSlugs` (only rows with an empty slug or a duplicate within the same site and language, in id order, per site and language, applying the same rule and the same suffixes, with the tombstone for soft-deleted rows) and only then creates the unique index, so it is idempotent and completes a partly backfilled table. The default `title_template` is written by the backfill and the seed, not by a column default, because the SQLite migrator rebuilds the table on every start when the default contains `%` and `|`.
Media usage has more sources than article bodies: `Article.CoverImageID` and `SocialImageID`, `Author.AvatarID` and `Site.DefaultSocialImageID`. `ListMedia`, the purge plan and `GetMediaUsage` count an article once however many places use the image. `DeleteMedia` clears the cover and social references (`article.Repository.ClearImage`, restored with `RestoreImage` when the delete fails), `MergeMedia` repoints them (`RepointImage`) and counts an article rewritten in its body and its cover once, and `GetMediaUsage` (now built with the site and author repositories) returns articles, authors and sites with `type` and `fields`. Media usage has more sources than article bodies: `Article.CoverImageID` and `SocialImageID`, `Author.AvatarID` and `Site.DefaultSocialImageID`. `ListMedia`, the purge plan and `GetMediaUsage` count an article once however many places use the image. `DeleteMedia` clears the cover and social references (`article.Repository.ClearImage`, restored with `RestoreImage` when the delete fails), `MergeMedia` repoints them (`RepointImage`) and counts an article rewritten in its body and its cover once, and `GetMediaUsage` (now built with the site and author repositories) returns articles, authors and sites with `type` and `fields`.
@@ -95,7 +106,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).
@@ -103,6 +114,16 @@ The cache screen adds three ports in `internal/domain/image`: `VariantCacheRepos
At boot, `BackfillImageMetadataUseCase` (through `image.Repository.ListMissingMetadata` and `UpdateMetadata`) fills `filename`, `size`, `content_type`, `width`, `height` and `sha256` for image rows that lack them, reading the bytes through `image.Storage` (the files in `UPLOAD_DIR` with the local adapter, the bucket objects with the S3 adapter). It is idempotent, and a row whose file is missing or unreadable is left as it is without stopping the boot. The old `article_id` column and the `article_images` table are kept and never written. At boot, `BackfillImageMetadataUseCase` (through `image.Repository.ListMissingMetadata` and `UpdateMetadata`) fills `filename`, `size`, `content_type`, `width`, `height` and `sha256` for image rows that lack them, reading the bytes through `image.Storage` (the files in `UPLOAD_DIR` with the local adapter, the bucket objects with the S3 adapter). It is idempotent, and a row whose file is missing or unreadable is left as it is without stopping the boot. The old `article_id` column and the `article_images` table are kept and never written.
### Roles and permissions
`internal/domain/role` holds the permission catalogue, the built-in roles, one exported constant per catalogue key (`roleKeys.go`, the only place a key is spelled in `api/`) and the pure rules over grants: `ValidateGrants`, `ParseTypedKey` and `Role.GrantSet()`. `Role.GrantSet()` is the single constructor of a `GrantSet` and the only place a stored grant becomes an effective one: it drops unknown keys, typed keys on non-content permissions or with an invalid type key, and owner-only permissions on a role that is not locked; it treats a toggle stored at `own` as `none`; and it resolves duplicate rows to the most restrictive scope. `ValidateGrants` rejects the same rows at write time (`ErrDuplicateGrant`, `ErrOwnerOnlyGrant`, `ErrInvalidScope`, `ErrUnknownPermission`), so a bad row is refused when written and ignored when read. A toggle permission only counts at scope `all`, a scoped one at `own` or `all`. A content permission can be narrowed or widened per content type with a key such as `content.update:blog`; the typed row replaces the wildcard for that type and a `none` row denies. A `GrantSet` is opaque: `ScopeFor(key, typeKey)` resolves wildcard and typed rows, `Permits(key, typeKey, callerID, createdBy)` is the one implementation of own and all (`created_by` 0 and caller 0 own nothing), and `Holds`, `HoldsFor` and `HoldsAll` answer the gate questions. Use cases, handlers and middleware never compare a caller id with `CreatedBy` and never read grant rows. `role.Repository` holds `List` (with every role's grants, in one pass), `Get`, `GetByName`, `Create`, `Save`, `Delete`, `ReassignMembers`, `RemoveTypedGrants` and `MemberCounts` (users grouped by `role_id` plus invites with `accepted_at` NULL grouped by `role_id`, two statements for any number of roles); no role use case scans `user.Repository.GetAll`. `user.Repository` gains `UpdateRole(id, from, to)`, a compare-and-swap on the role the use case read (`ErrRoleChanged`, `ErrUserNotFound`, `role.ErrRoleNotFound`), and `TransferOwnership(from, to, ownerRoleID, formerRoleID)`, which updates both rows in one transaction and fails whole when `from` no longer holds the Owner role (`ErrRoleChanged`) or `to` is missing or unverified (`ErrInvalidTransfer`). `invite.Invite` carries `RoleID`. `ChangeUserRoleUseCase`, `TransferOwnershipUseCase` and the amended invite use cases find the built-in roles with one helper, `builtInRole(roles, name)` (`GetByName`, then `built_in` must be true), and a user's role with `resolveRole`, which reads `role_id` only. `Delete` re-counts users and open invites inside its transaction and `ReassignMembers` moves users and open invites in one transaction and returns their sum. `Save` is version checked: it updates the row only when the caller's version matches, bumps the version, writes `updated_at` and `updated_by`, replaces the grants in the same transaction and returns `ErrRoleConflict` otherwise. It never changes `built_in` or `locked`. `Delete` removes the role and its grants in one transaction and returns `ErrRoleHasMembers` when a user still has the role id; `ReassignMembers(from, to)` changes only `role_id` and returns the count; `RemoveTypedGrants(typeKey)` removes the five `content.*:{typeKey}` rows from every role and bumps the version of each affected role once. The role domain also owns `GrantSet.Covers(other, typeKeys)`, the single implementation of "the caller holds at least these grants" behind the no-escalation rule (it returns an `EscalationError` naming the first offending key), `Role.EffectiveGrants()` (the normalised list used by role responses, the audit diff and `/v1/auth/me`) and `DiffGrants`. The roles API (`/v1/role`) is served by `ListRolesUseCase`, `GetRoleUseCase`, `CreateRoleUseCase`, `UpdateRoleUseCase` (which also resets a built-in role), `DeleteRoleUseCase` and `ReassignRoleMembersUseCase`; they depend on `role.Repository`, `user.Repository`, `contenttype.Repository` and `audit.Recorder` only, and `api/handlers/role` maps their domain errors to the status and code. `DeleteContentTypeUseCase` and `CreateContentTypeUseCase` also take the role repository to clear per-type grants. `DeleteContentTypeUseCase` deletes the type and then clears its typed rows; if that cleanup fails the rows stay, which is safe because the role views (`GET /v1/role`, `GET /v1/role/{id}` and every write response) drop typed rows for content types that no longer exist, so a GET body stays a valid PUT body, and `CreateContentTypeUseCase` clears the rows of a key right after a successful create, before any role can match the new type. A failed create never touches the roles. The repository re-checks the name case-insensitively inside the `Create` and `Save` transactions (`ErrRoleNameTaken`), locks the role row in `Delete` before counting members (a no-op on SQLite) and guards the `ReassignMembers` update with an `EXISTS` on the target role, answering `ErrInvalidReassign` when the target vanished.
Enforcement path. The first middleware that needs the signed-in user (`AuditContext`, `RequireCurrentToken`, `RequireVerifiedUser` or a permission gate) stores a request-scoped holder in the context (`access.WithCurrentUser`), so the user is loaded once per request; an API key adds the one load of its own authentication. `CheckPermissionUseCase` resolves the caller's role with one `role.Repository.Get` (a user whose `role_id` is 0 resolves to `ErrRoleNotFound`, an empty grant set), builds the `GrantSet` from the grants the role already carries and never calls `List`. `RequireTypedPermission` gates a content route on the typed scope before any lookup (the type key is `article` for articles and the `{key}` of the URL for entries) and puts the caller (`access.Caller`: user id and grants) in the context. The optional `OptionalAccess` middleware does the same for the public article routes without ever refusing: no cookie, an unverified user, a stale token or an unresolvable role leave the caller anonymous, and only a role repository failure answers 500. The handler passes the caller to the use case as `useCases.ContentCaller`; the use case loads the article or entry, decides the scope with `Permits` right after the load and before any other lookup or validation, and returns a `role.MissingPermissionError`, which `access.WriteIfMissingPermission` writes as 403 with the base key in `X-Missing-Permission`. Reading follows the same helper: an article is visible when it is online or `content.read` permits its `created_by`, and an entry the caller may not read is `entry.ErrEntryNotFound`. A list under scope `own` is filtered before totals, search and paging. `CreateContentTypeUseCase` refuses the built-in type keys with `contenttype.ErrKeyTaken`.
Built-in reconciliation: `database.SeedBuiltInRoles` creates the three built-in roles when they are missing and never overwrites an edited one. On every start it adds the catalogue keys a built-in role lacks: always for Owner, at scope `all`, and for Admin and Writer only while their version is still 1. It never removes or downgrades a grant and never bumps the version.
Created-by backfill: `database.BackfillCreatedBy` assigns articles (soft-deleted ones included) and entries whose `created_by` is 0 to the first owner by id. A database without an owner is left alone. Entries have no soft delete, so no unscoped query is needed for them.
## Frontend ↔ backend ## Frontend ↔ backend
``` ```
-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
@@ -12,7 +12,7 @@ A content type is a named schema (a key, a name and 1 to 50 fields) stored as on
The domain packages `internal/domain/contenttype` and `internal/domain/entry` own the rules: key, name and field validation, entry validation against a schema, the sort whitelist, the page limits and the value equality used by uniqueness. The use cases orchestrate them through the two repositories. The repositories only store and load rows. Entry counting for the "type still has entries" rule lives on the entry repository. The domain packages `internal/domain/contenttype` and `internal/domain/entry` own the rules: key, name and field validation, entry validation against a schema, the sort whitelist, the page limits and the value equality used by uniqueness. The use cases orchestrate them through the two repositories. The repositories only store and load rows. Entry counting for the "type still has entries" rule lives on the entry repository.
## Known limitations of phase 1 ## Known limitations
- Uniqueness and schema re-validation are O(n). Checking a unique field loads every entry of the type and compares values in Go, and updating a type with stored entries loads all of them to re-validate. This keeps the SQL portable across SQLite, MySQL/MariaDB and PostgreSQL. The path to fix it is the filterable-fields phase: project the values of unique and filterable fields into an indexed table, so uniqueness becomes an indexed lookup and re-validation can be restricted to the changed fields. - Uniqueness and schema re-validation are O(n). Checking a unique field loads every entry of the type and compares values in Go, and updating a type with stored entries loads all of them to re-validate. This keeps the SQL portable across SQLite, MySQL/MariaDB and PostgreSQL. The path to fix it is the filterable-fields phase: project the values of unique and filterable fields into an indexed table, so uniqueness becomes an indexed lookup and re-validation can be restricted to the changed fields.
- Unique values are checked without a transaction, so two concurrent writes of the same unique value can both succeed. A content type key is protected by a unique index, and a violation is reported as `content_type_key_taken` (409). - Unique values are checked without a transaction, so two concurrent writes of the same unique value can both succeed. A content type key is protected by a unique index, and a violation is reported as `content_type_key_taken` (409).
+4 -4
View File
@@ -45,7 +45,7 @@ Once the restart helper is installed (it writes `update-helper.json` next to `DB
The owner's Restart button installs a downloaded update, or just restarts the site, without touching the server by hand. The app itself stays unprivileged: the systemd unit below keeps `ProtectSystem=strict` and only the data directory (the directory that holds `DB_FILE`) is writable. The only privileged code is a small helper, the same binary started as `renewcms apply-update` by a systemd service that runs as root. The owner's Restart button installs a downloaded update, or just restarts the site, without touching the server by hand. The app itself stays unprivileged: the systemd unit below keeps `ProtectSystem=strict` and only the data directory (the directory that holds `DB_FILE`) is writable. The only privileged code is a small helper, the same binary started as `renewcms apply-update` by a systemd service that runs as root.
First install v2.6.0-beta or newer manually, back up the database, uploads and current binary, and confirm the app runs as an unprivileged service user. The binary and its parent directory should be controlled by root. Owners can start updates and restarts; admins have read-only update status. First install the helper manually, back up the database, uploads and current binary, and confirm the app runs as an unprivileged service user. The binary and its parent directory should be controlled by root. Owners can start updates and restarts; admins have read-only update status.
#### Find the actual database directory #### Find the actual database directory
@@ -121,7 +121,7 @@ On the latest release you can test only a plain restart. Test installation, forc
- **Restart is missing:** reload Settings, confirm you are owner, and inspect `GET /v1/system/update` in the browser's Network panel. For an idle owner, `can_apply: false` means the app did not detect the helper. Check that `update-helper.json` is beside the actual database and readable by the service user. - **Restart is missing:** reload Settings, confirm you are owner, and inspect `GET /v1/system/update` in the browser's Network panel. For an idle owner, `can_apply: false` means the app did not detect the helper. Check that `update-helper.json` is beside the actual database and readable by the service user.
- **Wrong helper directory:** disable the helper with the old `--data-dir`, then enable it with the correct directory and port. Do not change `DB_FILE` to compensate. - **Wrong helper directory:** disable the helper with the old `--data-dir`, then enable it with the correct directory and port. Do not change `DB_FILE` to compensate.
- **Overlay does not clear:** inspect the helper journal, `update-result.json` and `update-running.json` in the actual database directory. Check localhost health on the configured port, then public health through the proxy. Do not cache `/healthz` at the proxy. - **Overlay does not clear:** inspect the helper journal, `update-result.json` and `update-running.json` in the actual database directory. Check localhost health on the configured port, then public health through the proxy. Do not cache `/healthz` at the proxy.
- **Old binary panics on `--version`:** older releases may interpret it as normal startup and require server environment variables. v2.6.0-beta and newer print their version without loading configuration. A separately launched process failing this way does not stop the systemd service. - **Old binary panics on `--version`:** releases before v2.6.0-beta treat it as normal startup and require server environment variables. A separately launched process failing this way does not stop the systemd service.
- **Download or verification fails:** inspect the app journal. All assets and redirects must use HTTPS on the configured feed host. The release must include the six binaries, `checksums.txt` and `checksums.txt.sig`. - **Download or verification fails:** inspect the app journal. All assets and redirects must use HTTPS on the configured feed host. The release must include the six binaries, `checksums.txt` and `checksums.txt.sig`.
- **Update rolls back:** check the previous version and helper journal. Automatic rollback restores the binary, not the database; schema changes still require a recovery plan. - **Update rolls back:** check the previous version and helper journal. Automatic rollback restores the binary, not the database; schema changes still require a recovery plan.
@@ -159,7 +159,7 @@ What is supported and what is not:
#### Verification status #### Verification status
A real v2.6.0-beta plain browser restart was confirmed on Linux/systemd on 2026-10-02: the path unit triggered the helper, a new server process started, the result was `succeeded`, and public health returned `ok`. Real signed installation, forced rollback and adversarial filesystem checks remain unverified. The manual cases are listed in [the restart QA procedure](../features/updates_restart_helper.qa.md). Only the plain browser restart has been confirmed on a real Linux/systemd machine. Signed installation, forced rollback and adversarial filesystem checks remain unverified; the manual cases are in [the restart QA procedure](../features/updates_restart_helper.qa.md).
## 2. Lay out the server ## 2. Lay out the server
@@ -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
+30 -130
View File
@@ -1,140 +1,40 @@
# RenewCMS design pass 2 # RenewCMS design
Nuxt UI v4 back-office. Tokens only, no raw hex (brand mark excepted). Light and dark. 1440×900 and 390×844. Radius 0. Nuxt UI v4 back-office. Tokens only, no raw hex (the brand mark excepted). Light and dark, at 1440×900 and 390×844. Radius 0. Behaviour comes from `features/`; where the two disagree, stop and ask.
## Boards ## Files
- `RenewCMS Screens Back-office.dc.html`: every back-office screen, Settings → Media (variants, cache), and the group "States matrix: controls". Frames: `AppFrame` (shell), `DirectoryFrame` (Sites and Authors), `ActivityFrame`, `MediaFrame`, `VariantsFrame`, `IntegrationPage`, `IntegrationImages`, `CodeSnippet`, `StatesMatrix`.
- `RenewCMS Screens Auth.dc.html` (7 groups, 50 states), `RenewCMS Screens API keys.dc.html` (12 states).
- `RenewCMS Prototype.dc.html`: updated to match (title-only New article, no body limit or counter, neutral count, pagination, link button, AppFrame's mobile drawer).
- Unchanged: Foundations, Components, Handoff, Directions and Emails boards.
## Pass 3: sites and authors (revised) | File | Content |
Roles, decisions and the slice order are in `sites-authors-slices.md` (Sites and Authors) and `seo-slices.md` (SEO). | --- | --- |
| `routes.md` | Routes with their auth requirement. |
| `components.md` | Component inventory with its Nuxt UI mapping, then the full component specs. |
| `states.md` | Every state per screen, plus the HTTP-status-to-copy table. |
| `screens/<screen>.md` | Exact copy per state. `visual:check` takes the screen name from the file name. |
| `foundations.md` | Tokens, spacing, type and contrast. |
| `emails.md` | The mail templates. |
| `decisions.md` | Product and interface decisions that are not visible in the specs: search and sharing, sites and authors, roles, account self-service and the interface defaults. |
| `media-field.md` | Spec of the Media field type: control, states, copy, accessibility and API. |
| `source/` | The raw export. The `.dc.html` boards are the visual reference, to open in a browser. `tokens/` and `emails/` hold the ready-to-use token and template files. |
Back-office board groups: Sites, Sites: form, Sites: delete, Authors, Authors: form, Authors: delete, Editor: site and authors, Profile: author profile, Articles: sites and authors. Plus tables: decisions to confirm (13 rows, 5 marked Decided), deviations, API and errors (with the 403 rows), components, accessibility, copy per state. ## Boards (in `source/`)
- Roles: only creating, editing, deleting and setting the default site are owner only (no sidebar entry or Publishing card for others, 403 page on a direct link). Anyone who can edit an article can set its site and read the site list. Authors: owner and admin manage; other roles read-only, and any role can create and edit their own author (user link locked, no delete).
- The site key is immutable: read-only with a lock in the edit form; the warning state and dialog are gone.
- The "Author profile" card is drawn in every existing Profile frame. The "Site and authors" section shows collapsed in every existing Editor frame that has the details sidebar (39 already did; the Loading frame now shows the header with a skeleton summary). The Not found frame has no editor, and on mobile the section is inside the Details sheet. The dedicated groups keep only the feature-specific states.
- Shared pieces (list, slide-over, delete-with-reassign dialog, slug field, media field) are defined once in `DirectoryFrame`, used by Sites and Authors. The Profile card is defined once in `AppFrame`.
- States trimmed from 87 to 68 (Sites 9, Sites: form 7, Sites: delete 3, Authors 8, Authors: form 11, Authors: delete 6, Editor: site and authors 16, Profile: author profile 5, Articles: sites and authors 3). Dropped: in-progress and done variants (covered by the button loading pattern and the confirm state's trigger), per-error URL variants, the site picker (same picker as the avatar), manual slug override, long names (merged into Many authors), per-field duplicates. The blocked-delete dialog is one frame, "Server fallback (409)".
- Only individual states that render a relative time or a countdown carry the "Clock-sensitive" tag (13 states, listed in states.md). No Home or Articles frame is tagged as a whole.
- Role-restricted variants drawn: read-only Authors list and detail, hidden Sites entry, Sites 403, own-author edit.
## Pass 4: custom content types - `RenewCMS Screens Back-office.dc.html`: every back-office screen, with the frames `AppFrame` (shell), `DirectoryFrame` (Sites and Authors), `ActivityFrame`, `MediaFrame`, `VariantsFrame`, `IntegrationPage`, `IntegrationSearch`, `IntegrationImages`, `CodeSnippet` and `StatesMatrix`.
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. - `RenewCMS Screens Auth.dc.html`: log in, register, pending, verify, accept invite, forgot and reset password, verify new email, account deleted.
- AppFrame gains a Schema item (owner and admin) and a Content group (sidebar and mobile drawer). Nothing else in AppFrame changed. - `RenewCMS Screens API keys.dc.html`.
- Backend gaps still open: built-in types and fields, display names for created_by and updated_by, a type icon, per-change entry counts. - `RenewCMS Screens Roles.dc.html`: the role editor, users and ownership (`RolesFrame`, data `roles-spec.js`).
- Not done: Back-office and Prototype boards were not compared visually after the sidebar change (see Checks below). - `RenewCMS Screens Schema.dc.html`: custom content types, entries, relations and the Media field (`SchemaFrame`).
- `RenewCMS Screens Account.dc.html`: change email, export your data and delete your account (`AccountCards`, copy in `account-copy.js`).
- `RenewCMS Emails.dc.html`, `RenewCMS Foundations.dc.html`, `RenewCMS Components Primitives.dc.html`, `RenewCMS Components Product.dc.html`, `RenewCMS Handoff.dc.html`, `RenewCMS Directions.dc.html` and `RenewCMS Prototype.dc.html`.
## Specs Every state has a desktop and a mobile frame, and the theme switch gives light and dark. States that render a relative time or a countdown are tagged clock-sensitive in `states.md` and skipped by `task visual:check`.
routes.md · components.md · states.md · foundations.md · change-list.md · activity-spec.js · screens/*.md (24 files)
## Status ## Known gaps
| Section | Status |
|---|---|
| A1 Activity export | Done: CSV only, synchronous; progress state removed; JSON proposed |
| A2 Pagination `page`/`size` | Done in frames, routes.md, change-list.md |
| A3 Unknown variant and unsupported parameter | Done: both 400 bodies in the Responses table |
| A4 New tokens | Done: foundations.md table |
| A5 screens/*.md | Done: 22 files, copy generated from the board source |
| B1 Editor link | Done: 11 states |
| B2 Duplicates | Done for sidebar, topbar, drawer, code block, modal geometry; see Not done |
| B3 CodeSnippet | Done |
| B4 Overlays | Done |
| B5 Prototype | Done |
| B6 Contrast and states matrix | Done for the pairs listed; matrix drawn |
| B7 Consistency sweep | Done for the roles listed |
| B8 Copy glossary | Done by search; not every line re-read |
| B9 Media and picker | Badge added; Media pagination drawn (9 states); filter, sort and size not folded in |
| B10 "proposed" labels | Only article pagination and JSON export |
## State counts (Back-office board: 341 before pass 3, plus 68 for sites and authors = 409) - The Foundations, Components and Prototype boards do not show the account self-service pieces or every newer token.
| Group | States | - Duplicate implementations that look alike are not merged in code: toasts, badges, empty states and modal shells.
|---|---| - The Back-office board still shows the owner, admin and user navigation. Writer frames use the restricted `user` navigation of `AppFrame`.
| Boot | 1 | - The Schema board group 8 (Permissions) is superseded by the role editor, and `/settings/permissions` redirects to `/settings/roles`.
| Home | 10 |
| Articles | 14 |
| Articles: pagination | 11 |
| New article | 5 |
| Editor | 41 |
| Media | 52 |
| Media picker | 13 |
| Integration | 8 |
| Activity | 9 |
| Activity: filter cards | 10 |
| Activity: export | 15 |
| Activity details | 6 |
| My activity | 3 |
| Users | 17 |
| Settings | 25 |
| Settings: Media cleanup | 9 |
| Purge dialog | 8 |
| Purge results | 2 |
| Media duplicates entry | 2 |
| Settings: Retention | 6 |
| Profile | 13 |
| Global | 4 |
| Integration: images | 9 |
| Settings navigation | 5 |
| Variants list | 12 |
| Add edit variant | 11 |
| Media library (variants) | 6 |
| Image detail | 8 |
| Cache panel | 10 |
| Editor picker | 5 |
Back-office total 341 (pass 2 groups, table above) + 68 (sites and authors) = 409. Auth board 50 (Log in 9, Register 6, Pending 6, Verify 6, Accept invite 10, Forgot password 6, Reset password 7). API keys board 12. Total 471 states; every one has a desktop and a mobile frame, and the theme switch gives light and dark. The matrix has 24 control rows, 5 states on desktop and 4 on mobile (no hover). screens/*.md list the states of the pass 2 groups and the 68 pass 3 states. ## Article localization baseline (refreshed 2026-11-03)
## Fixes applied (pass 2) Start with [localization.md](localization.md) (authority, integration rules, open decisions, third-pass decisions), then [localization-tables.md](localization-tables.md) (generated from `source/locale-spec.js`), [localization-corrections.md](localization-corrections.md) (what the corrections pass rendered and left open) and [localization-changelog.md](localization-changelog.md) (state IDs and copy changed by the third pass). States are indexed in `states.md` and `screens/localization-*.md` (8 files, 183 states in 16 groups; L6 and L9 are release 2). The Articles list pixel gate is group L7s (single-language site) and L7 (several languages), not the Back-office Articles groups. References: `source/RenewCMS Screens Localization.dc.html`, `LocaleFrame.dc.html` (drawn inside the shared `AppFrame`), `locale-spec.js` and `locale-fixtures.js`. The LocaleLive prototype was not imported, and the Prototype board does not demonstrate localization.
1. Activity export dialog: removed the 42% progress bar, the "large export" state, the server-job copy and the "ready later" toast; added "Preparing download…" (indeterminate), "Download started", failed, nothing to export, 403; CSV only, with one proposed JSON state.
2. Export dialog and menu copy now match the implemented endpoint (current view with filters, all with optional range).
3. Articles pagination used `per_page`, sizes 10/25/50, default 10, 32 pages. Now `page`/`size`, 5/25/50/100, default 25, 13 pages; frames, route, URL examples and the change list updated.
4. The Integration responses table now shows both 400 bodies, `unknown_variant` and `unsupported_parameter`.
5. `--rc-sand` and `--rc-on-sand` (and the other `--rc-*` tokens) documented as new tokens with light and dark values and their uses.
6. Raw colours removed from frames: crop handles and mask, tooltip, transparency checker, drag-drop text, selected-row text in MediaFrame, hex in the Prototype. Only the brand mark keeps hex.
7. ActivityFrame, MediaFrame and VariantsFrame sidebars, topbars and (Variants) mobile drawer deleted; they render inside AppFrame. Activity now follows the sidebar order (Users, Activity, Integration, Settings).
8. Prototype's own mobile drawer (Home, Articles, Users, Integration only) replaced by AppFrame's drawer.
9. All code blocks on Integration (auth example, endpoint examples, error response), the base URL, the image URL builder and the one-time API key use CodeSnippet; the three older block styles are gone. CodeSnippet tabs changed from sand pills to the underline style used by tabs elsewhere.
10. Variant form: mobile full page replaced by a 92% bottom sheet with grabber and close ×; back arrow removed.
11. Dialog geometry unified (140 px top offset on desktop, flush bottom sheets with grabber on mobile, header 20 24 0, footer secondary left and primary right, close × 44 px on mobile). Changed: Media and Variants dialogs (mobile inset), Activity export (centered, header bar, 480 wide), API keys dialogs (border, 18 px title, 44 px buttons, 120 px offset).
12. Current page in the paginator: border `--ui-primary` instead of sand (was 1.3:1).
13. Page padding 24/16 everywhere (was 32 and 24); card padding 16 (was 16 and 20); section gap 16 (was 16, 20, 28); page title 20/28 (was 28/36, 24/32, 20/28); stat figure 24/32; card title 15/24; inputs 32/44 (were 40); one 13 px icon became 14; toast width 356 (was 360, 372).
14. Copy: "Removed N …" in activity lines became "Deleted N …"; export titles and footers per the glossary.
15. Media screen: variant count badge added to grid card, list row and mobile row, matching the Variants board.
16. Editor toolbar on mobile was a cut-down 9-button subset; it now has the full toolbar with sideways scroll and edge fades.
17. Editor words and characters show "0 words · 0 characters" for a new empty article (was a fallback sample count).
## Defaults chosen
- Slide-over rule: only forms with a live preview and record details; on mobile always a 92% bottom sheet.
- Hover, active, disabled and focus tokens for the matrix (components not specified before): primary hover `--ui-text`, active `--ui-text-toned`; destructive hover opacity 0.85 and active 0.75; disabled 40% (rows 55%).
- Article pagination: API shape (array body, total in `X-Total-Count`) is a design assumption to confirm with the specifier.
- The Remove action in the link popover has no confirmation; undo restores the link.
- The link button is disabled when an image is selected.
- The tooltip text is "Insert link (Ctrl+K)" and "Insert link (⌘K)" on macOS.
- Mobile toolbar scrolls sideways; no wrap, no overflow menu.
- Selected nav items keep the sand fill plus weight 500 and `aria-current` (the fill alone is 1.3:1 in light).
- Syntax colouring dropped from code samples (one rendering).
- Export "Download started" offers only Close.
- New article keeps the title counter "n / 200" (title is limited to 200); the body has no limit and no counter.
- Page title 20/28, page padding 24/16, card padding 16 (foundations.md).
- Activity position in the sidebar follows AppFrame.
- The Prototype shows a toast "Not in this prototype" for sidebar items it has no screen for (Media, Activity, Settings).
## Checks run
- Opened `RenewCMS Screens Back-office.dc.html` in the preview: it loaded, 38 sections rendered, and I read the DOM of the Activity, Export, Media, Variants, Editor, Integration, Pagination, Picker, Editor picker and States matrix groups to confirm the frames render text and the sidebar. I did not read the console.
- Computed the contrast table from token values with a script.
- Searched frames and boards for raw hex and rgb values (only token definitions on the board roots and the brand mark remain), for exclamation marks, Remove and Delete, Update and Save, and per_page.
- Generated screens/*.md and counted states from the board source; the counts equal the DOM counts for the Back-office board.
## Not done
- Console errors on the Auth, API keys, Prototype, Foundations and Components boards were not read by me. The delivery check covers the Back-office board; the other boards use the changed frames (AppFrame, ApiKeysPage, AuthCard, MediaFrame) and may need a look.
- Light and dark were checked for the Back-office board by reading DOM only; I did not view the screenshots of each state at 1440 and 390, so visual regressions from the shell change (slot mode) are possible.
- Media screen: the "With variants / Without" filter, the "Largest total size" sort and a total-size column exist only on the Variants board states; they are not folded into the Media toolbar.
- Media picker tiles and the Editor picker were not compared field by field.
- Duplicated implementations that look alike are not merged in code: toasts (5), badges (2), empty states (2), modal shells (4). Only their visuals were aligned.
- Hover, active and focus-visible are drawn once in the matrix; screens do not redraw them. Hover and active tokens for destructive buttons use opacity, not a token.
- Contrast was not computed for every hover and active background, only the pairs listed in foundations.md.
- The glossary pass was a search for known patterns, not a line-by-line read of every string. Titles in Title Case were not searched.
- The Components, Handoff and Foundations boards were not updated to mention the new tokens, CodeSnippet or the matrix.
- Integration still lists "max 10000" for article bodies, as the backend does today (change-list item 11).
- The sandbox cannot export; no files were bundled.
-93
View File
@@ -1,93 +0,0 @@
# Change list for implementation (status after pass 2; SEO round drawn; cleanup round drawn)
## Cleanup round
1. Editor: site and authors, "Create author" states (4 states, desktop and mobile): the mobile dialog sat under the Details sheet (z-index 50 against 55) and was hidden. It now stacks above the sheet (z-index 60), as the SEO panel does. Full-width bottom sheet with grabber, same fields, Cancel left and "Create author" right (Cancel below on mobile, as the other mobile dialogs). Frame: `DirectoryFrame.dc.html`. The four states share the fix: dialog, "for me", slug taken, failed.
2. Integration, "6. Errors": the 403 row gets the muted note "Site SEO defaults are owner only. Article SEO fields need only the right to edit the article." The row below shifts down by the wrapped note height (two 18 px lines desktop, three mobile, plus the 2 px row gap). The old inline parenthetical with the same sentence in the 403 cause text was removed, so it isn't said twice. Frame: `IntegrationPage.dc.html`.
3. Integration, sitemap errors: 404 now shows the body `site_not_found` in code style (was "Site not found"); 400 now shows the generic body-mismatch text used by the other routes (was "Invalid page or size.").
4. New groups on the Back-office board: "Sites: pagination" and "Authors: pagination", 10 states each (20 states, every one desktop and mobile; light and dark by the theme switch). Back-office total 409 → 429. Same pager as Articles and Media, sizes 5, 25, 50, 100, default 25 (no difference to report). One deviation: on a single page the page-size select is hidden and only "N sites" or "N authors" remains.
5. Specs: screens/sites.md, screens/authors.md (pager states, URL rules, out-of-range fallback), screens/integration.md, states.md (pagination states, three HTTP rows), components.md (single-page variant, no new component), routes.md (Sites pagination in the URL).
**Backend assumptions to confirm.** GET /v1/site/ takes `q`, `page`, `size` and returns `X-Total-Count` (it returns every site today). GET /v1/author/ gets `page`, `size` and `X-Total-Count` (it has `q`).
**Open points.**
- Sites has no search field. The two states that need one (empty after search, search resets to page 1) draw the Authors field on Sites with "Search by name or key". Drop those states if you don't want search on Sites.
- Stale copy found, not changed: GET /v1/article/ on Integration still shows the 400 caption "Invalid page or size." while every other route, and now the sitemap, uses the body-mismatch text. The 404 row of the Errors table still lists only the four resource messages and doesn't mention `site_not_found`. The existing Sites and Authors "Default" frames don't draw the count line. README.md state counts and the "Pagination" notes were not updated (outside this round).
## SEO round: decisions (frames drawn)
**Placement.** A "Search and sharing" section sits under "Site and authors" in the Editor sidebar and in the mobile Details sheet. It is collapsed by default, shows a one-line summary ("Ready", "2 suggestions" or "Hidden from search") and is remembered per browser like Site and authors. It holds only the slug, the full URL and three actions: "Edit search and sharing", "What the frontend gets" and the suggestion list. The fields and live previews open in a slide-over (desktop) or a 92% bottom sheet stacked over the Details sheet (mobile), because the 280 px sidebar is too narrow for previews and the slide-over rule already covers forms with a live preview. The API preview is a 720 px dialog (desktop) or a bottom sheet (mobile).
**Principles.** RenewCMS does not render pages or inject meta tags. Every field is optional and the UI shows its fallback. No scores. Suggestions never block saving or publishing; publishing is allowed regardless. Suggestions are dismissible per article.
**Fallback chain (resolved server-side, shown in the UI).**
| Output | Order |
|---|---|
| title | seo_title, then article title; site title_template applied last |
| description | seo_description, then excerpt, then first sentence of the body, then site default_description |
| image | og_image_id, then cover_image_id, then site social image |
| canonical | canonical_url, then site base_url + "/" + slug |
| robots | noindex true gives "noindex, nofollow"; otherwise site default_robots |
| og/twitter title and description | social_title, social_description, then the resolved values above |
**Soft ranges (counters, never blocks).** Meta title 30–60 characters; description 70–160; slug "very long" above 75 characters. Counter turns neutral-warning (`--ui-warning`) outside the range, never red.
**New article fields (PATCH /v1/article/{id}, all optional, snake_case).** `slug`, `excerpt` (max 300), `seo_title` (max 120), `seo_description` (max 320), `cover_image_id`, `cover_image_alt` (max 200; the cover is "ready" only with alt text), `social_title`, `social_description`, `social_image_id`, `canonical_url` (absolute https URL), `noindex` (boolean; only sets a flag in the API, it doesn't change visibility), `seo_dismissed` (string[] of suggestion codes). Slug: lowercase letters, numbers, hyphens; unique per site; 409 `slug_taken` with `suggestion` ("<slug>-2"); auto-generated from the title until edited.
**New site fields (PATCH /v1/site/{id}, owner only).** `site_name`, `title_template` (default "%title% | %site%", must contain %title%), `default_description` (max 320), `social_image_id` (existing), `default_robots` ("index" | "noindex"; existing as robots).
**New endpoints.**
- `GET /v1/article/{id}/seo`: resolved object, public for online articles, 404 for drafts to anonymous callers. Shape: `{ title, description, canonical_url, robots, og: { type, title, description, image, image_alt, url, site_name, locale }, twitter: { card, title, description, image, image_alt }, image: { url, alt, source }, authors: [{ name, url, same_as: [] }], published_at, modified_at, fallbacks: { title, description, image, canonical }, json_ld }`. `json_ld` is a ready Article object (headline, description, image, author[] with name, url and sameAs from author profile URL and social links, datePublished, dateModified, mainEntityOfPage).
- `GET /v1/site/{key}/sitemap?page=&size=`: published URLs only, total in `X-Total-Count`. Items: `{ url, modified_at, noindex }`. Decision: yes, shown on Integration under "Search and sharing" with a copy button; noindex articles are included with the flag so the frontend can skip them.
- `GET /v1/article/?seo=ready|suggestions|hidden`: filter behind "Needs attention" (suggestions) with `seo_status` and `seo_suggestions` (count) added to list items.
**Articles list.** Quiet indicator inside the Status cell (and under the title on mobile cards): nothing when ready, a lightbulb chip "N" for suggestions, an eye-off chip "Hidden" for noindex. Toolbar gets a "Needs attention" toggle next to search; tabs and counts are unchanged. It behaves the same on a single-site install (independent of the Site filter, which stays hidden).
**Authors.** No change to the Authors screen. Profile URL (website) and social links feed `authors[].url` and `same_as`, and JSON-LD `author[].sameAs`; the API preview shows them.
**Permissions.** Anyone who can edit an article edits its SEO fields. Only the owner edits site SEO defaults. 401 and 403 rows join the existing HTTP table: 403 `owner_only` on Site SEO fields, 401 on a missing session.
**Left out on purpose.** Keyword scoring and focus keywords, readability scores, redirects management, schema types beyond Article, hreflang, robots.txt and sitemap rendering (RenewCMS only provides data), automatic image generation for social cards.
**Open questions.**
1. Is `slug` immutable after first publish, or can it change (and break URLs with no redirects)?
2. Does the API return the SEO object for drafts to authenticated callers (for frontend previews)?
3. Should noindex articles be excluded from the sitemap endpoint instead of flagged?
4. Is title_template applied by the API (resolved title) or only returned for the frontend to apply?
5. Backfill: generate slugs for existing articles from their titles at migration, with `-2` suffixes on conflicts?
6. Should excerpt be exposed in the list payload as the article teaser?
**Status.** Frames drawn on the Back-office board (groups: Articles: search status, Editor: search and sharing, Editor: what the frontend gets, Sites: SEO defaults), Integration page group added, specs updated. Placement rationale: the sidebar holds only the summary, address and suggestions because it is 280 px wide; previews and fields need a slide-over.
Ordered by implementation dependency: tokens and shell first, then shared components, then screens. "Frontend only" means no backend work is needed.
| # | Screen | Change | Done in design? | Needs backend (yes/no, what) | Needs new tokens or components | Frontend only |
|---|---|---|---|---|---|---|
| 1 | All | Add the `--rc-*` tokens (sand, on-sand, four soft grounds, overlay, two shadows) to the app CSS, light and dark (foundations.md) | Yes | No | 9 new tokens | Yes |
| 2 | All | One sidebar, topbar and mobile drawer; Settings parent and child selected states; Activity sits between Users and Integration | Yes | No | NavItem, NavGroup | Yes |
| 3 | All | Overlay pattern: dialog (desktop) and bottom sheet (mobile); slide-over only for the variant form and record details; footer secondary left, primary right | Yes | No | Modal wrapper rules (components.md) | Yes |
| 4 | All | CodeSnippet is the only code block (Integration, Images, API keys, base URL, image URL) | Yes | No | CodeSnippet | Yes |
| 5 | All | Copy glossary pass (Delete vs Remove, Save vs Update, toast phrasing) | Yes, by search; not every line re-read | No | None | Yes |
| 6 | Settings | "Media" card with "Manage image variants" and "Cache usage" | Yes | No | MediaLinksCard | Yes |
| 7 | Media, picker | Variant count badge on grid, list and mobile rows | Yes | No (variant counts already come with GET /v1/media?variants=) | Badge "N variants" | Yes |
| 8 | Media | "With variants / Without" filter and "Largest total size" sort in the Media toolbar | Drawn on the Variants board only, not folded into the Media screen | No (GET /v1/media?variants=&sort=total_size exists) | None | Yes |
| 9 | Image variants | Variant form as slide-over (desktop) and tall sheet (mobile) | Yes | No | None | Yes |
| 10 | New article | Title only. Body removed from the modal; the editor opens straight away | Yes | Maybe: confirm `POST /v1/article/` accepts an empty `body` (it is "required" today); otherwise the frontend sends an empty string | NewArticleModal | Yes if empty body is accepted |
| 11 | Editor | Remove the 10,000 character limit, counter, limit and over-limit states; neutral count | Yes | Yes: remove the body length validation on `POST /v1/article/` and `PATCH /v1/article/{id}` | EditorStatusBar | No |
| 12 | Editor | Insert-link button (default, hover, active, disabled), tooltip, LinkModal, link popover and touch sheet, rendered link, toolbar scrolling at 390 px | Yes | No (editor only) | LinkModal, LinkPopover, ToolbarButton | Yes |
| 13 | Articles | Pagination with `page` and `size` (5, 25, 50, 100; default 25), URL state, loading, error, out of range | Yes | **Yes:** `page`, `size` on `GET /v1/article/` (same convention and 400 as Activity); total in `X-Total-Count`, array body unchanged; Integration reference updated | Paginator, PageSizeSelect | No |
| 13b | Media | Pagination under the grid and list, same Paginator and PageSizeSelect as Articles; `page` and `size` in the URL; saved size preference | Yes (9 states in the Media group) | **Yes:** `page`, `size` on `GET /v1/media/` (replaces `cursor` and `limit`); total in `X-Total-Count`, array body unchanged; Integration reference | None (reuses Paginator, PageSizeSelect) | No |
| 14 | Activity | Failed-action and security cards as toggles, synced chip and segment | Yes | No | FilterCardToggle | Yes |
| 15 | Activity | Export menu and dialog, CSV: current view (active filters) and all activity (no filters, optional `from`/`to`). Preparing, started, failed, nothing to export, 403 | Yes | No: `GET /v1/activity/export` is implemented (CSV, synchronous, owner and admin, same filters as the list) | ExportMenu, ExportDialog | Yes |
| 16 | Activity | JSON export (format control CSV or JSON) | Yes, one state, labelled proposed | **Yes (proposed):** `format=json` on `GET /v1/activity/export` | Segmented format control | No |
| 17 | Integration | Images and variants section, URL builder, response bodies `unknown_variant` and `unsupported_parameter` | Yes | No | UrlBuilder | Yes |
| 18 | All | States matrix for controls (hover, focus-visible, active, disabled) | Yes (board "States matrix: controls") | No | None | Yes |
| 19 | All | Contrast fixes: paginator current page border, no muted text on sand | Yes | No | None | Yes |
| 20 | All | Spacing, type and icon sizes made consistent (foundations.md, "One value per role") | Yes in the frames listed there | No | None | Yes |
| 21 | Settings, sidebar | Sites screen under Settings → Sites ("Publishing" group); "Publishing" card on Settings. Owner only: hidden for other roles, 403 page on a direct link. Key immutable after creation | Yes | **Yes:** `site` table, GET/POST/PATCH/DELETE /v1/site/ (writes owner only; PATCH rejects a changed key), `reassign_to`, seed from PUBLIC_URL | SitesTable, SiteForm, SlugField (locked variant), ReassignDialog | No |
| 22 | Sidebar | Authors entry between Media and Users, all roles. Owner and admin manage; other roles read-only list and detail | Yes | **Yes:** `author` table, GET /v1/author/ (any role), POST/PATCH/DELETE (owner and admin; a user may PATCH their own linked author), POST /v1/author/me (any role) | AuthorsTable, AuthorForm, SocialLinksRepeater, MediaField | No |
| 23 | Editor | "Site and authors" section in every Editor frame (collapsed by default): Site select (any role that can edit the article), reorderable authors, inline create (owner and admin), hint | Yes | **Yes:** `site_id`, `author_ids[]` on PATCH /v1/article/{id} | MetaSection, AuthorList, AuthorSelect, SiteSelect, CreateAuthorHint | No |
| 24 | Articles | Authors column; Site column and filter when more than one site | Yes | **Yes:** `site` filter, `site` and `authors` in the list payload | AuthorStack | No |
| 25 | Profile | "Author profile" card in every Profile frame, one-click create, edit own author (user link locked) | Yes | **Yes:** POST /v1/author/me | AuthorProfileCard | No |
| 26 | Backfill | Existing articles get the default site; authors start empty | n/a | **Yes:** migration | None | No |
+80 -3
View File
@@ -27,13 +27,14 @@ One component for every code or copyable value. Props: `tabs` (`{ k, label, code
## Editor: link ## Editor: link
- **Toolbar button** (icon `link`, after the list buttons): default `--ui-text-toned`; hover `--ui-bg-elevated` with tooltip "Insert link (Ctrl+K)" (macOS: "Insert link (⌘K)"); focus-visible 2 px `--ui-primary` outline; active when the cursor is inside a link (`aria-pressed`, `--rc-sand` and `--rc-on-sand`); disabled at 40% opacity when an image is selected. 28 px desktop, 40 px mobile. - **Toolbar button** (icon `link`, after the list buttons): default `--ui-text-toned`; hover `--ui-bg-elevated` with tooltip "Insert link (Ctrl+K)" (macOS: "Insert link (⌘K)"); focus-visible 2 px `--ui-primary` outline; active when the cursor is inside a link (`aria-pressed`, `--rc-sand` and `--rc-on-sand`); disabled at 40% opacity when an image is selected. 28 px desktop, 40 px mobile.
- **LinkModal**: dialog on desktop, bottom sheet on mobile. Fields "Link text" (prefilled from the selection), "URL" (http, https, mailto, relative path, #anchor), toggle "Open in new tab". Footer: Cancel left, "Insert link" or "Save link" right; "Remove link" as a text button in edit mode. Errors: "Enter the link text." and "Enter a valid URL. Use http(s), mailto, a path or #anchor." - **LinkModal**: dialog on desktop, bottom sheet on mobile. Fields "Link text" (prefilled from the selection), "URL" (http, https, mailto, relative path, #anchor), toggle "Open in new tab". Footer: Cancel left, "Insert link" or "Save link" right; "Remove link" as a text button in edit mode. Errors: "Enter the link text." and "Enter a valid URL. Use http(s), mailto, a path or #anchor." Helper text under the toggle: "Links open in the same tab unless you turn on a new tab."
- **Link popover** (desktop): under the link, 288 px, URL in mono on top, then "Edit", "Open", "Remove" (error colour). Opens on click or Enter on a focused link; Esc closes. **Touch**: bottom sheet with the link text, the URL and three 48 px rows "Edit link", "Open link", "Remove link". Remove needs no confirmation (undo restores). - **Link popover** (desktop): under the link, 288 px, URL in mono on top, then "Edit", "Open", "Remove" (error colour). Opens on click or Enter on a focused link; Esc closes. **Touch**: bottom sheet with the link text, the URL and three 48 px rows "Edit link", "Open link", "Remove link". Remove needs no confirmation (undo restores).
- **Rendered link**: `--ui-text-highlighted`, 1 px underline, 3 px offset. Hover 2 px underline. Focus 2 px `--ui-primary` outline, offset 2. Selected: `--rc-sand` fill, `--rc-on-sand` text. - **Rendered link**: `--ui-text-highlighted`, 1 px underline, 3 px offset. Hover 2 px underline. Focus 2 px `--ui-primary` outline, offset 2. Selected: `--rc-sand` fill, `--rc-on-sand` text.
- **Toolbar at 390 px**: the full toolbar (22 buttons) does not fit. It scrolls sideways in one row, never wraps; a 24 px fade (`--ui-bg` to transparent) marks hidden content on each side. Buttons stay 40 px. - **Toolbar at 390 px**: the full toolbar (22 buttons) does not fit. It scrolls sideways in one row, never wraps; a 24 px fade (`--ui-bg` to transparent) marks hidden content on each side. Buttons stay 40 px.
## Paginator ## Paginator (AppPaginator)
First, previous, page numbers, next, last; "Showing 26–50 of 312"; page-size select "5 per page", "25 per page", "50 per page", "100 per page" (default 25). Mobile: previous, "Page 2 of 13", next. Hidden when there is one page. Desktop layout, one row: the summary on the left (it takes the free space), the page-size select next to it, the page controls right-aligned; Sites, Authors, Articles and Media draw it the same way. Buttons 32 px (44 px mobile), current page `--rc-sand` with `--ui-primary` border, disabled controls 40% opacity, focus ring 2 px `--ui-primary`. Page size and page live in the URL as `size` and `page`. Shipped as `AppPaginator`; every list board (Articles, Activity, Media, Authors, Sites, Localization list) draws this one. Desktop: summary "Showing 1–5 of 8" (flex 1), page-size select, then first, previous, numbers, next, last. 390 px: summary and select on one row, then Previous, "Page N of M", Next at 44 px. The summary and select stay when there is one page; only the buttons hide.
First, previous, page numbers, next, last; "Showing 26–50 of 312"; page-size select "5 per page", "25 per page", "50 per page", "100 per page" (default 25). Mobile: previous, "Page 2 of 13", next. Buttons 32 px (44 px mobile), current page `--rc-sand` with `--ui-primary` border, disabled controls 40% opacity, focus ring 2 px `--ui-primary`. Page size and page live in the URL as `size` and `page`.
Variant for Sites and Authors (no new component): when everything fits on one page the page-size select is hidden together with the controls and the footer shows only the count line "N sites" or "N authors" in `--ui-text-muted`. Loading dims the whole pager to 40% and disables it; the summary reads "Loading page N…". Sizes are unchanged: 5, 25, 50, 100. Variant for Sites and Authors (no new component): when everything fits on one page the page-size select is hidden together with the controls and the footer shows only the count line "N sites" or "N authors" in `--ui-text-muted`. Loading dims the whole pager to 40% and disables it; the summary reads "Loading page N…". Sizes are unchanged: 5, 25, 50, 100.
@@ -121,3 +122,79 @@ 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.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 |
## Roles and permissions (new)
| Component | Used for | Nuxt UI mapping |
|---|---|---|
| ScopeControl (tri-state) | None / Own / All in grid cells, mobile cards and general rows | URadioGroup variant="table" orientation="horizontal" size="xs", three items, in a grid cell. Selected item: sand fill, weight 600 and an underline |
| OnOffCell | Create column and boolean rows | USwitch with visible On/Off label |
| PermissionGrid | Content permissions | Custom grid (role="grid") of ScopeControl cells; header buttons use UDropdownMenu for bulk actions |
| PresetPills | Read only, Write own, Full content | UButton variant="outline" size="xs", pressed state via aria-pressed |
| PermissionGroup | Collapsible group with "x of y enabled" | UCollapsible; header UButton variant="ghost" |
| OwnerOnlyTag | Locked owner-only items | UBadge variant="subtle" with lucide lock icon |
| RoleBadge | Users, roles, API keys | UBadge variant="outline" with role icon (crown, shield, pencil, user-round) |
| RolePreview | What this role can do | Card on desktop (UCard), USlideover side="bottom" on mobile |
| RolePicker | Change role, invite, reassign on delete | URadioGroup variant="card" with description; USelectMenu for the reassign field; items disabled with a reason in description |
| SaveBar | Unsaved changes | Sticky container with UButton color="neutral" variant="outline" and UButton color="primary" |
| ReadOnlyBanner | Read-only pages | UAlert color="info" icon="i-lucide-lock" variant="soft" |
| ViewOnlyMark | Own scope rows | Text with lucide lock icon and UTooltip |
Accessibility of the tri-state cell:
| Item | Pattern |
|---|---|
| Structure | The grid is role="grid". Each cell contains a role="radiogroup" named "{Type}: {Action}" (for example "Events: Update") with three role="radio" items None, Own, All. Create is a role="switch" named "Events: Create". |
| Keyboard | Tab moves between cells (one stop per cell). Inside a group, Left and Right (or Up and Down) move and select, Home and End jump to None and All. Arrow keys also move the roving tabindex. Space selects. Header bulk buttons open a menu with the same three values. |
| Announcement | Selected item is aria-checked="true". A polite live region announces changes: "Events, Update, set to Own." Disabled items are aria-disabled and described by the reason ("You can only grant what your role has."). |
| Not by color alone | Selected segment: sand fill plus weight 600 plus a 2 px underline in --ui-primary. Locked: lock icon. Changed cell: square marker. Mixed: text badge. |
| Targets | 26 px segments on desktop, 44 px on mobile. Focus: 2 px --ui-primary outline, offset 2 px. |
## Account (change email, export, delete)
| Component | Status | Nuxt UI mapping | Where |
|---|---|---|---|
| EmailChangeForm | New | UFormField + UInput (email, password) + UButton, inside the Account UCard | Profile |
| PendingEmailNotice | New | UAlert (info) + two UButton (outline) | Profile |
| DataExportCard | New | UCard + UButton; notices as UAlert | Profile |
| DangerZoneCard | New | UCard with border var(--ui-error), UButton color error | Profile |
| DeleteAccountDialog | New | UModal (existing destructive ConfirmDialog shell) + UInput x2 + list + UAlert info + ULink | Profile |
| BlockedDialog | New | UModal with dismissible false, no close button; UButton primary for the next step | Profile |
Specs: field heights 40 (44 mobile), buttons 36 (44 mobile), card padding 16, section gap 16. Colors from tokens only. Destructive confirm is disabled at 40% opacity until valid. Implemented in AccountCards.dc.html and the AppFrame modal.
## Localization components (spec)
| Component | Built from (Nuxt UI v4) | Notes |
|---|---|---|
| LanguageMenu | UDropdownMenu with a UButton trigger | Menu button with menu; rows carry badges and a Read only tag; no Add translation row without create permission |
| CapabilityGate | none (logic) | Renders each action from capabilities[]; never from the role name |
| EditorHeader | UButton, UBadge, UDropdownMenu | One row on desktop: language, badges, title, actions (title fills the remaining width). On mobile the title sits above the badges. At most one filled button. Collapse order and mobile bottom bar in the header priority table |
| TitleInput | UInput (heading size) | Underline field, no box. Accessible name "Title (French)", no visible label; bounds 3 to 200; counter; helper under the field only while editing |
| ActionOverflow | UDropdownMenu (desktop), UDrawer (mobile) | Disabled items carry a visible reason |
| StatusBadge | UBadge variant soft | Publication: solid icon plus word |
| FreshnessBadge | UBadge variant outline | Refresh icon plus word; icon-only at 1024 with aria-label |
| SourcePane | UCard | Read-only reference with own scroll and dir/lang. Dashed outline and "Temporary reference" tag |
| TrackedSourceBadge | UBadge variant soft color info | Distinct from the temporary reference |
| ConflictDialog | UModal (desktop), UDrawer (mobile) | Four options; Keep my changes is the only filled button. Save over theirs is outlined in `--ui-error` with a triangle-alert icon (destructive cue, same size as the other secondary buttons) |
| CoverageChips | UBadge variant outline | Collapse after 5 (1440) or 4 (1024, 390) with a +N chip; dashed for missing |
| ListFilters | USelectMenu, UInput, UDrawer on mobile | Language filter groups Enabled and Disabled |
| UnitLabel | plain text, aria-live polite | "8 articles", "4 French versions", "4 articles not in French" |
| RowMenu | UDropdownMenu / UDrawer | Same actions on every width |
| SocialLocaleField | UInput, UBadge | Derived, Set, Not set |
| PublicUrlPattern | UInput, UAlert | Live preview from a real article, validation messages |
| MoveArticlePanel | USelectMenu, UModal | Note lists readable versions only |
## Localization board additions
- Sidebar: no Languages item. Languages lives under Settings → Sites → [site]. Nothing is added to `navItems`.
- Toast icon box: 28 × 28 px, 16 px icon, tone colour on its `-soft` ground (`--rc-success-soft`, `--rc-info-soft`, `--rc-warning-soft`, `--rc-error-soft`).
- Slide-over panel (Search and sharing, Media detail): desktop right-aligned over `--rc-overlay`, 960 px (Media detail 420 px), full height, header 16 24, close button; 390 px: bottom sheet at 92% height. Drawn inside the AppFrame shell, never free-standing.
- Coverage chip overflow (+N): 22 px chip; at 390 px its tap area is 44 px high.
- Language menu rows: a disabled-language version shows a Disabled tag and the footer explains publishing is off.
- Destructive outline button: `--ui-error` text and border on `--ui-bg`, used only for Save over theirs.
+117
View File
@@ -0,0 +1,117 @@
# Design decisions
Product and interface decisions that outlive the design passes. Behaviour comes from `features/`; where the two disagree, stop and ask. Screen copy and states are in `screens/*.md`, `states.md` and `routes.md`.
## Search and sharing (SEO)
### Interface
**Placement.** A "Search and sharing" section sits under "Site and authors" in the Editor sidebar and in the mobile Details sheet. It is collapsed by default, shows a one-line summary ("Ready", "2 suggestions" or "Hidden from search") and is remembered per browser like Site and authors. It holds only the slug, the full URL and three actions: "Edit search and sharing", "What the frontend gets" and the suggestion list. The fields and live previews open in a slide-over (desktop) or a 92% bottom sheet stacked over the Details sheet (mobile), because the 280 px sidebar is too narrow for previews and the slide-over rule already covers forms with a live preview. The API preview is a 720 px dialog (desktop) or a bottom sheet (mobile).
**Principles.** RenewCMS does not render pages or inject meta tags. Every field is optional and the UI shows its fallback. No scores. Suggestions never block saving or publishing; publishing is allowed regardless. Suggestions are dismissible per article.
**Fallback chain (resolved server-side, shown in the UI).**
| Output | Order |
|---|---|
| title | seo_title, then article title; site title_template applied last |
| description | seo_description, then excerpt, then first sentence of the body, then site default_description |
| image | og_image_id, then cover_image_id, then site social image |
| canonical | canonical_url, then site base_url + "/" + slug |
| robots | noindex true gives "noindex, nofollow"; otherwise site default_robots |
| og/twitter title and description | social_title, social_description, then the resolved values above |
**Soft ranges (counters, never blocks).** Meta title 30–60 characters; description 70–160; slug "very long" above 75 characters. Counter turns neutral-warning (`--ui-warning`) outside the range, never red.
**New article fields (PATCH /v1/article/{id}, all optional, snake_case).** `slug`, `excerpt` (max 300), `seo_title` (max 120), `seo_description` (max 320), `cover_image_id`, `cover_image_alt` (max 200; the cover is "ready" only with alt text), `social_title`, `social_description`, `social_image_id`, `canonical_url` (absolute https URL), `noindex` (boolean; only sets a flag in the API, it doesn't change visibility), `seo_dismissed` (string[] of suggestion codes). Slug: lowercase letters, numbers, hyphens; unique per site; 409 `slug_taken` with `suggestion` ("<slug>-2"); auto-generated from the title until edited.
**New site fields (PATCH /v1/site/{id}, owner only).** `site_name`, `title_template` (default "%title% | %site%", must contain %title%), `default_description` (max 320), `social_image_id` (existing), `default_robots` ("index" | "noindex"; existing as robots).
**New endpoints.**
- `GET /v1/article/{id}/seo`: resolved object, public for online articles, 404 for drafts to anonymous callers. Shape: `{ title, description, canonical_url, robots, og: { type, title, description, image, image_alt, url, site_name, locale }, twitter: { card, title, description, image, image_alt }, image: { url, alt, source }, authors: [{ name, url, same_as: [] }], published_at, modified_at, fallbacks: { title, description, image, canonical }, json_ld }`. `json_ld` is a ready Article object (headline, description, image, author[] with name, url and sameAs from author profile URL and social links, datePublished, dateModified, mainEntityOfPage).
- `GET /v1/site/{key}/sitemap?page=&size=`: published URLs only, total in `X-Total-Count`. Items: `{ url, modified_at, noindex }`. Decision: yes, shown on Integration under "Search and sharing" with a copy button; noindex articles are included with the flag so the frontend can skip them.
- `GET /v1/article/?seo=ready|suggestions|hidden`: filter behind "Needs attention" (suggestions) with `seo_status` and `seo_suggestions` (count) added to list items.
**Articles list.** Quiet indicator inside the Status cell (and under the title on mobile cards): nothing when ready, a lightbulb chip "N" for suggestions, an eye-off chip "Hidden" for noindex. Toolbar gets a "Needs attention" toggle next to search; tabs and counts are unchanged. It behaves the same on a single-site install (independent of the Site filter, which stays hidden).
**Authors.** No change to the Authors screen. Profile URL (website) and social links feed `authors[].url` and `same_as`, and JSON-LD `author[].sameAs`; the API preview shows them.
**Permissions.** Anyone who can edit an article edits its SEO fields. Only the owner edits site SEO defaults. 401 and 403 rows join the existing HTTP table: 403 `owner_only` on Site SEO fields, 401 on a missing session.
**Left out on purpose.** Keyword scoring and focus keywords, readability scores, redirects management, schema types beyond Article, hreflang, robots.txt and sitemap rendering (RenewCMS only provides data), automatic image generation for social cards.
### Decisions
| # | Question | Decision |
| --- | --- | --- |
| 1 | Is `slug` immutable after publication? | No. It stays editable. RenewCMS does not manage redirects, so the frontend owns them. No extra warning copy is added to the design. |
| 2 | SEO object for drafts | `GET /v1/article/{id}/seo` answers drafts to authenticated callers who can read the article, and 404 to anonymous callers. The editor preview needs it. |
| 3 | Noindex in the sitemap | Included with `noindex: true`, as drawn. The frontend decides. |
| 4 | Who applies `title_template` | The API. `title` in the SEO object is resolved. The raw `seo_title` and the site template stay readable on their own routes. |
| 5 | Backfill | Migration generates a slug for every existing article from its title (same slug rule as authors), unique per site, with `-2`, `-3` suffixes. A title with no letter or digit becomes `article`, then `article-2`, `article-3`. It runs once and is idempotent. |
| 6 | Excerpt in the list payload | Yes. Article items carry `excerpt`. |
### Implicit decisions
- Suggestions come from one server-side rule set. The same function feeds `seo_status` and `seo_suggestions` in the article list, the collapsed section summary, and the editor panel.
- The editor panel's "checking" states and the "slug taken" state use one non-persisting endpoint: `POST /v1/article/{id}/seo/check`. Its body takes the same optional SEO fields as `PATCH /v1/article/{id}`, plus an optional `body` (never `site_id` or `author_ids`), and overrides the saved values for the check only. It answers `{ status, suggestions: [{ code, field, params }], slug: { available, suggestion } }`. Copy for each code lives in the SPA, with a French entry. `seo_dismissed` codes are filtered out of `suggestions` and are never counted in the list.
- The suggestion codes are the ones the board uses: `title_long`, `title_empty`, `desc_short`, `desc_long`, `cover_alt`, `cover_none`, `slug_long`, `no_au`, `no_h`, `body_alt`, `short`.
- Cover, social and site social images are media usages: `GET /media/{id}/usage`, `used_in`, the unused filter, merge, purge and delete protection must count them. This also closes the existing gap where author avatars and site social images are missing from `GET /media/{id}/usage`.
- Roles: anyone who can edit an article edits its SEO fields and runs the check. Only the owner edits site SEO fields (403 "Only the owner can do this."). `GET /v1/site/{key}/sitemap` is public, like the other read routes that serve online articles. SEO edits are logged as an `articles` event; no field values or body text are stored.
- `PATCH /v1/article/{id}` still requires at least one known field and still answers 400 on `null`. The SEO fields join `body`, `site_id` and `author_ids`.
## Sites and authors
### Who can do what
| Action | Owner | Admin | Other roles |
|---|---|---|---|
| Create, edit, set default, delete a site | yes | no | no |
| Read the site list, choose an article's site | yes | yes | yes, if they can edit the article |
| Create, edit, delete any author | yes | yes | no |
| Read authors, pick authors on an article | yes | yes | yes |
| Create and edit their own linked author (`POST /v1/author/me`) | yes | yes | yes |
| Create an author from the editor ("Create author…", "This is me") | yes | yes | no |
### Decisions
- One site per article (`site_id` on the article). No per-site publish state: `is_online` stays the global switch. API keys stay global.
- The site key is immutable after creation. Exactly one default site exists and it cannot be deleted. Deleting a site with articles requires `reassign_to`.
- Authors are separate from users. An optional, unique link to a user. The slug is globally unique and not tied to a site. Zero authors on an article is allowed and never blocks publishing. Deleting an author with articles requires `reassign_to` (an author id or `none`).
- Media used as an author avatar or a site's default social image counts as media usage.
- The default site is seeded once from `PUBLIC_URL`. That variable is the CMS's own address (email links), so the seed is only a starting value that the owner edits. The base URL must be https, except for loopback hosts.
- Existing articles are backfilled to the default site and get no authors.
## Roles and permissions
Event names follow the backend: `role.create`, `role.edit`, `role.delete`, `role.reassign`, `user.change_role`, `user.transfer_ownership`, `user.remove`.
### Decisions
| # | Decision made | Alternative |
|---|---|---|
| 1 | Content permissions come before General permissions in the editor, because the common case (Contributor) only touches the grid. | General first, as in the brief. |
| 2 | Writer gets Authors: view and edit own, and Activity: own. | No Authors or Activity access. |
| 3 | A new role starts with nothing granted; presets fill the grid. | Start from a copy of Writer. |
| 4 | Own-scope rows others created show "View only" with a lock icon, not a hidden row. | Hide other people's entries. |
| 5 | Reset to default exists for built-in roles edited by the owner. | No reset. |
| 6 | Activity own/all scope uses the same None / Own / All control. | Toggle plus a separate scope select. |
| 7 | Transfer ownership takes effect at once, no email to the new owner. | The new owner must accept. |
| 8 | A user with Roles: manage cannot edit their own role, even in a custom role. | Allow narrowing only. |
## Account self-service
Authored content is anonymized to "Deleted user". The email-change link lasts 2 hours. One export succeeds per user every 15 minutes, and a direct download is the export flow. "Last administrator" counts Owner. A change request for an address already in use answers like success. The account-deleted email goes to the address the account had.
## Interface defaults
- Slide-over rule: only forms with a live preview and record details; on mobile always a 92% bottom sheet.
- Hover, active, disabled and focus tokens for the matrix (components not specified before): primary hover `--ui-text`, active `--ui-text-toned`; destructive hover opacity 0.85 and active 0.75; disabled 40% (rows 55%).
- Article pagination: Shipped shapes: the article list body is {items, total, page, size, counts}; the media list body is an array with the total in `X-Total-Count`. Users and authors follow their own routes (see routes.md).
- The Remove action in the link popover has no confirmation; undo restores the link.
- The link button is disabled when an image is selected.
- The tooltip text is "Insert link (Ctrl+K)" and "Insert link (⌘K)" on macOS.
- Mobile toolbar scrolls sideways; no wrap, no overflow menu.
- Selected nav items keep the sand fill plus weight 500 and `aria-current` (the fill alone is 1.3:1 in light).
- Syntax colouring dropped from code samples (one rendering).
- Export "Download started" offers only Close.
- New article keeps the title counter "n / 200" (title is limited to 200); the body has no limit and no counter.
- Page title 20/28, page padding 24/16, card padding 16 (foundations.md).
- Activity position in the sidebar follows AppFrame.
- The Prototype shows a toast "Not in this prototype" for sidebar items it has no screen for (Media, Activity, Settings).
+11
View File
@@ -14,3 +14,14 @@ Previews: `source/RenewCMS Emails.dc.html`.
Three Go html/template files: emails/verification.html, emails/password-reset.html and emails/invitation.html . They use a table layout with inline CSS and a 600 px maximum width. The button is bulletproof: a colored table cell plus a padded link, so it survives Outlook. Each has a plain-URL fallback, a hidden preheader, and prefers-color-scheme overrides for clients that support them. The mark is live text in a black cell rather than an image, so it shows even when images are blocked. Previews below use example values. Three Go html/template files: emails/verification.html, emails/password-reset.html and emails/invitation.html . They use a table layout with inline CSS and a 600 px maximum width. The button is bulletproof: a colored table cell plus a padded link, so it survives Outlook. Each has a plain-URL fallback, a hidden preheader, and prefers-color-scheme overrides for clients that support them. The mark is live text in a black cell rather than an image, so it shows even when images are blocked. Previews below use example values.
Suggested subjects are "Verify your RenewCMS account", "Reset your RenewCMS password" and "<InvitedBy> invited you to RenewCMS", where .InvitedBy is the inviter's display name or username. html/template escapes the .Email value for the query string in the reset link (the @ becomes %40), and the confirm route reads it back decoded. Suggested subjects are "Verify your RenewCMS account", "Reset your RenewCMS password" and "<InvitedBy> invited you to RenewCMS", where .InvitedBy is the inviter's display name or username. html/template escapes the .Email value for the query string in the reset link (the @ becomes %40), and the confirm route reads it back decoded.
## Account emails (change email, deletion, export)
Go `html/template` files built from `source/emails/verification.html` (same table layout, tokens, dark overrides, bulletproof button, URL fallback). English only.
| File | To | Subject | Variables |
|---|---|---|---|
| `source/emails/verify-new-email.html` | the new address | Confirm your new RenewCMS email address | `.Host`, `.Username`, `.VerificationCode`, linking to `{{.Host}}/account/email/confirm?c={{.VerificationCode}}` (expires in 2 hours, works once) |
| `source/emails/email-change-notice.html` | the old address, at request time | Your RenewCMS email address change was requested | `.Host`, `.Username`, `.NewEmail`, linking to `{{.Host}}/profile` |
| `source/emails/account-deleted.html` | the address the account had, sent once | Your RenewCMS account has been deleted | `.Host`, `.Username`, `.DeletedAt`; no button, generic text, no personal data |
Previews are rows on `source/RenewCMS Emails.dc.html`.
+81
View File
@@ -0,0 +1,81 @@
# Localization board changelog (pass 3)
Board: RenewCMS Screens Localization. Frame: LocaleFrame. Spec: locale-spec.js. State IDs are unchanged; seven IDs moved to a different frame selector (marked "selector"). 183 states in 16 groups (was 169 after the corrections pass).
Where a board and the spec disagreed, the spec won. Decisions the spec did not make are marked **Decided**. Frames were redrawn from code and not compared against the shipped app, so each **Decided** item is the thing to check first.
## A. Redrawn to match the spec
| ID | Expected copy and layout |
|---|---|
| loc.l8.saveFailPublish | Error banner above the editor: "Couldn't save French" / "Your changes are kept here. Nothing was published. Try saving again." Badge "Save failed", primary "Try saving again". Error toast: "Couldn't save French" / "Nothing was published. Your changes are kept. Try again." |
| loc.l8.done | Info banner "This version is online. Saving updates the live page right away." Badge Published, status "Saved". Toast "French published" / "Other versions weren't changed." |
| loc.l4.empty | Start empty selected. Source version reads "No source", help "Optional. Freshness shows No source until you pick a tracked source in the editor." |
| loc.l4.unreadable | Alert "The source isn't available to you" / "Choose another source you can read, or start empty. Your title is kept." Source version "Choose a version", error "Choose a version you can read." Create disabled |
| loc.l3.translation | Same fields as Add translation: kind radios (Translation selected), Article ("No French version yet."), Language ("Only enabled languages this article doesn't have yet."), Source version, "Title in French", Starting content (Start empty / Copy from English, selected). Button "Create French draft" |
| loc.l11b.moveSlug | Alert "An address is already used on Atelier" / "An address must be unique within its language on Atelier. Change the address below, then move again. Nothing was moved." Then "Conflicting version": French, the address in mono, "Edit slug". Note "Only versions you can read are named." |
| loc.conflict (and every dialog built from it) | "Save over theirs" is outlined in `--ui-error` with a triangle-alert icon and an error-colour title icon. Keep my changes stays the only filled button |
| Chip row, Articles list | The stray "0" came from `m && shift && …` rendering the number 0 in the mobile tab strip. Fixed with `!!shift`. Filter chips keep `width:max-content` |
| loc.l7.* (all list states) | Pager is AppPaginator (see components.md). Desktop: "Showing 1–5 of 8", "5 per page", first, previous, 1 2, next, last. 390: summary and select, then Previous, "Page 2 of 2", Next. +N overflow chip keeps 22 px visual height and gets a 44 px tap area at 390. The tab strip is no longer shifted by the stray character |
## B. Redrawn inside the AppFrame
| ID | Now |
|---|---|
| loc.seo.noFallback, loc.url.unset, loc.l10.noSocial | Editor in the shell, with the Search and sharing slide-over (960 px; bottom sheet 92% at 390) |
| loc.slug.published | Edit slug dialog over the same slide-over |
| loc.l12.seoPreview (selector v:seo x:preview), loc.l12.siteFallback (selector v:seo x:siteFallback) | Same slide-over; siteFallback shows French and Arabic versions side by side as cards |
| loc.l10.api | Integration page: sidebar item Integration active, breadcrumb "Integration" |
| loc.l12.media | Media page (grid, one card selected) with the 420 px image detail panel: "Used in 2 articles · 4 versions · 1 file". Bottom sheet at 390 |
| loc.l12.menu (selector v:li x:menuLang) | Articles list, French selected, row menu open: Open French, Open another language…, Publish French, Copy API URL, Delete French version (danger). 390: bottom sheet |
| loc.l12.apiCopy (selector v:li x:apiCopy) | Articles list with toast "API URL copied" / "/v1/article/14?lang=fr". 390: toast across the bottom with 16 px margins |
| loc.l1.single | "Social locale" and "Derived: pt_BR" on their own line at 390. The value was previously empty and is now drawn |
## C. Missing frames and copy
| Item | Decision |
|---|---|
| Banners | save failed, publish failed and online banners as in the Copy decisions table of the board |
| Row menu | All languages: Open <language>, Open another language…, Add translation…, Unpublish <language>, Copy API URL, Delete <language> version. Language selected: Publish or Unpublish replaces Add translation… |
| Disabled-language picker | New state **loc.l5.menuDisabled**. Spanish row shows Draft and a Disabled tag. Footer: "Spanish is disabled on this site. Its version stays readable and editable. It can't be published until an owner re-enables Spanish." |
| Setup done | "Languages assigned" / "16 articles now have a language. Nothing was translated, and no articles were grouped." |
| Version count line, 390 | **Decided: shown**, on its own line under each language name ("4 versions · 2 published"). Desktop unchanged |
| Public URL preview | **Decided: site default language.** Uses the most recently updated article that has a version in the default language. Journal: https://journal.example.com/en/how-we-price-a-bathroom-renovation. A site with no articles previews a sample address. The Valid example in the spec changed from the French address |
| invalid_host | New state **loc.l1b.invalidHost**. Pattern https://journal..example.com/{lang}/{slug}. Message "Enter a valid host name, such as journal.example.com." Added to the 422 list |
| site.* activity labels | Added to the Activity frame and the board table: site.language.add "Added French to Journal"; .enable "Re-enabled Spanish on Journal"; .disable "Disabled German on Journal"; .remove "Removed Italian from Journal"; .default "Made French the default language of Journal"; .social_locale "Set the social locale for French on Journal to fr_FR"; site.public_url.update "Changed the public URL pattern of Journal"; site.language.setup "Assigned languages to 16 articles on Journal, Notes and Archive"; article.move "Moved "<title>" from Journal to Atelier" |
| Toast icon box | 28 × 28 px, 16 px icon, tone colour on its -soft ground |
| Languages sidebar item | **Decided: none.** routes.md and components.md say so |
| loc.l11.session | Editor behind the dialog shows the unsaved changes. Title "Your session expired" / "Log in to continue. Your title, body and search fields for this French version are kept in this browser and restored after you log in, with a notice." Button "Log in" |
| loc.l4.gone | Deleted and unreadable sources look identical after submit (same neutral 404): "The source isn't available to you". The spec Visibility row was updated. "Source deleted" remains only in the review banner (L9) |
| loc.l8.deleteSource | "Delete the English version?" / "English is the tracked source for versions you can read." Alert "Review tracking will pause": "French, German and Arabic track English. They stay as they are and keep their review history. Each one asks you to choose a new source." |
| loc.l11b.moveSelectHidden | Arabic not listed or counted; "Versions you can't read aren't listed or counted." |
| loc.l7.review | Needs review tab, "2 articles need review" (no copy change) |
## D. Copy
| Item | Final copy |
|---|---|
| Delete article (loc.l8.deleteStoryOk) | Title "Delete English, French, German and Arabic?" / "The article and all of its translations will be deleted. This can't be undone." |
| New state loc.l8.deleteStoryFail (partial delete) | "Couldn't delete the article" / "Nothing was deleted. Every version is still there. Try again in a moment." Deleting is atomic, so there is no partial result. Same copy in screens/articles.md row 13 |
| New state loc.l8.deleteDone | Toast "French version deleted" / ""<title>" was deleted. English and German weren't changed." Editor opens English |
| New state loc.l8.deleteStoryDone | Toast on the list: "Article deleted" / "The article and all of its translations were deleted." |
| New state loc.l11b.moveFail | "Couldn't move the article" / "Nothing was moved. All 4 versions are still on Journal. Try again." Buttons Cancel, Try again |
| loc.l11.conflict2 | Alert "Their version changed again" / "Someone else saved this version again at 14:41, before your save went through. Nothing was overwritten. Your changes are still here." (was "Couldn't replace theirs") |
| loc.l3.multi, loc.l3.sitechange | Language help "Default language for Journal." (was "Default for Journal.") |
## E. Older design gaps
| Item | Status |
|---|---|
| Old Articles board | Replaced as the list pixel gate by new group L7s (single-language site), 7 states: loc.l7s.default, draft, noResults, empty, loading, fail, menu. No language filter, coverage column or tabs. Back-office groups kept as a copy reference |
| routes.md /articles row | Rewritten: query params, response `{ items, total, page, size, counts }` |
| Role-picker sand card | Already uses `--rc-on-sand` for name and description in RolesFrame; no change |
| Media detail panel, "Used elsewhere" | Panel now draws the section below the article list: "Used elsewhere" with rows "Author avatar" (/authors) and "Site default social image" (/settings/sites). The "Used in N" badge counts articles, entries, avatars and the site image. loc.l12.media shows "Used in 2" with two articles. New state **loc.l12.mediaElsewhere**: an image used only as an author avatar, badge "Used in 1", "Articles" with "No article shows it.", then "Used elsewhere" with Author avatar. Tooltip and delete-dialog copy unchanged. MediaFrame already had four used-elsewhere states (avatar, site, both, none); those stay |
| Editor "Create author" on 390 px (dialog, for me, slug taken, failed) | The Details sheet and the dialog were both drawn, with the shell's own sheet competing. On 390 the shell sheet is now off for these states, the Details sheet is drawn once, and the dialog sits above it (z-index 70). Not checked visually |
| Selected media-card badges | Confirmed: "Used in N" and Draft outline badges keep an opaque `--ui-bg` ground and `--ui-text-toned` text on a selected sand card: 9.7:1 light, 11.6:1 dark (needs 4.5:1). The soft badges (Duplicate, variants) now also sit on `--ui-bg` with a currentColor border when selected |
## Header and counts
Board header paragraph, README.md, states.md and localization-corrections.md now say 183 states in 16 groups.
## New state IDs
loc.l12.mediaElsewhere, loc.l5.menuDisabled, loc.l1b.invalidHost, loc.l8.deleteDone, loc.l8.deleteStoryFail, loc.l8.deleteStoryDone, loc.l11b.moveFail, loc.l7s.default, loc.l7s.draft, loc.l7s.noResults, loc.l7s.empty, loc.l7s.loading, loc.l7s.fail, loc.l7s.menu.
+53
View File
@@ -0,0 +1,53 @@
# Localization corrections and completion report
Board: RenewCMS Screens Localization. Frame: LocaleFrame. Fixtures: locale-fixtures.js. Spec: locale-spec.js. LocaleLive and the Handoff board were not touched.
## State counts
169 states in 15 groups (was 109) at the end of that pass; the third pass brought it to 183 in 16 groups (see `localization-changelog.md`). Counts at the end of the corrections pass: L1 25, L1b 9, L2 7, L3 4, L4 10, L5 25, L5b 9, L6 12 (release 2), L7 16, L8 13, L9 11 (release 2), L10 5, L11 7, L11b 8, L12 8. 33 states are also drawn at 1024. The full ID table is in states.md, and the board lists IDs, selectors and fixtures per state.
IDs: 99 existing states keep their group, frame and selector. 70 are new. Ten existing states were rekeyed without changing meaning: the seven permission states moved from frame ed to perm (L5b), and the three move failures moved from L11 to L11b. Legacy IDs (loc.perm.*, loc.dup.*, loc.lang.*, loc.src.*, loc.review.changed, loc.conflict, loc.slug.published, loc.url.unset, loc.seo.noFallback) were kept as the canonical ID of the state they map to; the loc.lN.xxx alias is listed beside each. Nothing was removed without a replacement.
## Sections to files and states
| Section | Files | State IDs |
|---|---|---|
| 1 Permissions | LocaleFrame, locale-spec.js | loc.perm.readonly, loc.l5b.roMenu, loc.perm.editNoPublish, loc.perm.publishNoEdit, loc.perm.siblingReadOnly, loc.perm.siblingHidden, loc.perm.createNotAll, loc.l5b.noAdd, loc.l5b.withAdd, loc.l5.cleanOnline |
| 2 Header, actions, title | LocaleFrame, AppFrame (edHeader, edMobBar slots), spec tables Editor header priority, Action matrix, Title field states | loc.l5.default, dirty, dirtyPublish, cleanOnline, onlineDirty, saving, saved, saveFail, pubFail, ovf, focus, titleEdit, titleUnsaved, invalid, titleShort, titleLong, titleSaving, failed; loc.l8.unpublishDirty |
| 3 Conflict | LocaleFrame | loc.conflict, loc.l11.conflictRestored, reloadConfirm, conflict2, download, restored, session |
| 4 List | LocaleFrame, fixtures view() | loc.l7.all, page2, fr, frMissing, emptyMissing, noResults, frLoading, listFail, limited, review, author, langFilter, rowMenu, filters, tabsScroll, long |
| 5 Languages and setup | LocaleFrame, routes.md | loc.l1.* (reenableDone, reenableFail, broader, defaultFail, removeFail, stale, social, socialEdit, socialInvalid, readonly), loc.l1b.*, loc.l2.noLocale, inProgress |
| 6 Move, delete, add translation | LocaleFrame | loc.l11b.*, loc.l8.deleteStoryOk, deleteStory, loc.l4.long, unreadable, langOff |
| 7 Review and reference (release 2) | LocaleFrame | loc.l9.*, loc.l6.* (arRef, narrow at 1024, rtl) |
| 8 Metadata, API, surfaces | LocaleFrame | loc.l10.*, loc.l12.* |
| 9 Fixtures | locale-fixtures.js, board tables Fixture index and Fixture totals check | all |
| 10 Accessibility | spec table Accessibility and interaction, board table Contrast | all |
| 11 Docs | routes.md, states.md, components.md, README.md, screens/localization-*.md (8 files, generated from the spec) | all |
## Rendered and inspected
I rendered the frame at full size and looked at these. Everything else is specified in the spec and the board, and drawn by the same code, but I did not look at it.
- 1440 light: ed.dirtyPublish, perm.ro, perm.p6, ed.menu, ed.titleLong, pd.unpublishDirty, pm.conflict, pm.moveSelect, fr.review, li.all, li.long, li.author, li.limited, sl.social, sl.broader, su.ready, pu.encoded, seo (default), api, sf.home, src.split.
- 1024: ed.dirtyPublish (dark), ed.cleanOnline, src.rtl (dark), li.long, li.all.
- 390: ed.dirtyPublish, ed.pubFail, ed.ovf, pm.conflict (all four options and the primary visible without scrolling), at.long (primary stays at the bottom), li.filters, li.long, li.rowMenu, li.page2, src.mobileSrc, sl.multi (dark), perm.ro (dark).
- Dark: li.all 1440, ed.dirtyPublish 1024, src.rtl 1024, sl.multi 390, perm.ro 390.
- The board's computed tables (fixture totals, state counts, contrast) were read in the browser. Every total matches the fixture. Contrast passes for every badge, chip and selected variant in light and dark. Disabled controls at 40% (2.6:1 light) are exempt.
## Not completed
- Most states were not looked at. Only the list above was rendered and inspected. 1024 frames exist for 33 states and I looked at five.
- Icons come from an online icon service and did not load in my screenshots, so icon presence and placement were not checked visually.
- Header widths between 1024 and 1440 were not drawn; the collapse order is specified and shown at the two ends.
- The mobile Languages rows are taller than needed (social locale wraps onto its own line). Not tuned.
- Nuxt UI components are named in components.md; the frames are built from the design tokens, as before.
- Archive, Notes and Gallery appear in single states, not as full lists.
- Setup frames still list all sites, although the route is per site (see below).
- LocaleLive and the Handoff board still describe the old behaviour.
## Documents that disagreed, and what I aligned to
- Route: routes.md and the board said /settings/languages; the brief says /settings/sites/:key/languages. Aligned to the brief. The setup page lists every site, so :key is the site it was opened from.
- Wording: the brief says "story" never appears in the UI, but section 1 uses "Delete story" and "You can't delete this story." I used "article" everywhere ("Delete article", "You can't delete this article."). Rule not changed; only the word.
- Count: the brief's example "5 French versions" disagrees with the decided fixture (fr 4). Aligned to the fixture: "4 French versions".
- routes.md still listed list params mode and needs_review and the old public route GET /v1/public/site/{key}/article/{slug}?lang=. Removed; aligned to tab and the two final public routes.
- states.md said the frame was not yet updated for the permission states; replaced by the generated table.
- The previous 1024 frames were a 1440 frame clipped to 1024. AppFrame now takes a width, so 1024 frames are real.
- Section 2 asks for a "Retry publish" action; the banner and the primary both use that label.
## Rules I believe are wrong
None changed. One to watch: Save over theirs sits at equal weight with Reload theirs, as required. If both stay unfilled, a user may not see that Save over theirs is the destructive one. The explanation text carries that. Left as is.
+392
View File
@@ -0,0 +1,392 @@
# Localization board tables
Generated from `source/locale-spec.js`. Read `localization.md` first: its explicit corrections supersede conflicting text below. API additions are proposals to be specified and accepted through `/slice`, not existing endpoints.
## Decisions
| Question | Chosen behavior | Rationale | Existing behavior affected | Backend dependency | Release |
| --- | --- | --- | --- | --- | --- |
| Language model | One story group, one article id per language, one version per locale | Reuses the article editor, permissions and publish flow | None for single-language sites | group_id, lang on articles; unique (group_id, lang) | Initial |
| Default vs editing vs source | Three separate roles. Default is a site setting; editing language is the open article; source is chosen per translation | Default is not always the best source | None | source_article_id per version | Initial |
| Locale scope | Per site, list of enabled languages plus one default | Matches site-level settings | Settings → Sites gains Languages | site_languages table | Initial |
| Site locale field | Four distinct values: formatting locale (existing Site.Locale, still used for dates and numbers), default content language (new, seeded from the full Site.Locale and confirmed by the owner), article language (per version), social metadata locale (explicit or derived, never guessed) | Avoids silent reinterpretation | ResolveArticleSEO reads Site.Locale for social metadata (verify in repo); for localized articles it uses the article language | None | Initial |
| Disable vs remove | Disable keeps content and published versions. Remove only at zero versions | No configuration action deletes or unpublishes | None | Count per language; 409 language_in_use | Initial |
| Existing content | Setup assigns a language per site, in one transaction; each article becomes its own story | Metadata only; no guessed grouping | Articles gain lang | Bulk assign endpoint, atomic | Initial |
| Titles | Editable after creation. A title change never alters an existing slug. Slug changes only through explicit Edit slug; no redirects are promised (none in the backend) | Translated titles must be revisable; URLs stay stable. Same rule on single-language sites | CHANGE: titles were immutable. Slug policy applies everywhere | Allow title in PUT; slug rules | Initial |
| Slug uniqueness | Unique per (site, lang) | Same slug in two languages is normal | Today unique per site | Index change | Initial |
| Language control | Dropdown beside the title; rows show version state; interface language unchanged | Compact for 2 to 20 languages | Editor heading | translations[] on GET article | Initial |
| Switching | Opens another article id. Dirty form asks Keep editing, Discard, Save and switch | URL is the state; no lost work | None | None | Initial |
| Add translation | Draft only; copy or start empty; images/authors reused; copied text flagged Needs review | Copying is a start, not completion | None | POST translations; 409 language_exists | Initial |
| Source reference | Optional read-only pane; segment on mobile; no sync | Keeps the single editor default | None | Read access to source | Initial |
| Direction | dir on editor and reference panes only | Shell stays LTR | None | Per-language dir from locale | Initial |
| List: all languages | One row per story; title from default version, else first accessible; coverage chips | Avoids duplicates | Articles list | Grouped query, access-filtered | Initial |
| List: language selected | One row per version; Not in French tab lists stories | Units always stated | Tabs and counts | lang, tab params | Initial |
| Search | All languages: every accessible title. Language: that language only | Predictable | Search | Access-filtered | Initial |
| Publishing | Per version; copy always names the language; no bulk publish | Prevents accidental scope | Publish button copy | None | Initial |
| Deleting | Per version. Last version deletes the story. Article delete needs permission on all | Explicit scope | Delete dialog | None | Initial |
| Freshness | Needs review when the source revision changes after the reviewed revision; Mark as reviewed records it | Reliable, not timestamp-based | None | content_revision on versions; reviewed_source_revision | Initial |
| Revision-bumping fields | Title, body, excerpt, slug, image alt text, SEO and social text. Not authors, cover, site, publication | Only translatable content counts | None | Revision incremented in same write | Initial |
| Site move | Moves the whole story; destination must enable every language; slug conflicts block | No splitting or merging | Site select in editor | Move endpoint, validation | Initial |
| Hidden versions | Titles, counts, coverage, language summaries, previews, errors and deletion confirmations name only versions the user can read | No leakage | List counts, delete dialog | Filter at query level | Initial |
| Machine translation | Not included | Out of scope | None | None | Later |
| Cross-site stories | Not included | Out of scope | None | None | Later |
| Bulk publish / review | Not included | No clear need | None | None | Later |
| Slug policy | Slug generated once at creation. Changed only by Edit slug, before or after publishing. Published change warns: "Links to the old address will stop working. RenewCMS does not create redirects." | One policy, no redirect promise | Slug field | Unique (site, lang) | Initial |
| Permission model | Capabilities per version: read, edit, publish, delete, create-translation, review. UI renders from capabilities[] on the article response, not from role names | Matches role/scope permissions | Editor, list | capabilities[]; server enforces every call | Initial |
| Missing vs hidden | "Not in French" lists stories where French is absent or unreadable to the user. Add French translation on a story with an unreadable French returns a neutral 409 (see Visibility policy) | Discovery cannot leak existence | List | Conflict check ignores read permission; response is neutral | Initial |
| Source-copy access | Read access to the chosen source is rechecked at submit, inside the transaction | Access can change while the dialog is open | Add translation | Neutral 403/404 | Initial |
| Disabled languages | Versions stay readable and editable; publishing blocked until re-enabled; filter lists them under Disabled | No silent unpublishing | Site languages | enabled flag per site language | Initial |
| Header priority | Left to right: language dropdown, publication badge, status badge (unsaved, saving, saved, failed), freshness badge, Read only tag, title input (fills the remaining width, same row on desktop), then reference button, Unpublish, Save, primary, overflow. At most one filled button. Collapse order: reference label, Unpublish to overflow, freshness to icon | The primary action is never hidden | Editor header | None | Initial |
| Public URL pattern | Per-site owner setting with {lang} and {slug}; live preview from a real article; unset state links from "Public URL not configured" | No fabricated website URLs | Settings → Sites | public_url_pattern on site | Initial |
| Social locale per language | Per-language owner field on Languages: Derived (from the tag), Set (typed), Not set. Format language_REGION | Never guess a region | Languages page | social_locale per site language | Initial |
| Release split | Source reference (L6) and Freshness and review (L9) are release 2. Frames are drawn in full so they can be checked | Smaller first release | None | None | Release 2 |
| UI wording | The UI says "article", never "story". No revision numbers, IDs or HTTP status names in user-facing copy. Internal notes may say story | Plain language | All localization copy | None | Initial |
| Languages in the sidebar | No sidebar item. Languages is reached only through Settings → Sites → [site] → Languages, which routes.md lists as the only languages route | One route, one entry point, per-site scope | Sidebar unchanged | None | Initial |
| Public URL preview | The preview uses the most recently updated article that has a version in the site default language, in that language. A site without articles previews a sample address | Predictable and never fabricates a language | Public URL page | None | Initial |
| Deleting an article | Dialog names the readable versions and states that the article and all of its translations are deleted. Failure copy: "Couldn't delete the article" with "Nothing was deleted. Every version is still there. Try again in a moment." | Delete is atomic, so there is no partial delete | Delete dialog | None | Initial |
| Destructive cue in the conflict dialog | Keep my changes is the only filled button. Save over theirs is outlined in --ui-error with a triangle-alert icon, the same size as the other secondary buttons | Marks the destructive choice without changing the equal-weight rule | Conflict dialog | None | Initial |
## Capability matrix (per version, enforced server-side)
| Case | Read | Edit | Publish | Delete | Create translation | Review | UI result |
| --- | --- | --- | --- | --- | --- | --- | --- |
| P1 Read-only version | Yes | No | No | No | If can create on site | No | Banner "You can read this version. You can't edit it." No Save, Publish, Delete; formatting toolbar hidden; fields read-only; the reference action remains |
| P2 Edit, no publish | Yes | Yes | No | Per scope | Per scope | If can edit | Save shown; Publish hidden; hint "Publishing needs the publish permission" |
| P3 Publish, no edit | Yes | No | Yes | Per scope | Per scope | No | Publish/Unpublish shown, fields read-only (only if existing permissions allow publish without edit) |
| P4 Sibling readable, not editable | Yes | No | No | No | n/a | n/a | Opens read-only; row tag "Read only" |
| P5 Sibling not readable | No | No | No | No | n/a | n/a | Row absent; no count, no placeholder |
| P6 Can create, not modify all | Yes | Own versions | Own | Own | Yes | Own | Delete article and Move article disabled with the reason "You can't delete this article." Delete French version stays available if allowed |
| Owner / Admin | Yes | Yes | Yes | Yes | Yes | Yes | All readable versions; not inferred from role label alone |
## Field ownership, copy and fallback
| Field | Own per version | Copied on "Copy from source" | Fallback if empty |
| --- | --- | --- | --- |
| Title | Yes | Entered by the editor | None (required) |
| Slug | Yes | Generated from the new title | None |
| Body | Yes | Yes, flagged Needs review | None |
| Excerpt | Yes | Yes | First words of body |
| SEO title and description | Yes | Yes | Title / excerpt, then site defaults |
| Social text | Yes | Yes | SEO text |
| Image alt text | Yes | Yes | None |
| Cover and inline images | Reference, files shared | Yes, no duplicate files | None |
| Authors | Yes | Yes, editable | None |
| Site | Shared by the story | Same | None |
| Publication and timestamps | Yes | No | None |
## API: existing vs proposed
| Capability | Status | Request | Errors |
| --- | --- | --- | --- |
| List articles | Existing, extended | GET /v1/article/?page=&size=&q=&status=&site=&seo= (existing). Proposed: lang, tab=all\|missing\|review (same names as the URL; no separate mode or needs_review) | 400 invalid page/size (SPA never shows it) |
| Get article | Existing, extended | GET /v1/article/{id}. Proposed fields: lang, story_id, capabilities[], translations[] (readable only), source { article_id, revision, status: tracked\|inaccessible\|deleted } | 404 for hidden or deleted |
| Create article | Existing, extended | POST /v1/article/. Proposed: lang, story_id, source_article_id, copy (routes to translation rules) | 409 language_unavailable · 422 language_not_enabled |
| Edit | Existing, extended | PATCH /v1/article/{id}. Proposed: if_revision for overwrite recheck | 409 revision_conflict { current_revision } |
| Publish / unpublish | Existing | PATCH /v1/article/{id}/publish, /unpublish. Per version | 403 missing_permission · 422 language_disabled |
| Delete | Existing | DELETE /v1/article/{id}. Last version deletes the story | 403 · 404 |
| Add translation | Proposed | POST /v1/article/{id}/translations { lang, title, source_article_id, copy }. Path id is any readable version; source_article_id selects the copy source; source_revision captured in the transaction | 409 language_unavailable (neutral) · 404 (neutral) · 422 · 403 |
| Mark reviewed | Proposed | POST /v1/article/{id}/review { source_article_id, source_revision, translation_revision } | 409 source_changed · translation_changed · source_replaced · 403 |
| Change tracked source | Proposed | PATCH /v1/article/{id}/source { source_article_id\|null } | 422 source_cycle · 422 source_other_story · 403 |
| Site languages | Proposed | GET/PUT /v1/site/{key}/languages { default, languages[{ lang, enabled }] }, atomic | 422 default_not_enabled · no_enabled_language · 409 language_in_use · 409 languages_changed |
| Setup | Proposed | GET/POST /v1/language/setup { sites:[{ key, lang }] }, idempotent per site key; articles created during setup get the site default; retry after failure is safe. UI route /settings/sites/:key/languages/setup | 403 · 409 setup_in_progress |
| Move story | Proposed | POST /v1/story/{story_id}/move { site }, atomic, revalidates | 409 slug_conflict · 422 language_not_enabled · 403 (neutral) |
| Publish with unsaved edits | Client sequence | PATCH /v1/article/{id} (save) then PATCH /v1/article/{id}/publish. The second call is sent only if the first returns 200. No new endpoint | Save failure: nothing published, edits stay unsaved |
| Public article (two requests) | Proposed | Exact: GET /v1/public/site/{key}/lang/{lang}/article/{slug}. Resolve: GET /v1/public/site/{key}/story/{story_id}?lang=&fallback=default. Existing article-ID links unchanged | See Public lookup |
| Public URL pattern | Proposed | GET/PUT /v1/site/{key} { public_url_pattern }. Placeholders {lang}, {slug}. Owner only | 422 unknown_placeholder · invalid_scheme · invalid_host · not_encoded · missing_slug · 403 |
| Social locale | Proposed | PUT /v1/site/{key}/languages { languages[{ lang, enabled, social_locale\|null }] } | 422 invalid_social_locale |
## Accessibility and interaction
| Control | Accessible name and keyboard | Focus | Announcement |
| --- | --- | --- | --- |
| Language control | "Language: French. Switch version". Enter or Down opens a menu; arrows move; Enter selects; Escape closes | Into the list on open; back to the control on close | Polite: "Editing French version" |
| Title input | Accessible name "Title (French)", no visible label (the language dropdown beside it names the version); aria-describedby points to the help or error text; invalid sets aria-invalid and the message is an alert | Stays in the field; on Try again, back to the field | Polite: "Saving title", "Title saved"; errors are announced |
| Save, Save and publish, Retry publish | Buttons named by their text including the language ("Save and publish French"); busy state sets aria-busy; Tab order: title, language, status, reference, Unpublish, Save, primary, More actions | After save, stays on the button; after a failed save, on Try saving again | Polite: "French saved"; "Saved as a draft. Publishing failed. Try publishing again." |
| More actions menu or sheet | Menu button "More actions"; items are menuitems; disabled items use aria-disabled and show the reason as text | First enabled item on open; back to More actions on close | None |
| Reference button | "Show source reference" or "Hide source reference", icon-only at 1024 with the same name | Moves into the pane on show; back to the button on hide | Polite: "Showing English reference" |
| Conflict dialog and sheet | role dialog, modal; options are buttons in order Keep my changes, Download my version, Reload theirs, Save over theirs; Escape equals Keep my changes | First button (Keep my changes) on open; back to the title on close | Polite: "Download started" |
| Move panel and dialogs | Site select is a listbox named "Site"; the note is the description of the confirm button | Into the list; back to the site select | Polite: "Moved to Atelier" |
| Add translation dialog | Focus trapped; Escape cancels unless creating | First field; back to the control | Polite: "French draft created" |
| Source segment (mobile) | Two-button radiogroup, arrows switch | Stays on the segment | Polite: "Showing English source" |
| Coverage chips | aria-label per chip: "French: draft, needs review". The "+3" chip is named "3 more languages: …" | Row, not chips. Dashed chips are buttons on desktop only when the user can create | None |
| List unit label | aria-live polite: "4 articles not in French" | None | Polite on every filter change |
| Status without color | Publication badges are solid with an icon (Published: check, Draft: pencil). Freshness badges are outlined with a refresh icon and a word. Save status always has an icon and a word | None | None |
| Touch targets | On mobile every button, menu row, chip button and segment is at least 44 px high; the bottom bar keeps the primary visible | None | None |
| Reduced motion | No slide or fade transitions on popovers, sheets and the tab strip scroll when prefers-reduced-motion is set; the saving spinner becomes a static icon with the word "Saving" | None | None |
## Acceptance scenarios
| # | Given / When / Then |
| --- | --- |
| 1 | Given a single-language site, when creating an article, then no language control appears anywhere. |
| 2 | Given French is enabled, when an editor adds a French translation with "Copy from English", then a draft is created, the editor opens it, and the badge reads Draft and Needs review. |
| 3 | When French is published, then English publication is unchanged. |
| 4 | When English changes title or body after review, then French shows Needs review; changing authors does not. |
| 5 | Given dirty French, when choosing English, then a three-choice dialog appears and no work is lost. |
| 6 | Given a writer who cannot see the German draft, then German appears nowhere in lists, counts, menus or alternates. |
| 7 | When disabling German with 12 versions, then all 12 stay and 3 published stay online. |
| 8 | When two editors create French at once, then the second sees "French is no longer available" with entries kept. |
| 9 | When moving a story to a site missing a language, then the move is blocked and nothing splits. |
| 10 | When the interface language is Arabic or French, the editing language indicator still shows the article language. |
| 11 | Given French has unsaved edits, when the user chooses Save and publish French and the save fails, then nothing is published and the edits stay unsaved with Try saving again. |
| 12 | Given French is missing and unpublished, when a client resolves the story with lang=fr and fallback=default and the default is published, then the response is the default language with requested_lang fr and fallback true; with the default also unpublished it is 404 language_not_available. |
| 13 | Given a site locale pt-BR, when setup seeds the default language, then it reads Portuguese (Brazil) pt-BR and the owner confirms it before anything applies. |
## Existing surfaces audit and verification
| Item | Note |
| --- | --- |
| Home | Recent articles show the default-language title with a language code when not default. States loc.l12.home, loc.l12.homeFr |
| Activity | Events gain the language: "Published French version of …". State loc.l12.activity |
| Article menu | Publish and Delete labels name the language on multilingual sites. State loc.l12.menu |
| API URL copy | Copies the version URL with ?lang=. State loc.l12.apiCopy |
| SEO preview | Shows the localized address and canonical. State loc.l12.seoPreview |
| Media usage | Counts a shared image once; lists versions that use it. State loc.l12.media |
| Site text fallback | A site-level text (for example a site description) is a fallback only for articles in the same language. A French article can use the French site text; an Arabic article with no Arabic site text gets "No fallback" and the tag is left out. State loc.l12.siteFallback |
| Verification limit | Repository files were not accessible. Statements about them are assumptions marked verify in repo. |
| Decided | Slug policy, hidden-version disclosure, Home counting articles, and review storing the source version only (no text diff) are decided in the other tables. |
## Visibility and anti-enumeration policy
| Situation | User can read it | User cannot read it |
| --- | --- | --- |
| Duplicate translation | "French already exists for this article." Action: Open French version | "French can't be created for this article." No Open action, no title, no hint a version exists |
| Create conflict response | 409 language_exists with article_id | 409 language_unavailable; identical body for exists-unreadable, disabled and lost race |
| Article delete confirmation | Names readable versions: "Delete English and French?" | Unreadable versions are not named or counted. If any blocks deletion: "You can't delete this article." plus Delete this version |
| Source unavailable | Deleted or unreadable at submit: the same neutral 404, shown as "The source isn't available to you." The review banner (L9) says "Source deleted" only for a source the user already knew about | "The source isn't available to you." |
| Missing translation tab | Row shown; Add French translation | Same row; a 409 shows the neutral copy |
| Counts and summaries | Readable versions only | Never included |
## Public lookup and URLs
| Topic | Decision |
| --- | --- |
| CMS API vs website | CMS API URLs (/v1/...) are never shown as website URLs. Website URLs come from a proposed per-site public_url_pattern (owner), e.g. https://example.com/{lang}/{slug}. Existing convention unverified. |
| Pattern not configured | "Public URL not configured" with a link to site settings. No URL is fabricated. API links by article ID remain. |
| Exact lookup | GET /v1/public/site/{key}/lang/{lang}/article/{slug}. Matches site + language + slug only (slug is unique per site and language). Missing or unpublished: 404 article_not_found. It never falls back and never tries another language's slug |
| Resolution by story | GET /v1/public/site/{key}/story/{story_id}?lang=&fallback=default. story_id is the stable story identifier, returned on every public response and in alternates[]. No lang means the site default language. Fallback is decided only by story_id |
| Example: requested version published | story st_01, lang=fr, French published: 200, lang fr, fallback false |
| Example: requested missing or unpublished | lang=fr, no published French. Without fallback: 404 language_not_available. With fallback=default and a published default (en): 200, lang en, requested_lang fr, fallback true |
| Example: default also missing or unpublished | lang=fr, fallback=default, French and the default both unavailable: 404 language_not_available. No third language is tried |
| Example: default requested but unpublished | lang=en, English unpublished, fallback=default: 404 language_not_available |
| Compatibility | Article-ID endpoints (GET /v1/article/{id}) and existing public URLs keep working. Setup labels existing articles with the site default language |
| Response identity | Always lang (actual language). alternates[] lists only published, enabled-language versions |
| Canonical | The localized page itself, unless an explicit canonical override is set |
| Default-language change | Does not change what existing URLs return; absent or unpublished default gives 404 unless fallback is requested |
## Locale semantics
| Value | Meaning | Used for |
| --- | --- | --- |
| Site formatting locale | Existing Site.Locale | SPA dates and numbers; kept |
| Default content language | New per-site setting. Setup seeds it from the full Site.Locale when a supported language entry matches (en-GB, pt-BR). If only the language part is supported it seeds that and says so. No locale: the owner must choose. The owner confirms or changes it explicitly; nothing applies unconfirmed | Fallback, new-article default, setup |
| Article language | BCP 47 tag per version (en, fr, pt-BR, ar) | html lang, API lang, hreflang |
| Social metadata locale | Resolved in order: 1) explicit social locale on the site language (set by an owner, e.g. fr: fr_FR); 2) the language tag already has a region (pt-BR gives pt_BR); 3) Site.Locale has the same language part (site en-GB and article en give en_GB); 4) otherwise none: og:locale and og:locale:alternate are omitted for that version and the editor shows Not set. No region is invented for a bare language. og:locale:alternate lists other published versions whose locale resolves by the same rules; the rest are left out | og:locale, og:locale:alternate |
| SEO fallbacks | Empty French SEO fields fall back to French title and excerpt. English site defaults are never applied silently to a non-default language: editor shows "Empty. English site default not used." and the tag is omitted | Editor labels: "Fallback: French title", "No fallback" |
## Article list modes and sample data
| Mode | Units and count | Representative title | Row opens | Search | Sort |
| --- | --- | --- | --- | --- | --- |
| All languages | Stories | Default-language version if readable, else first readable by language code | Representative version | Any readable title | Story updated: latest readable version |
| Language selected | Versions in that language | That version | That version | That language only | Version updated |
| Missing language | Stories lacking it or unreadable in it | As All languages | Representative version | Titles in any readable language | Story updated |
| Filters | Status, Author, SEO, Needs review: a story matches if any readable version matches (language mode: the version) | | | | |
| Story Author, Updated | Union of readable authors; latest readable update | | | | |
| Differing sites | Language filter lists the union; Missing excludes sites that do not enable the language | | | | |
| Dataset (locale-fixtures.js) | See the Fixture index. Journal: 8 articles, 17 versions, page size 5 (page 1 shows 5, page 2 shows 3). Enabled en (default), fr, de, ar; disabled es, it. Versions: en 7 (6 published), fr 4 (2 published, 2 Needs review), de 4 (3 published), ar 1, es 1, it 0. 4 articles have no French version. Needs translation 7, Needs review 2. Every list, tab count, unit label and pager is computed from locale-fixtures.js. | | | | |
## Review source and revision semantics
| Topic | Decision |
| --- | --- |
| Record | { article_id, source_article_id, source_revision, translation_revision, reviewed_by, reviewed_at } |
| Confirmation guard | The dialog carries the versions the user saw. If either moved, the dialog says "The English source changed while you were reviewing. Review again." or "French was changed by someone else while you were reviewing. Review again." Nothing is marked |
| Change tracked source | Explicit action Change tracked source. Result: Needs review. Earlier reviews are kept as history |
| Cycles | Prevented (422 source_cycle). Source must be in the same story |
| Access loss vs deletion | Access lost: "The source isn't available to you right now." history kept, Mark reviewed disabled. Deleted: "Source deleted" with Choose a new source |
| Source replacement | Pick another readable version of the story; freshness becomes Needs review |
| What changed | Changed-field summary only, shown as "Changed fields: Title, Body", with the source version date and the translation version date. No text diff and no revision numbers in the UI |
| Concurrent edits | Mark reviewed applies only to the revisions the user saw |
## Title, slug and concurrent edit flows
| Case | Behavior |
| --- | --- |
| Title editing | Inline underline input in heading style, on the same row as the language, badges and actions on desktop (no box, no visible label). States: pristine, focus, editing, unsaved, invalid ("Enter a title"), too short, too long, saving, failed (value kept). Bounds 3 to 200 characters. Accessible label "Title (French)". Editing the title never changes the slug |
| Slug | See Slug policy. Edit slug lives in Search and sharing and in the overflow menu; its note says "Editing the title never changes the slug." |
| Conflict | "Someone else saved this version at <time>." Choices: Keep my changes (filled; nothing sent), Download my version, Reload theirs (confirm: "This discards your unsaved changes."), Save over theirs (sends the version fetched now; a newer save gives a new conflict) Save over theirs is outlined in the error colour with a warning icon. |
| Overwrite scope | "Replaces the title, body and search fields of this version only. Other languages are untouched." |
| Session expiry | Draft kept locally per article (title, body, search fields) until saved or discarded. After login: "Restored unsaved changes from <time>." |
## Language configuration lifecycle
| Action | Rule |
| --- | --- |
| Disable default | Blocked: "Choose another default first." |
| Disable last enabled | Blocked: "At least one language must stay enabled." |
| Disable with content | Allowed; versions remain; published stay online; publishing blocked for drafts |
| Re-enable | Row action Re-enable; no data change |
| Remove | Only at zero versions; never the default |
| Save error | Dialog keeps language, default and toggle values; error above the footer |
| Story moves | Disabled-language versions count toward destination requirements |
## Mobile list and prototype scope
| Item | Spec |
| --- | --- |
| Filter sheet | Site, Language, Status, Author, SEO; Clear all and "Show N results"; active filters show as chips with "Remove filter Status: Draft" and Clear all |
| Tabs | Scrolls with edge fade and buttons "Scroll tabs left/right"; Not in French is always reachable |
| Pager | Same page size as desktop (5); "Page 1 of 2"; the URL keeps page and size |
| Row actions | Identical capability on every width: see Row actions. Mobile uses the row menu button (44 px), desktop shows the same button (28 px) |
| Prototype flows | Not part of this pass. The LocaleLive prototype was not touched |
## Editor header priority
| Order | Item | 1440 | 1024 | 390 |
| --- | --- | --- | --- | --- |
| 1 | Title input (underline, heading style; own row on mobile, shares the header row on desktop) | Full width | Full width | Full width |
| 2 | Language dropdown | Visible | Visible | Visible, 44 px |
| 3 | Publication badge | Visible | Visible | Visible |
| 4 | Primary action (the only filled button) | Rightmost before More actions | Same | Fixed bottom bar, fills the width left by Save and More |
| 5 | Status badge (Unsaved changes, Saving, Saved, Save failed) | Visible | Visible | Visible |
| 6 | Save (secondary) | Visible | Visible | Bottom bar, next to the primary |
| 7 | Freshness badge | Icon and word | Collapses first: icon only, name in aria-label | Wraps under the language row |
| 8 | Read only tag | Visible | Visible | Visible |
| 9 | Reference button | Icon and label | Collapses second: icon only | More actions sheet |
| 10 | Unpublish (secondary) | Visible | Collapses third: More actions menu | More actions sheet |
| 11 | More actions | Edit slug, Move article, Delete versions | Same plus Unpublish | Same plus reference and Unpublish |
## Action matrix
| State | Permissions | Primary (filled) | Secondary | Notes |
| --- | --- | --- | --- | --- |
| Clean draft | edit + publish | Publish French | Save (off) | loc.l5.default |
| Clean draft | edit only | None | Save (off) | Hint: Publishing needs the publish permission |
| Dirty draft | edit only | Save | None | loc.l5.dirty; "Saving keeps it as a draft." |
| Dirty draft | edit + publish | Save and publish French | Save | loc.l5.dirtyPublish |
| Clean online | edit + publish | None | Unpublish French, Save (off) | loc.l5.cleanOnline; "This version is online. Saving updates the live page right away." |
| Dirty online | edit + publish | Save | Unpublish French | loc.l5.onlineDirty |
| Saving | any | Saving… (busy) | None | loc.l5.saving |
| Saved | any | Publish French if allowed | Save (off) | loc.l5.saved |
| Save failed | edit | Try saving again | None | loc.l5.saveFail; nothing published |
| Publish failed after save | edit + publish | Retry publish | Save (off) | loc.l5.pubFail; "Saved as a draft. Publishing failed. Try publishing again." |
| Unpublish with edits | publish | Unchanged | Unpublish French | loc.l8.unpublishDirty; saved version goes offline, local edits stay, nothing is saved |
| Read-only | read | None | None | Reference button remains |
| Publish without edit | publish | Publish French | None | Fields read-only |
## Title field states
| State | Look | Message | Save |
| --- | --- | --- | --- |
| Pristine | Heading-size text, neutral border | None | Off |
| Focus | Primary 2px underline | "Changing the title doesn't change the address." | Off |
| Editing | Primary border, counter n / 200 | Same note | On |
| Unsaved | Neutral border, Unsaved changes badge | Same note | On |
| Invalid | Error border and icon | "Enter a title" | Blocked |
| Too short | Error border, counter | "Use at least 3 characters" | Blocked |
| Too long | Error border, counter 203 / 200 | "Use 200 characters or fewer" | Blocked |
| Saving | Spinner | "Saving title…" | Busy |
| Save failed | Error border and icon | "Couldn't save the title. Your text is kept." Try again | On |
## Row actions (same on every width)
| Action | Shown when | Desktop | Mobile |
| --- | --- | --- | --- |
| Open <language> | Always, for the version the row opens | Row click and menu | Row tap and menu |
| Open another language… | More than one readable version | Menu | Menu |
| Add translation… | User can create and a language is missing | Menu (dashed chip button as a shortcut) | Menu |
| Publish / Unpublish <language> | User can publish | Menu | Menu |
| Copy API URL | Always | Menu | Menu |
| Delete <language> version | User can delete | Menu | Menu |
## Coverage chips for many languages
| Width | Chips shown | Overflow | Dashed missing chips |
| --- | --- | --- | --- |
| 1440 | 5 | "+3" chip for 8 languages; named "3 more languages: …" | Last in order; buttons only if the user can create; hidden otherwise |
| 1024 | 4 (narrower column) | "+4" | Same |
| 390 | 4, under the title | "+4" | Not buttons; added from the row menu |
| Order | Default language, other existing versions, disabled-language versions, then missing | | Never shown for languages the user can't create |
## URL state (article list)
| Param | Values | Default |
| --- | --- | --- |
| site | Site key | First site |
| lang | Language code; absent means all languages | all |
| tab | all, missing, review (Published and Drafts are the status filter) | all |
| q | Search text | empty |
| status | online, draft | any |
| author | Author name | any |
| seo | attention | any |
| page | Page number, starting at 1; filter changes reset it | 1 |
| size | Rows per page | 5 in the fixture |
## Public URL pattern validation
| Case | Example | Message |
| --- | --- | --- |
| Valid | https://journal.example.com/{lang}/{slug} | Preview: https://journal.example.com/en/how-we-price-a-bathroom-renovation |
| Unknown placeholder | https://journal.example.com/{language}/{slug} | Unknown placeholder {language}. Use {lang} and {slug}. |
| Bad scheme | ftp://journal.example.com/{lang}/{slug} | Start with https:// or http://. |
| Not encoded | https://journal.example.com/my pages/{lang}/{slug} | Remove spaces and characters that need encoding. Use letters, digits, - and _. |
| Missing {slug} | https://journal.example.com/{lang} | Add {slug} so each article has its own address. |
| Invalid host | https://journal..example.com/{lang}/{slug} | Enter a valid host name, such as journal.example.com. |
| Unset | | Public URL not configured, with a link to this setting |
## Social locale per language
| State | Label | Meaning |
| --- | --- | --- |
| Derived | Derived: pt_BR | The language tag has a region. Not editable except by setting a value |
| Set | Set: fr_FR | An owner typed it. Format language_REGION |
| Not set | Not set | No region available. og:locale and og:locale:alternate are left out |
| Invalid | fr-FR | Use letters and one underscore, for example fr_FR. |
## Move article
| Case | Behavior |
| --- | --- |
| Entry point | The site select in the editor details |
| Note | "Moves all language versions of this article." Lists readable versions; a version the user can read but not edit is tagged Read only; unreadable versions are not listed or counted |
| Confirm | "Move to Atelier?" with the same list |
| Failures | Language missing in the destination (disabled languages count), address conflict (names only readable conflicting versions), no permission (neutral) |
## Release 2 groups
| Group | Release | Why |
| --- | --- | --- |
| L6 Source reference | Release 2 | Drawn in full so the checker has frames |
| L9 Freshness and review | Release 2 | Drawn in full so the checker has frames |
## Copy decisions (pass 3)
| Item | Final copy or rule |
| --- | --- |
| Editor banner: save failed | Couldn't save French. Your changes are kept here. Nothing was published. Try saving again. |
| Editor banner: publish failed | Saved as a draft. Publishing failed. Try publishing again. (detail: Your edits are saved. Only the publishing step failed.) |
| Editor banner: online | This version is online. Saving updates the live page right away. |
| Row menu, all languages | Open <language>, Open another language…, Add translation…, Unpublish <language>, Copy API URL, Delete <language> version |
| Row menu, language selected | Open <language>, Open another language…, Publish or Unpublish <language>, Copy API URL, Delete <language> version |
| Disabled-language version in the menu | Row shows the Disabled tag. Footer: "<Language> is disabled on this site. Its version stays readable and editable. It can't be published until an owner re-enables <Language>." |
| Setup done | Languages assigned. N articles now have a language. Nothing was translated, and no articles were grouped. |
| Languages list on 390 px | The version count line ("4 versions · 2 published") is shown, on its own line under the language name |
| Single-language card on 390 px | "Social locale" and "Derived: pt_BR" sit on their own line below the language |
| Partial or failed delete | Couldn't delete the article. Nothing was deleted. Every version is still there. Try again in a moment. |
| Version deleted toast | French version deleted. "<title>" was deleted. English and German weren't changed. |
| Article deleted toast | Article deleted. The article and all of its translations were deleted. |
| Move failed | Couldn't move the article. Nothing was moved. All 4 versions are still on Journal. Try again. |
| Second conflict | Their version changed again. Someone else saved this version again at <time>, before your save went through. Nothing was overwritten. Your changes are still here. |
| New article, language help | Default language for <site>. |
| Invalid host | Enter a valid host name, such as journal.example.com. |
| Toast icon box | 28 × 28 px, 16 px icon, tone colour on its -soft ground (--rc-success-soft, --rc-info-soft, --rc-warning-soft, --rc-error-soft). Body and title as in the Toast table |
| Activity: site.language.add | Added <language> to <site> |
| Activity: site.language.enable | Re-enabled <language> on <site> |
| Activity: site.language.disable | Disabled <language> on <site> |
| Activity: site.language.remove | Removed <language> from <site> |
| Activity: site.language.default | Made <language> the default language of <site> |
| Activity: site.language.social_locale | Set the social locale for <language> on <site> to <value> |
| Activity: site.public_url.update | Changed the public URL pattern of <site> |
| Activity: site.language.setup | Assigned languages to N articles on <sites> |
| Activity: article.move | Moved "<title>" from <site> to <site> |
+125
View File
@@ -0,0 +1,125 @@
# Article localization implementation handoff
Baseline imported 2026-10-31 and refreshed 2026-11-01 (completion pass) from `.claude/design`. This is a target design, not a statement that the feature exists. The user authorized this import and reconciliation. Feature and QA acceptance still happen per slice before implementation.
## Authority and imported artifacts
For localization, use this document for integration rules and corrections, `localization-tables.md` (generated from `source/locale-spec.js`) for the product tables, `screens/localization-*.md` and `states.md` for the state inventory, and `localization-corrections.md` for what the last design pass rendered, inspected and left open. Use `source/LocaleFrame.dc.html` for layout and rendered copy. This document supersedes conflicting board notes and older title/slug assumptions. Existing accepted `features/` behavior remains binding until a new accepted slice explicitly changes it. Report any remaining conflict at specification time; do not silently change behavior to match a mockup.
Imported sources are the Localization board, LocaleFrame, locale-spec.js, locale-fixtures.js (the single fixture set every list, count and pager derives from) and `localization-changelog.md` (state IDs and copy changed by the third pass). Since the third pass (2026-11-03), LocaleFrame draws inside the shared AppFrame, which gained optional editor-header slots and a width option; LocalizationShell is gone. Do not introduce a second application shell in production: continue using DashboardShell and existing editor components.
The LocaleLive prototype was deliberately not imported. The Prototype and Handoff boards remain unchanged and do not demonstrate localization. This written handoff replaces the missing localization handoff, not the missing interactive prototype. No rendered visual parity, keyboard flow, browser console check or production test is claimed by this import.
## Product model
A story groups article versions within one site. Each version keeps its article ID, creator/permissions, language, title, body, slug, SEO/social fields, alt text, publication and timestamps. Enforce one version per normalized locale per story. Files are shared references, not duplicated uploads. Authors and image selections are copied independently when requested. All versions share the story's site. Site changes therefore use an atomic story move rather than moving one linked version alone.
Site default, current editing language, temporary comparison reference and tracked review source are distinct. Changing `?ref=` changes only the comparison pane. It does not update the tracked source. No machine translation, cross-site grouping, bulk publishing, synced scrolling or text diff is included.
Use existing ID conventions for new records unless the accepted backend slice establishes a reason to differ. Example `st_01` in mockups is illustrative; it does not mandate string IDs.
## Languages and existing-content setup
Owner manages `/settings/sites/:key/languages`. Editors who need language metadata can read the allowed metadata without gaining site-management access. Gate all row menus and Re-enable actions as well as Add language.
At least one language is enabled and the default is enabled. Choose another default before retiring the current one. Remove only unused, non-default languages. Disable preserves content and online versions; editing remains permitted, but draft publication and new translation creation require re-enabling. Unpublish remains available under existing permissions. Existing disabled-language versions remain accessible through permitted lists and direct IDs.
Preserve full supported locale tags such as `pt-BR`. If only a broader tag is supported, explain the suggested substitution and require confirmation. No locale means an explicit choice, not an inferred translation. Setup assigns a language and a separate story to each existing article; it does not guess translation links.
Setup must be idempotent and atomic for its declared scope. The backend slice must define create/setup concurrency and safe retries before coding: an unassigned article must not become stranded or assigned to a different default halfway through setup. Keep stable article IDs, bodies, publication and API reads. Test migrations through the repository’s applicable persistence tests; HTTP fakes alone do not establish migration correctness.
## Editing, permissions and publication
Retain existing per-version read/update/publish/delete scopes and creator semantics. Translation membership grants no additional permission. Publishing and updating are separate permissions. A user allowed to update an online article can change its live content by saving, even without publish permission; this preserves the current direct-update model. This feature does not add unpublished revisions or editorial approval of updates.
Use this copy for an online editable version: “This version is online. Saving updates the live page right away.” For draft writers without publish: “Saving keeps it as a draft.” Do not claim saving an online article produces a draft.
Both viewports use Save and publish for a dirty offline version when update and publish are allowed. Save succeeds before publish is sent. Save failure retains dirty data and sends no publish request. If save succeeds but publishing fails, content is saved offline; offer retry publication without pretending the save failed. Recheck conflicts/permissions server-side on both operations. No transactional combined endpoint is promised. Unpublish does not discard or implicitly save local edits; explain the resulting saved/offline state and retain the draft buffer.
Titles become editable for single-language and multilingual articles, using existing 3–200 character validation. Title edits never regenerate an existing slug. Explicit slug edits are permitted before or after publication. Warn: “Links to the old address will stop working. RenewCMS does not create redirects.” No redirect capability is promised.
Retain title, body, search fields and base revision after failures. Reload-theirs requires discard confirmation; download local work before discarding when requested. Overwrite uses the revision shown by the conflict dialog as its expected revision; do not silently fetch a newer revision immediately before saving and thereby bypass confirmation of another writer's changes. A subsequent update must produce a fresh conflict.
Local recovery is scoped to authenticated user and article ID. Do not restore another user's content after account switching. Define cleanup on successful save, explicit discard, logout and access revocation in the slice acceptance criteria. Draft recovery must not grant server access.
## Visibility and list semantics
Only readable versions contribute titles, author unions, timestamps, coverage, results and counts. Never include hidden siblings in public alternates or error payloads. Readable creation conflicts may link to the version; otherwise show “French can't be created for this story.” An unreadable-version conflict has no ID, title or Open action. Missing means no readable version, not proof no stored version exists. Do not advertise stronger anti-enumeration guarantees than that policy provides.
Authenticated editorial all-language view counts stories, uses the readable default-language title or deterministic first readable locale, and opens that representative version. Updated is the latest readable version update; authors are the union of readable authors. Selected-language view counts versions. Missing-language view counts stories in sites enabling the target language and searches readable source titles. Other language-filtered searches match that language's titles. All-language search matches any readable title.
Use `lang` and `tab=all|missing|review` consistently in SPA and editorial API requests. Omit default `tab=all`. Missing requires a selected language. Review works in the active story/version mode. Preserve `page`, `size`, `q`, `status`, `site`, `seo` and existing sort syntax. Author filter is a new capability, not shipped behavior. Reset page on filter changes. Preserve the existing page-size choices and URL normalization.
For combined filters in story mode require a single readable version to satisfy the version-level predicates together; do not match an English author's version and a different French draft to fabricate a combined match. The accepted list slice specifies tab counts and their filter scope explicitly, preserving existing count behavior where possible. The union-language filter must distinguish disabled languages; missing excludes sites not enabling the selected language.
Preserve public `/v1/article/` pagination, object shape and access rules. Do not silently change anonymous lists to grouped stories. Define an explicit opt-in editorial grouping contract in the accepted backend list slice; new clients must not depend on an unannounced response-type switch.
## API target and compatibility
Existing `/v1/article/` POST/GET, `/v1/article/{id}` GET/PATCH/DELETE and PATCH publish/unpublish remain. The SPA keeps `/article/:id/edit` and the existing new-article entry. API capability tables describe proposed extensions, not functioning endpoints. Preserve snake_case and existing validation/error conventions; accepted HTTP specs establish exact bodies and status codes. Do not copy mockup JSON errors over current plain-text contracts indiscriminately.
Proposed extensions include language config/setup, article language/story metadata, translation creation, source/review tracking and atomic story moves. Use one translation-creation implementation for both UI entry points. Source must belong to the same story and be readable at submit. Copy snapshots and source revision are captured together server-side. Start-empty creates no tracked source and shows No source until explicitly linked.
Slugs become unique within `(site, lang)`. Exact public lookup is `/v1/public/site/{key}/lang/{lang}/article/{slug}` and never falls back. Story resolution is `/v1/public/site/{key}/story/{story_id}?lang=fr&fallback=default`. Without a published requested version, return not-found unless fallback was explicitly requested and the default version is published. Never try an arbitrary third language. Return actual `lang`, `requested_lang` and fallback status as appropriate. A default change affects requests omitting language; existing article-ID and explicit-language reads remain stable. Remove contrary “existing URLs never change” claims for language-omitted resolution.
Public alternates include eligible published versions only. Disabled published versions stay available by ID/exact read but are excluded from discovery alternates as designed. Decide noindex handling consistently with existing SEO output during the metadata slice.
Website URLs are not CMS API URLs. Use existing site URL conventions where compatible; a proposed owner-configured public URL pattern enables locale-aware links. No pattern/configuration means “Public URL not configured”; do not fabricate page URLs or change legacy canonical output before a slice explicitly accepts that change. Validate placeholders, URL scheme and encoding in the backend contract.
## Locale and SEO corrections
Article language determines content `lang`, direction and alternate-language identity; the SPA interface locale remains user-controlled. Existing `Site.Locale` currently participates in social metadata. Do not describe it as an existing SPA formatting setting: SPA formatting uses its own i18n locale. The feature changes article social metadata resolution deliberately rather than pretending the old field had no SEO purpose.
Preserve full article tags. Resolve social locale from explicit per-language configuration, a supported regional tag mapping, or a matching existing site locale; otherwise omit it and show Not set. Validate mappings instead of inventing a region. Bare languages do not imply a particular country. Respect existing canonical overrides.
Local SEO fallback uses the local title/body/excerpt according to existing fallback behavior. Do not silently inject a different language's site text. If a site textual fallback is used, its language must match the article language; default-language changes do not relabel existing site text. Image defaults may still be shared, with per-version alt text. The metadata slice must specify exact fallback order and conditional copy; “Description empty, tag omitted” is not universally correct when a local body/excerpt can supply it.
## Review and concurrency
Store source identity, source content revision, translation revision, reviewer and review time. Review confirmation must check both revisions and that the tracked source is unchanged. Source replacement must be in the same story, readable and cycle-free. Replacing it sets Needs review. Keep past review history when the source is deleted or access is temporarily lost; do not reveal unreadable source metadata. Access loss disables review while allowing permitted translation edits.
Content revision changes include title/body/excerpt/slug/alt/SEO/social text. Authors, site moves, image selection and publication do not increment the localization content revision. Use a separate edit concurrency version if needed so non-content updates still cannot be overwritten silently. Changed-field summaries must aggregate fields changed since the reviewed source revision, not merely the latest update. No text diff or immutable historical-source viewer is promised.
## Visual validation and implementation gaps
The board contains 16 groups and 183 states (L6 and L9 are release 2). L7s (single-language list) replaces the old Back-office Articles groups as the list's pixel-gate reference. Screen files map stable IDs to exported selectors. Markups are illustrations, not production accessible controls. Implement actual Nuxt UI input/menu/tab behavior. Retain the full existing editor toolbar; the shortened mockup toolbar does not authorize removing features.
The existing visual checker must be extended to discover localization's groups, state tables and 1024px reference where needed, with scoped fixtures and API mocks. Do not claim `task visual:check` can already verify the import. No threshold increases or exceptions are authorized. Clock-sensitive skips only apply to states whose rendering actually depends on current time, not whole features containing dates.
Known board limitations to settle in the relevant accepted slice: partial sample rows despite full-page totals; alternate empty-state fixtures; desktop/mobile action parity; read-only config controls; title validation bounds; source reference SEO metadata; restore/reload interactions; and state fixtures consistent across lists and editor. If matching the board would violate this handoff or an accepted scenario, document the discrepancy and obtain the workflow's explicit design decision before coding. Do not waive visual checks or silently improve the reference in a coder stage.
## Recommended slice order
1. Language value rules, site configuration and existing-content setup/migration contracts.
2. Story/version storage, unique constraints and authorized translation creation.
3. Article update/title/slug and revision conflict contracts, preserving public compatibility.
4. Site language settings and setup SPA.
5. Editor language navigation, translation dialog and publication scope.
6. Editorial grouped/language/missing lists with mobile filters and pagination.
7. Public story resolution, localized URL configuration and SEO metadata.
8. Optional comparison pane, tracked-source review and freshness UI.
9. Atomic story moves/deletion and integration regression coverage.
Split further to keep accepted slices reviewable. Include required backend support before each SPA slice. Each slice follows specifier acceptance → coder → size-gated cleaner/architect → hardener → qa. This order is planning guidance, not acceptance of Gherkin or permission to skip a gate.
## Open decisions and known design gaps (2026-11-01)
Settle these during specification of the slice named, before coding.
| Topic | Gap | Slice |
| --- | --- | --- |
| Setup route | The route is `/settings/sites/:key/languages/setup` but the page lists every site, and the proposed setup API is global. Decide one global page reached from a per-site banner, or a per-site page. | Languages and setup |
| Visual coverage | About 45 of the original 169 states were rendered and inspected by the designer (see `localization-corrections.md`). Icons were never checked. Unseen frames may be broken; the visual check will reveal them. | All SPA slices |
| Header widths | Editor header widths between 1024 and 1440 are specified, not drawn. The checker captures 1440, 1024 and 390 only. | Editor |
| Mobile Languages rows | Rows are taller than needed. Tune in implementation. | Languages and setup |
| Partial fixtures | Archive, Notes and Gallery exist only as single states. | Languages and setup |
| Mobile list page 2 | The designer could not reproduce the overflow-chip and tab-strip issue on mobile page 2; they removed a stray character and gave the "+N" chip a 44 px tap area. Check it against the app. | Article list |
## Third-pass decisions (2026-11-03)
- No Languages item in the sidebar. Languages is reached from Settings → Sites → [site] → Languages, and from the setup banner.
- Mobile list rows show the version count on its own line.
- The Public URL pattern preview uses the site's default language (Journal previews the English address).
- A deleted source and an unreadable source show the same message after submit: "The source isn't available to you".
- "Save over theirs" is an error-coloured outline button with a warning icon; Keep my changes stays the only filled button.
- "Delete article" is atomic: on failure nothing is removed and every version stays.
+103
View File
@@ -0,0 +1,103 @@
# Media field type
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.
+52 -3
View File
@@ -7,7 +7,7 @@
| /settings/media/cache | Cache (admin) | none | GET /v1/image-variants/cache, POST /v1/image-variants/cache/purge {scope: all|unused|variant|image} | | /settings/media/cache | Cache (admin) | none | GET /v1/image-variants/cache, POST /v1/image-variants/cache/purge {scope: all|unused|variant|image} |
| /media | Media library | page, size, q, filter, sort, view | GET /v1/media/?page=&size=&q=&filter=&variants=&sort= (page, size; total in the `X-Total-Count` header) | | /media | Media library | page, size, q, filter, sort, view | GET /v1/media/?page=&size=&q=&filter=&variants=&sort= (page, size; total in the `X-Total-Count` header) |
| /media (detail) | Variants tab | none | GET /v1/media/{id}/variants, POST and DELETE /v1/media/{id}/variants/{name} | | /media (detail) | Variants tab | none | GET /v1/media/{id}/variants, POST and DELETE /v1/media/{id}/variants/{name} |
| /articles | Articles list | page, size, tab, q | GET /v1/article/?page=&size=&q=&status= (page, size; total in the `X-Total-Count` header; array body unchanged) | | /articles | Articles list | site, lang, tab, q, status, author, seo, page, size | GET /v1/article/?page=&size=&q=&status=&site=&seo= returns `{ items, total, page, size, counts }`. Proposed on top: `lang`, `tab=all\|missing\|review` (see Localization). The old array body with `X-Total-Count` no longer applies to articles; media and authors still use it |
| /activity | Activity | q, actor, category, outcome, security, range, from, to, page, size | GET /v1/activity (page, size), GET /v1/activity/export (shipped, CSV) | | /activity | Activity | q, actor, category, outcome, security, range, from, to, page, size | GET /v1/activity (page, size), GET /v1/activity/export (shipped, CSV) |
| /integration | Integration | none | none | | /integration | Integration | none | none |
| /settings/sites | Sites (owner only; other roles get a 403 page and no sidebar entry): list, add and edit slide-over, delete with reassignment. The key is read-only after creation | none | GET/POST /v1/site/, PATCH/DELETE /v1/site/{id} (DELETE takes `reassign_to`) | | /settings/sites | Sites (owner only; other roles get a 403 page and no sidebar entry): list, add and edit slide-over, delete with reassignment. The key is read-only after creation | none | GET/POST /v1/site/, PATCH/DELETE /v1/site/{id} (DELETE takes `reassign_to`) |
@@ -22,11 +22,11 @@
| /content/:key | Entry list (any verified user). Available now | page, size, sort | GET /v1/content-type/{key}, GET /v1/content-type/{key}/entry?page=&size=&sort= | | /content/:key | Entry list (any verified user). Available now | page, size, sort | GET /v1/content-type/{key}, GET /v1/content-type/{key}/entry?page=&size=&sort= |
| /content/:key/new | New entry (any verified user). Available now | none | POST /v1/content-type/{key}/entry | | /content/:key/new | New entry (any verified user). Available now | none | POST /v1/content-type/{key}/entry |
| /content/:key/:id | Entry editor (any verified user). Available now | none | GET/PUT/DELETE /v1/content-type/{key}/entry/{id} | | /content/:key/:id | Entry editor (any verified user). Available now | none | GET/PUT/DELETE /v1/content-type/{key}/entry/{id} |
| /settings/permissions | Permissions grid (owner or admin). Later | none | not built | | /settings/permissions | Retired. 301 to /settings/roles (see Roles and permissions below) | none | not built |
## Pagination in the URL (Articles, Media) ## Pagination in the URL (Articles, Media)
`/articles?page=2&size=50` and `/media?page=7&size=50`. Parameter names follow the repo (activity already uses `page` and `size`). Allowed sizes 5, 25, 50, 100. Defaults `page=1`, `size=25`, omitted from the URL when default. Changing search, tab, filter or size resets `page` to 1. `page` above the last page redirects (replace) to the last page and shows "That page doesn't exist. Showing the last page." An invalid `size` falls back to 25. `/articles?page=2&size=50` and `/media?page=7&size=50`. Parameter names follow the repo (activity already uses `page` and `size`). Allowed sizes 5, 25, 50, 100. Defaults `page=1`, `size=25`, omitted from the URL when default. Changing search, tab, filter or size resets `page` to 1. `page` above the last page redirects (replace) to the last page and shows "That page doesn't exist. Showing the last page." An invalid `size` falls back to 25.
**API:** `GET /v1/article/` accepts `page` (default 1) and `size` (5, 25, 50, 100; default 25), as `GET /v1/activity` does. The body stays a JSON array so existing consumers keep working; the total comes back in `X-Total-Count` (the response shape is to be confirmed with the specifier). Anonymous callers only see online articles, and the total counts only those. Invalid `page` or `size` answers 400, the same as Activity. **API:** `GET /v1/article/` accepts `page` (default 1) and `size` (5, 25, 50, 100; default 25), as `GET /v1/activity` does. The body is `{ items, total, page, size, counts }` (`counts` feeds the tab numbers); articles no longer send `X-Total-Count`, Media and Authors still do. Anonymous callers only see online articles, and the total counts only those. Invalid `page` or `size` answers 400, the same as Activity.
**Media API:** `GET /v1/media/` takes the same `page` and `size`, with the same 400 and the total in `X-Total-Count`; the array body stays. The earlier `cursor` and `limit` parameters are replaced by them. **Media API:** `GET /v1/media/` takes the same `page` and `size`, with the same 400 and the total in `X-Total-Count`; the array body stays. The earlier `cursor` and `limit` parameters are replaced by them.
@@ -53,3 +53,52 @@ No new page routes. The panel and dialog are overlays on `/article/:id/edit`: `?
## Custom content types in the URL ## Custom content types in the URL
`/content/events?page=2&size=50&sort=created_at:desc`. `page` and `size` follow Articles (sizes 5, 25, 50, 100; default 25). `sort` is one parameter, `<id|created_at|updated_at>:<asc|desc>`, default `updated_at:desc`. Defaults are omitted from the URL; a size or sort change resets `page` to 1; invalid values are replaced silently by the default; a `page` past the end falls back to the last page. The response carries `total`, `page`, `size` and `sort`: use them for the summary ("Showing 1–5 of 37"), the pager and the "37 entries use this content type" line of the review step. No filter or search on custom fields yet. Auth: `/schema*` owner or admin (403 page otherwise), `/content*` any verified user (unverified accounts are redirected to /register/pending). Unknown type: 404 content_type_not_found page. Unknown entry: 404 entry_not_found page. `/content/events?page=2&size=50&sort=created_at:desc`. `page` and `size` follow Articles (sizes 5, 25, 50, 100; default 25). `sort` is one parameter, `<id|created_at|updated_at>:<asc|desc>`, default `updated_at:desc`. Defaults are omitted from the URL; a size or sort change resets `page` to 1; invalid values are replaced silently by the default; a `page` past the end falls back to the last page. The response carries `total`, `page`, `size` and `sort`: use them for the summary ("Showing 1–5 of 37"), the pager and the "37 entries use this content type" line of the review step. No filter or search on custom fields yet. Auth: `/schema*` owner or admin (403 page otherwise), `/content*` any verified user (unverified accounts are redirected to /register/pending). Unknown type: 404 content_type_not_found page. Unknown entry: 404 entry_not_found page.
## Roles and permissions
| Route | Purpose | Access |
|---|---|---|
| /settings/roles | Roles list | Roles: view |
| /settings/roles/new | New role | Roles: manage |
| /settings/roles/:id | Role editor (read-only without manage) | Roles: view |
| /settings/permissions | Retired. 301 to /settings/roles | n/a |
API: GET/POST /v1/role · GET/PUT/DELETE /v1/role/{id} · POST /v1/role/{id}/reassign · PUT /v1/user/{id}/role · POST /v1/site/transfer-ownership · GET /v1/me · GET /v1/permission. Errors: 403 missing_permission, 403 role_locked, 409 role_has_members, 409 role_name_taken, 409 role_conflict.
Needs backend:
| Item | Detail |
|---|---|
| Role storage | Table role (id, name, description, built_in, locked, version) and role_permission (role_id, key, scope none|own|all). One role_id on user. Built-ins seeded and non-deletable. |
| Endpoints | GET/POST /v1/role · GET/PUT/DELETE /v1/role/{id} · POST /v1/role/{id}/reassign · PUT /v1/user/{id}/role · POST /v1/site/transfer-ownership · GET /v1/me (role and permissions) · GET /v1/permission (catalogue) |
| created_by | Add created_by (user id) to articles and entries so Own scope can be checked on read, update, delete and publish. Backfill from existing author or activity data. |
| Enforcement | Server checks every call against role permissions and the no-escalation rules. API keys resolve the creator's current role on each request. |
| Version field | role.version for the conflict state (409 role_conflict). |
| Activity events | role.create, role.edit (with a diff of added and removed permissions), role.delete, role.reassign, user.change_role, user.transfer_ownership. Present tense, as the backend emits them. |
## Account: change email, export, delete
| Route | Screen | Auth | API (assumed) |
|---|---|---|---|
| /account/email/confirm?c=CODE | Verify new email (AuthCard). States in screens/account.md | Session required; without one, inline log in (as /register/validate) | POST /v1/auth/email/confirm |
| /profile | Gains change email, Your data, Danger zone | Any verified user | POST /v1/auth/email/change, POST /v1/auth/email/resend, DELETE /v1/auth/email/change, GET /v1/user/me/export, DELETE /v1/user/me |
| /login?reason=account-deleted | One-time message after deletion | Public | none |
## Localization (proposed; existing routes unchanged)
Existing: /articles, /article/:id/edit, GET/POST /v1/article/, PATCH /v1/article/{id}, PATCH /v1/article/{id}/publish, PATCH /v1/article/{id}/unpublish, DELETE /v1/article/{id}.
| Route | Purpose | Access |
|---|---|---|
| /settings/sites/:key/languages | Site languages, default, disable, re-enable, remove, social locale per language. The only languages route (no global Languages page) | Owner edits, others read |
| /settings/sites/:key/languages/setup | First-time setup. :key is the site it was opened from; the page lists every site with unlabelled articles | Owner |
| /settings/sites/:key/public-url | Public URL pattern (placeholders {lang}, {slug}) | Owner edits, others read |
| /articles?site&lang&tab=all\|missing\|review&q&status&author&seo&page&size | Article list. Defaults omitted; filter changes reset page | Per article permission |
| /article/:id/edit | Editor, one id per language version | Per version capability |
| /article/:id/edit?ref=:sourceId | Temporary source reference (release 2). Does not change the tracked source | Read access to the reference |
| /article/:id/edit?dialog=add-translation&lang=fr | Add translation dialog | create-translation |
| /article/:id/edit?panel=seo | Search and sharing panel | edit |
Removed: /settings/languages and /settings/languages/setup (replaced by the site-scoped routes above). The old list params `mode` and `needs_review` are gone; `tab` replaces them.
Proposed API: GET /v1/article/ adds lang, tab=all|missing|review. GET /v1/article/{id} adds lang, story_id, capabilities[], translations[] (readable only), source. POST /v1/article/ adds lang, story_id, source_article_id, copy. POST /v1/article/{id}/translations. POST /v1/article/{id}/review (release 2). PATCH /v1/article/{id}/source (release 2). GET/PUT /v1/site/{key}/languages (adds social_locale per language). GET/PUT /v1/site/{key} adds public_url_pattern. GET/POST /v1/language/setup. POST /v1/story/{story_id}/move. PATCH /v1/article/{id} accepts if_revision (conflict response). Public: GET /v1/public/site/{key}/lang/{lang}/article/{slug} and GET /v1/public/site/{key}/story/{story_id}?lang=&fallback=default. The earlier GET /v1/public/site/{key}/article/{slug}?lang= is removed.
Sidebar: there is no Languages item. Languages is reached only from Settings → Sites → [site] → Languages (and the Set article languages banner for first-time setup). The sidebar item list in components.md is unchanged.
Field name is `lang` everywhere; the public list of other versions is `alternates`, the editor list is `translations`.
Details: see Localization board tables (Public lookup and URLs, Visibility policy).
+72
View File
@@ -0,0 +1,72 @@
# Account: change email, export my data, delete account
Route: `/profile` (extends the Account card, adds "Your data" and "Danger zone" cards). Verification landing: `/account/email/confirm?c=CODE`. API calls are assumed, not specified.
Placement: Profile already holds the read-only Email in the Account card and the Password card, so the email change extends that card; the two other features are cards at the bottom. No new navigation. Order: Display name, Account, Your role, Author profile, Password, Your data, Danger zone.
Boards: `RenewCMS Screens Account.dc.html` (Profile states), `RenewCMS Screens Auth.dc.html` (groups "Verify new email" and "Account deleted"). Frames: `AppFrame`, `AccountCards`, `AuthCard`. Copy source: `account-copy.js`. English only.
## Change email
| State | Copy |
|---|---|
| Default | "Email" field, link "Change email" |
| Form | "New email address" · "Current password" · "We'll send a verification link to the new address. Your email stays the same until you open it." · "Cancel" · "Send verification link" |
| Invalid format | "Enter a full email address, like name@example.com." |
| Same as current | "That's already your email address." |
| Password missing | "Enter your current password." |
| Wrong password (403) | "That password isn't correct. Try again." |
| Sending | "Sending…" |
| Pending | "Waiting for verification" · "We sent a link to marta.alves@atelier-renew.example. Until you open it, you keep logging in with marta@renew.example." · "Resend link" · "Cancel change"; toast "Verification link sent" / "Check marta.alves@atelier-renew.example. The link works once, within 2 hours." |
| Resending | "Sending…" |
| Resent | toast "Link sent again" / "The previous link no longer works." |
| Resend rate limited (429) | "Resend in 4:30" (disabled) · "Too many requests. Try again in a few minutes." |
| Cancelled | toast "Email change cancelled" / "You keep logging in with marta@renew.example." |
| Rate limited (429) | "Too many requests. Try again in a few minutes.", Send disabled |
| Server or network | "Something went wrong on our side. Nothing was changed. Try again in a moment." |
Rules: the old email stays active for login until the link is opened. The old address gets the notice email at request time. A request for an address already in use answers like success, so the UI and the response never reveal that an account exists.
## Verification landing (AuthCard)
| State | Copy |
|---|---|
| Confirming | "Confirming your new email…" |
| Success | "Your email address has changed" · "Your account now uses marta.alves@atelier-renew.example. Use it the next time you log in." · "Go to profile"; toast "Email address changed" / "Your account now uses marta.alves@atelier-renew.example." |
| Invalid or expired (403) | "This link doesn't work" · "It may have expired (links last 2 hours), been cancelled or already been used." · "Request a new link from your profile." · "Go to profile" |
| Address unavailable (409) | "We couldn't change your email address" · "This address can't be used for your account. Go back to your profile and try a different one." · "Go to profile" (same copy whether the address is taken or rejected) |
| No session (401) | "Log in to confirm your new email" · "You opened this link somewhere you're not logged in. Log in here and we'll confirm the change right after." · "Log in and confirm" |
| Missing code | "This link is incomplete" · "The confirmation code is missing. Open the link from your email again, or copy the full address into your browser." · "Go to log in" |
| Server error | "Couldn't confirm the change" · "Something went wrong on our side. Nothing was changed. Try again in a moment." · "Try again" |
## Your data
Contents listed in the card: Profile (Username, display name, email, role and author profile.); Authored content (Your articles and entries.); Uploaded media (References to the files you uploaded.); Account activity (Your log-ins and the actions recorded under your name.). Card copy: "Your data" · "Download a copy of the personal data RenewCMS holds about you, as JSON files in a ZIP.".
| State | Copy |
|---|---|
| Direct (recommended): default | "Download my data" · "Ready in a few seconds." |
| Preparing | "Preparing download…" |
| Started | toast "Download started" / "renewcms-export-marta-2026-10-29.zip is in your downloads." |
| Rate limited (429, one per 15 minutes, clock-sensitive) | "You can export once every 15 minutes" · "Your last export was at 09:41. Try again in 12 minutes." · "Available in 12:00" |
| Error | "Couldn't prepare your data" · "Nothing was changed. Try again in a moment." |
| Alternative, emailed link: default | "Request my data" · "Larger exports are prepared in the background. We'll email a download link to marta@renew.example when it's ready." |
| Requested | "We're preparing your export" · "This can take a few minutes. We'll email a link to marta@renew.example when it's ready." · "Export requested"; toast "Export requested" / "Check marta@renew.example in a few minutes." |
| Already in progress | "An export is already being prepared" · "We'll email a link to marta@renew.example when it's ready." |
Decision: direct download. An emailed export link is out of scope.
## Delete account
Danger zone: "Danger zone" · "Delete your account and your personal data. This can't be undone." · "Delete my account".
| State | Copy |
|---|---|
| Dialog | "Delete your account?" · "This permanently deletes your account. It can't be undone." · list: "Your username, display name and email address", "Your author profile and API keys", "Your sessions: you'll be logged out everywhere" · "Your articles and media stay" / "They stay on the site, credited to "Deleted user". Your name is removed from them." · "Export my data first" · "Current password" · "Type DELETE to confirm" · "Keep my account" · "Delete my account" |
| Empty, typing | Confirm disabled until password is filled and the word equals "DELETE" (exact, case-sensitive) |
| Wrong password (403) | "That password isn't correct. Try again." |
| Deleting | "Deleting…"; fields and Cancel disabled; then sign out and redirect to /login?reason=account-deleted |
| Rate limited (429) | "Too many requests. Try again in a few minutes." |
| Server error | "Couldn't delete your account. Nothing was deleted. Try again in a moment." |
| Blocked: last Owner or administrator | "You can't delete your account yet" · Owner: "You are the last Owner. RenewCMS needs at least one. Transfer ownership or promote another user first, then come back to delete your account." · Administrator: "You are the last administrator. RenewCMS needs at least one. Promote another user first, then come back to delete your account." · "Back to profile" · "Go to Users" |
| Blocked: cannot be deleted | "This account can't be deleted" · "RenewCMS can't delete this account right now. Ask an administrator to help, then try again." · "Back to profile" |
| Login after deletion | "Your account has been deleted" · "Your articles and media were kept without your name." |
Blocked dialogs have no close button, do not close on Escape or backdrop click, and always give a next step.
Authored content: anonymized to "Deleted user", stated in the dialog. Export-ready email: the link needs a logged-in session, stated in the email and the card hint. Account-deleted email: generic, no personal data, sent to the address the account had at deletion.
+30
View File
@@ -93,3 +93,33 @@ Route: `/activity`. API: GET /v1/activity (server scoped to the user).
| 1 | Default | No summary strip, no actor filter, no Export. Title becomes My activity. | | | 1 | Default | No summary strip, no actor filter, no Export. Title becomes My activity. | |
| 2 | Empty | The user has not done anything yet. | | | 2 | Empty | The user has not done anything yet. | |
| 3 | Details | Same slide-over, own event. | | | 3 | Details | Same slide-over, own event. | |
## Roles sync (pass 6): event names, failed sentences, categories
Event names are present tense, as the backend emits them: role.create, role.edit, role.delete, role.reassign, user.change_role, user.transfer_ownership. The outcome is a field; a failed event keeps its name and uses the failed sentence.
| Event | Sentence | Failed sentence |
|---|---|---|
| role.create | Role Contributor created | Failed to create the role Contributor |
| role.edit | Role Contributor edited | Failed to edit the role Contributor |
| role.delete | Role Intern deleted | Failed to delete the role Intern |
| role.reassign | Moved 3 members from Intern to Writer (one member: Moved 1 member from Intern to Writer) | Failed to move 3 members from Intern to Writer |
| user.change_role | Ines Duarte's role changed from Writer to Content lead | Failed to change the role of Ines Duarte |
| user.remove | Removed Ines Duarte | Failed to remove Ines Duarte |
| user.transfer_ownership | Ownership transferred from Marta Alves to Jonas Weber | Failed to transfer ownership to Jonas Weber |
Failed template: "Failed to {verb} {object}". A failed row shows the Failed badge after the sentence; the details panel shows "Why it failed" with the reason from the API.
Category filter values: Articles, Media, Users and invites (was "Users & invites"), Roles (new), API keys, Authentication, System. French and the failed sentences for every event are in screens/roles.md, group 8 and the table "Activity events: failed sentences, EN and FR". Frames: Roles board, group "8 Activity".
### Fallback wordings (app sync)
| Event | Condition | Sentence |
|---|---|---|
| role.reassign | target role unknown | Moved 3 members from Intern to another role |
| role.reassign | count unknown | Moved the members of the role Intern |
| role.reassign | failed, count unknown | Failed to move the members of the role Intern |
| role.reassign | failed, one member | Failed to move 1 member |
| user.remove | name unknown | Removed a user (proposal, not in the app) |
Event names match the backend: role.create, role.edit, role.delete, role.reassign, user.change_role, user.transfer_ownership, user.remove.
+7 -4
View File
@@ -1,10 +1,10 @@
# Articles # Articles
Route: `/article`, `/articles?page=2&size=50`. API: GET /v1/article/ · PATCH …/publish · PATCH …/unpublish · DELETE /v1/article/{id} · GET /v1/article/?page=&size=&q=&status= (page, size; total in the X-Total-Count header; invalid values are normalised in the URL, never shown as an error). Route: `/article`, `/articles?page=2&size=50`. API: GET /v1/article/ · PATCH …/publish · PATCH …/unpublish · DELETE /v1/article/{id} · GET /v1/article/?page=&size=&q=&status=&site=&seo= returns { items, total, page, size, counts } (invalid values are normalised in the URL, never shown as an error).
Rows update when the server responds, not optimistically. Search, tab and sort are stored in the query string. Rows update when the server responds, not optimistically. Search, tab and sort are stored in the query string.
Visual reference: `RenewCMS Screens Back-office.dc.html`, groups "Articles", "Articles: pagination". Frames: `AppFrame.dc.html` (shell, sidebar, topbar, drawer) plus the screen frame where listed in components.md. Visual reference and pixel gate: `RenewCMS Screens Localization.dc.html`, group L7s (single-language site) and L7 (several languages), drawn by LocaleFrame with the shipped AppPaginator. The Back-office groups "Articles" and "Articles: pagination" are superseded for the list layout; they stay as the copy reference for states the new groups do not repeat. Frames: `AppFrame.dc.html` (shell, sidebar, topbar, drawer) plus the screen frame where listed in components.md.
## Copy per state (generated from the board source, pass 2) ## Copy per state (generated from the board source, pass 2)
@@ -47,12 +47,12 @@ Rows update when the server responds, not optimistically. Search, tab and sort a
| 10 | Row vanished (404) | Any row action gets a 404. | "That article no longer exists" / "It was deleted somewhere else, so we removed it from the list." | | 10 | Row vanished (404) | Any row action gets a 404. | "That article no longer exists" / "It was deleted somewhere else, so we removed it from the list." |
| 11 | Delete: confirm | Delete… from the row menu. | | | 11 | Delete: confirm | Delete… from the row menu. | |
| 12 | Delete: in progress | DELETE in flight. The dialog can't be dismissed. | | | 12 | Delete: in progress | DELETE in flight. The dialog can't be dismissed. | |
| 13 | Delete: failed | 500, a partial failure where the article is kept. The error shows inside the dialog. | "Couldn't delete the article, so it's still there. Try again in a moment." | | 13 | Delete: failed | 500 or network failure. Deleting is atomic, so nothing is removed and every version is still there. The error shows inside the dialog. | "Couldn't delete the article." / "Nothing was deleted. Every version is still there. Try again in a moment." |
| 14 | Deleted | 204: the row is removed and focus moves to the next row. This is also where a delete from the editor ends up. | "Article deleted" / ""Winter checklist for timber windows" and its images are gone." | | 14 | Deleted | 204: the row is removed and focus moves to the next row. This is also where a delete from the editor ends up. | "Article deleted" / ""Winter checklist for timber windows" and its images are gone." |
### Articles: pagination (group "Articles: pagination", 11 states) ### Articles: pagination (group "Articles: pagination", 11 states)
Route: `/articles?page=2&size=50`. API: GET /v1/article/?page=&size=&q=&status= (page, size; total in the X-Total-Count header; invalid values are normalised in the URL, never shown as an error). Route: `/articles?page=2&size=50`. API: GET /v1/article/?page=&size=&q=&status=&site=&seo= returns { items, total, page, size, counts } (invalid values are normalised in the URL, never shown as an error).
Page and page size live in the URL as page and size. Defaults (page 1, size 25) are omitted. Allowed sizes 5, 25, 50, 100. Search, tab or sort changes reset to page 1. Rows equal the page size; the frames draw at most 10 rows. The paginator hides when everything fits on one page; the summary stays. Mobile shows Previous, "Page N of M" and Next. Keyboard: Tab reaches page size, first, previous, each page, next, last; Enter or Space activates; the current page has aria-current="page"; ArrowDown opens the page-size list, Enter selects, Esc closes. Page and page size live in the URL as page and size. Defaults (page 1, size 25) are omitted. Allowed sizes 5, 25, 50, 100. Search, tab or sort changes reset to page 1. Rows equal the page size; the frames draw at most 10 rows. The paginator hides when everything fits on one page; the summary stays. Mobile shows Previous, "Page N of M" and Next. Keyboard: Tab reaches page size, first, previous, each page, next, last; Enter or Space activates; the current page has aria-current="page"; ArrowDown opens the page-size list, Enter selects, Esc closes.
@@ -99,3 +99,6 @@ A quiet indicator in the Status cell on desktop and under the title on mobile ca
| 3 | Needs attention: none | Nothing to show with the toggle on. | Nothing needs attention · Every article has a clean check. Suggestions are optional, so this is just a bonus. · Show all articles | | 3 | Needs attention: none | Nothing to show with the toggle on. | Nothing needs attention · Every article has a clean check. Suggestions are optional, so this is just a bonus. · Show all articles |
Filter: "Needs attention" sets `?seo=suggestions` and resets `page` to 1. Tab counts do not change. Single-site installs behave the same; the Site filter stays hidden. Filter: "Needs attention" sets `?seo=suggestions` and resets `page` to 1. Tab counts do not change. Single-site installs behave the same; the Site filter stays hidden.
## Localization
Localization: modes All languages (stories), Language selected (versions), Missing language (stories); mobile filter sheet, scrollable tabs, pager; state in URL. See routes.md.
+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.md`, section 3.5. Board groups: 5 Content and entry list.
+3
View File
@@ -175,3 +175,6 @@ A read-only dialog (desktop, 720 px) or bottom sheet (mobile) with the resolved
| 4 | Draft article | Drafts answer 404 to anonymous callers. | This article is a draft. The API returns this data only to signed-in callers until it is published. | | 4 | Draft article | Drafts answer 404 to anonymous callers. | This article is a draft. The API returns this data only to signed-in callers until it is published. |
| 5 | Loading | Copy is disabled. | – | | 5 | Loading | Copy is disabled. | – |
| 6 | Error | GET failed. Nothing in the article changes. | Couldn't load the SEO data · GET /v1/article/12/seo failed. Your article is unchanged. Try again in a moment. · Try again | | 6 | Error | GET failed. Nothing in the article changes. | Couldn't load the SEO data · GET /v1/article/12/seo failed. Your article is unchanged. Try again in a moment. · Try again |
## Localization
Localization: actions render from per-version capabilities (read, edit, publish, delete, create-translation, review); title is an inline input; slug changes only via Edit slug. See Localization board.
+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.md`, section 3.6. Board groups: 6 Entry editor.
+97 -4
View File
@@ -12,10 +12,10 @@ Sticky section index on the right (desktop), "Jump to" select (mobile). A refere
- Intro: "RenewCMS is headless: it stores your content and your own code displays it. There are two ways in. Public read-only access lets a website read online articles. API keys let a script or service manage articles, media and users without the back-office." - Intro: "RenewCMS is headless: it stores your content and your own code displays it. There are two ways in. Public read-only access lets a website read online articles. API keys let a script or service manage articles, media and users without the back-office."
- Base URL: label "Base URL", a CodeSnippet with one tab ("Base URL") and the button "Copy" / "Copied" (2 s, announced). - Base URL: label "Base URL", a CodeSnippet with one tab ("Base URL") and the button "Copy" / "Copied" (2 s, announced).
- Authentication, card "Public": "No key needed. Two read-only routes, and only online articles are returned." `GET /v1/article/`, `GET /v1/article/{id}`. - Authentication, card "Public": "No key needed. Two read-only routes, and only online articles are returned." `GET /v1/article/`, `GET /v1/article/{id}`.
- Card "API key": "Send `Authorization: Bearer rcms_…`. Requests act as the user who created the key, with that user's role (owner or admin). A key never has more rights than its creator." CodeSnippet tabs curl, fetch (GET /v1/auth/me). "Keys start with `rcms_` and are shown in full once, when you create them." Link "Manage API keys". - Card "API key": "Send `Authorization: Bearer rcms_…`. Requests act as the user who created the key, with that user's role as it is now. A key never has more rights than its creator. A route that needs a permission answers 403 "missing_permission" to a key whose creator's role lacks it." CodeSnippet tabs curl, fetch (GET /v1/auth/me). "Keys start with `rcms_` and are shown in full once, when you create them." Link "Manage API keys".
- Note 1: "A key can't create, list or revoke API keys, log in, register, verify or reset a password, or call anything under `/v1/system`. Those routes answer 403 "This action needs a real session." An invalid, unknown, expired or revoked key answers 401, even on public routes, and so does a key whose user was deleted or unverified." - Note 1: "A key can't create, list or revoke API keys, log in, register, verify or reset a password, or call anything under `/v1/system`. Those routes answer 403 "This action needs a real session." An invalid, unknown, expired or revoked key answers 401, even on public routes, and so does a key whose user was deleted or unverified."
- Note 2: "Each key can make 120 requests per minute. Beyond that the API answers 429 with a `Retry-After` header." - Note 2: "Each key can make 120 requests per minute. Beyond that the API answers 429 with a `Retry-After` header."
- Groups: Articles (7), Media (6), Users and invites (6), Settings (1), Session only (12 routes, 3 sub-groups; every `/v1/system` route is in this group). Session-only banner: "These routes need a signed-in browser session. With an API key they answer 403 "This action needs a real session."" - Groups, in index order: Authentication, Articles (7), Search and sharing (2), Content types (5), Entries (5), Built-in types (2), Media (10), Sites and authors (2), Images and variants, Users and invites (6), Settings (1), Session only (35 routes in 6 sub-groups: System, Sign in and account, API key management, Sites and authors writes, Image variants, Activity; every `/v1/system` route is in this group), Errors, Notes. Session-only banner: "These routes need a signed-in browser session. With an API key they answer 403 "This action needs a real session.""
- Errors: "Every error is a plain-text body with a single sentence. The status code is in the HTTP status line, and the Content-Type is text/plain." Table 400, 401, 403, 404, 429, 500 with the real messages below. The 403 row has a note line under it: "Site SEO defaults are owner only. Article SEO fields need only the right to edit the article." (12/18, `--ui-text-muted`, in the cause column, 2 px under the cause text). It is the only row with a note; rows below it move down by the wrapped note height (two 18 px lines on desktop, three on mobile, plus 2 px). Sample: a status line plus the text body (`HTTP/1.1 403 Forbidden`, `Content-Type: text/plain`, blank line, `This action needs a real session.`). - Errors: "Every error is a plain-text body with a single sentence. The status code is in the HTTP status line, and the Content-Type is text/plain." Table 400, 401, 403, 404, 429, 500 with the real messages below. The 403 row has a note line under it: "Site SEO defaults are owner only. Article SEO fields need only the right to edit the article." (12/18, `--ui-text-muted`, in the cause column, 2 px under the cause text). It is the only row with a note; rows below it move down by the wrapped note height (two 18 px lines on desktop, three on mobile, plus 2 px). Sample: a status line plus the text body (`HTTP/1.1 403 Forbidden`, `Content-Type: text/plain`, blank line, `This action needs a real session.`).
- Notes: image URL prefix, CORS (existing copy), and "Article routes accept `?format=markdown`, `?format=html` or `?format=json` to choose how `body` is returned. With `json`, `body` is the stored JSON structure. Articles have `body_format: markdown` by default." - Notes: image URL prefix, CORS (existing copy), and "Article routes accept `?format=markdown`, `?format=html` or `?format=json` to choose how `body` is returned. With `json`, `body` is the stored JSON structure. Articles have `body_format: markdown` by default."
@@ -23,7 +23,7 @@ Sticky section index on the right (desktop), "Jump to" select (mobile). A refere
- Collapsed (44 px row): method badge, mono path, one-line description, chips, chevron. Desktop is one line; mobile is three (method and path, description, chips). - Collapsed (44 px row): method badge, mono path, one-line description, chips, chevron. Desktop is one line; mobile is three (method and path, description, chips).
- Expanded: "Request body" table (Name, Type, Required, Rule; "No request body." when empty), tabs fetch / curl / Response in one CodeSnippet with Copy, then "Errors": status chip plus one-line caption (also its `title` tooltip). - Expanded: "Request body" table (Name, Type, Required, Rule; "No request body." when empty), tabs fetch / curl / Response in one CodeSnippet with Copy, then "Errors": status chip plus one-line caption (also its `title` tooltip).
- Session only: dashed border, muted fill, lock icon, "Session only" chip, no method colour, no expand. - Session only: dashed border, muted fill, lock icon, "Session only" chip, no method colour, no expand.
- Chips: access "Public", "Verified user", "Owner only"; key "API key OK" (success soft) or "Session only" (dashed, muted). - Chips: access "Public", "Verified user", "Needs permission" (routes gated by a role permission; the permission name is in the route description), "Owner only"; key "API key OK" (success soft) or "Session only" (dashed, muted).
- Method badges: GET `--ui-bg-inverted`, POST success soft, PATCH warning soft, DELETE error soft. Existing tokens only. - Method badges: GET `--ui-bg-inverted`, POST success soft, PATCH warning soft, DELETE error soft. Existing tokens only.
## States ## States
@@ -34,7 +34,7 @@ Desktop 1440×900, mobile 390×844, light and dark.
Plain text, one sentence. Used in the table and in the per-endpoint error captions. Plain text, one sentence. Used in the table and in the per-endpoint error captions.
- 400: "The request cannot be processed due to a mismatch in the format of the body." / "The expiry must be a date in the future." Image requests (`/media/photo.png?v=`) answer 400 with a JSON body (`status`, `error`, `message`, `detail`) in two cases: `{ "status": 400, "error": "unknown_variant", "message": "Unknown variant", "detail": "unknown" }` for an unknown or disabled variant, and `{ "status": 400, "error": "unsupported_parameter", "message": "Unsupported parameter", "detail": "width" }` for any other query parameter (`width`, `height`, `format`, `quality`). Both are rows of the "Responses" table in "Images and variants". - 400: "The request cannot be processed due to a mismatch in the format of the body." / "The expiry must be a date in the future." Image requests (`/media/photo.png?v=`) answer 400 with a JSON body (`status`, `error`, `message`, `detail`) in two cases: `{ "status": 400, "error": "unknown_variant", "message": "Unknown variant", "detail": "unknown" }` for an unknown or disabled variant, and `{ "status": 400, "error": "unsupported_parameter", "message": "Unsupported parameter", "detail": "width" }` for any other query parameter (`width`, `height`, `format`, `quality`). Both are rows of the "Responses" table in "Images and variants".
- 401: "You must be logged in to access this resource." - 401: "You must be logged in to access this resource."
- 403: "This action needs a real session." (session-only routes called with a key) / "Only the owner can do this." / "You must verify your account to access this resource." Note under the 403 row: "Site SEO defaults are owner only. Article SEO fields need only the right to edit the article." The inline parenthetical that said the same thing in the row's cause text was removed to avoid saying it twice. - 403: "This action needs a real session." (session-only routes called with a key) / `missing_permission` (the role of the user, or of the key's creator, lacks the permission the route needs) / "You must verify your account to access this resource." Note under the 403 row: "`missing_permission` is the literal body, not a sentence. Site SEO defaults need the permission to manage sites. Article SEO fields need only the right to edit the article." The inline parenthetical that said the same thing in the row's cause text was removed to avoid saying it twice.
- 404: "Article not found" / "Image not found" / "Invite not found" / "API key not found" / `site_not_found` (GET /v1/site/{key}/sitemap only; body is the code, not a sentence) - 404: "Article not found" / "Image not found" / "Invite not found" / "API key not found" / `site_not_found` (GET /v1/site/{key}/sitemap only; body is the code, not a sentence)
- 429: "Too many requests. Please try again later." A per-key limit also sends `Retry-After`. - 429: "Too many requests. Please try again later." A per-key limit also sends `Retry-After`.
- 500: "Internal server error" - 500: "Internal server error"
@@ -114,3 +114,96 @@ New group "Search and sharing" after Articles, in the sidebar index and the mobi
- GET /v1/article/{id}/seo: the resolved SEO object. Fields: title, description, canonical_url, robots, og{type,title,description,url,site_name,image,image_alt,locale}, twitter{card,title,description,image,image_alt}, image{url,alt,source}, authors[{name,url,same_as}], published_at, modified_at, fallbacks, json_ld. Drafts answer 404 to anonymous callers. - GET /v1/article/{id}/seo: the resolved SEO object. Fields: title, description, canonical_url, robots, og{type,title,description,url,site_name,image,image_alt,locale}, twitter{card,title,description,image,image_alt}, image{url,alt,source}, authors[{name,url,same_as}], published_at, modified_at, fallbacks, json_ld. Drafts answer 404 to anonymous callers.
- GET /v1/site/{key}/sitemap?page=&size=: yes, shown per site by key. Items: { url, modified_at, noindex }. Total in X-Total-Count. Sizes 25, 50, 100, 500, default 100. Errors: 400 "The request cannot be processed due to a mismatch in the format of the body." (same text as the other routes; bad `page` or `size`), 401, 404 `site_not_found` (unknown site key; this is the body the API returns, shown as a code and not rewritten as prose). - GET /v1/site/{key}/sitemap?page=&size=: yes, shown per site by key. Items: { url, modified_at, noindex }. Total in X-Total-Count. Sizes 25, 50, 100, 500, default 100. Errors: 400 "The request cannot be processed due to a mismatch in the format of the body." (same text as the other routes; bad `page` or `size`), 401, 404 `site_not_found` (unknown site key; this is the body the API returns, shown as a code and not rewritten as prose).
PATCH /v1/article/{id} lists the new optional fields (slug, excerpt, seo_title, seo_description, cover_image_id, cover_image_alt, social_title, social_description, social_image_id, canonical_url, noindex, seo_dismissed). The 403 row of the HTTP status table adds: site SEO defaults are owner only; article SEO fields need only the right to edit the article. PATCH /v1/article/{id} lists the new optional fields (slug, excerpt, seo_title, seo_description, cover_image_id, cover_image_alt, social_title, social_description, social_image_id, canonical_url, noindex, seo_dismissed). The 403 row of the HTTP status table adds: site SEO defaults are owner only; article SEO fields need only the right to edit the article.
## Search (jump-to palette)
Board: group "Integration", states 8a to 8h, desktop 1440×900 and mobile 390×844, light and dark. Search never hides or filters the page. It only jumps, so find-in-page and deep links keep working.
### Behaviour
- Trigger, desktop: a field-style button in the page header, right of the title block, 320×36. Placeholder "Search the API reference…", "/" key hint. Mobile: 44×44 icon button right of "Jump to", inside the sticky bar. Opens with "/" (when focus is not in an input), Ctrl+K and Cmd+K. Both shortcuts are announced with aria-keyshortcuts.
- Palette: modal, 720 px wide, 96 px from the top, on the existing overlay. Mobile: full-screen sheet with a "Cancel" button (44 px) in the input row. Focus goes to the input; on close it returns to the trigger.
- Groups: "Endpoints" (max 6 rows, then "N more endpoints. Keep typing to narrow the list."), then "Sections". Empty query: one group "Suggested" with 5 rows.
- Match: every space-separated term must appear (case-insensitive substring) in method, path, description or access chip, or in a request field name, or in an error code or message. Rows matched only in a field or error show a second line ("Body field", "Query parameter" or "Error") with the match. Terms are highlighted with --rc-sand / --rc-on-sand. Rows matched in the path or description sort first.
- Selecting: Enter or click closes the palette, scrolls to the card (or section heading), expands the card, moves focus to the card button, and flashes the row (--rc-sand fill, 2 px --ui-primary ring, 1.5 s, then the open-card fill). With prefers-reduced-motion the flash is a static ring with no fade. The index active item updates through the existing scroll-spy. The URL hash becomes #ep-<id> so the result can be shared.
- Keys: Up and Down move (wrap), Enter opens, Esc closes, Home and End go to the first and last row. Typing resets the selection to the first row.
- Roles: input role="combobox" with aria-expanded, aria-controls, aria-autocomplete="list", aria-activedescendant; list role="listbox"; groups role="group" with aria-labelledby; rows role="option" with aria-selected and a full aria-label (method, path, description, access). A polite live region announces the count.
### Row anatomy
- Endpoint: method badge (existing colours), mono path 13/500, one-line description (ellipsis), access chip. Session-only: dashed muted badge, 400 weight path, dashed chip with lock icon, text --ui-text-muted.
- Section: icon in the badge column (hash, or lock for Session only), title 500, muted description.
- Selected: --ui-bg-elevated with a 2 px --ui-primary bar on the left (same as the section index active item). Hover: --ui-bg-elevated.
- Mobile rows: 56 px min height, badge and path on line 1, chip then description on line 2.
### Copy per state
| # | State | Copy |
|---|---|---|
| 8a | Trigger focused | Placeholder "Search the API reference…"; key hint "/"; aria-label "Search the API reference" |
| 8b | Open, empty | Input placeholder "Search the API reference…"; group "Suggested": Authentication ("Public access and API keys"), POST /v1/media/ ("Upload an image (multipart)." Verified user), Errors ("Status codes and messages"), GET /v1/article/ ("List articles, one page at a time." Public), PATCH /v1/user/me ("Update my profile." Verified user); footer "↑↓ Move", "↵ Open", "Esc Close", count "5 suggestions"; live "5 suggestions" |
| 8c | Typing "media" | Groups "Endpoints" (6 media routes) and "Sections" (Media, "10 routes"); count and live "17 results, showing 7" |
| 8d | "404", third row selected | Endpoints list the six first 404 routes with an "Error" line, for example "404 Article not found"; Sections: Errors ("Status codes and messages"); "N more endpoints. Keep typing to narrow the list."; count "22 results"; live "22 results, showing 7" |
| 8e | "keep_id" | POST /v1/media/merge, "Merge identical copies into one image.", Verified user, line "Body field keep_id"; "1 result" |
| 8f | "login" | POST /v1/auth/login, "Log in", chip "Session only" (lock); Section "Session only", "35 routes, not available to API keys"; "2 results" |
| 8g | No results | No match for "xyz". Try a path, a method or a status code like 404. Count "0 results"; live "No results" |
| 8h | After selecting | Page only: POST /v1/media/merge expanded and highlighted; index and Jump to read "Media" |
### Nuxt UI v4 mapping
- Trigger: UButton variant="outline" color="neutral" with a UIcon and UKbd (desktop); UButton icon-only (mobile). Shortcut: defineShortcuts({ '/': open, meta_k: open, ctrl_k: open }).
- Palette: UModal (fullscreen on mobile via the fullscreen prop) wrapping UCommandPalette with :groups, v-model:search-term, placeholder, :close (mobile "Cancel"). Fuse options off for the endpoint group (our own multi-field match), highlight via the #item-label and #item-description slots. UCommandPalette provides the combobox and listbox roles, aria-activedescendant and arrow-key handling.
- Rows: custom #item slot with UBadge (method, access chip), mono path, UIcon (lock, hash). Footer: #footer slot with UKbd for ↑ ↓ ↵ Esc. Empty: #empty slot. Live region: a visually hidden element with aria-live="polite".
- Flash: a CSS class on the EndpointCard row driven by a ref; uses var(--rc-sand) and var(--ui-primary) only.
### Assumptions to confirm
- Search is client-side over a static index built from the same data as the cards (method, path, first sentence of the description, access, request fields, error codes and messages). It does not search code samples, prose or response examples.
- Matching is substring per term, not fuzzy ("mdia" does not match "media").
- The palette shows the first sentence of each endpoint description, not the full text.
- Endpoints are capped at 6 rows with a count line; sections are never capped.
- Recent searches are left out. Open question: store the last 3 queries in localStorage?
- "/" is ignored while a text field has focus. Cmd+K on this route does not clash with any back-office shortcut (to confirm).
- The search trigger scrolls away with the header on desktop. Open question: keep it sticky next to the section index?
- Highlight uses --rc-sand on --rc-on-sand. On the selected row (--ui-bg-elevated) the two tones are close; the dark text keeps contrast. No new token is needed.
- The 1.5 s flash duration and the #ep-<id> hash are proposals.
## App sync notes
- Schema routes show the permission key as their access chip: schema.view (GET), schema.edit (POST, PUT), schema.delete (DELETE). Purge routes show "Needs permission" until the app names the key.
- 403 body for these routes: "Your role doesn't include this action. Ask an owner or admin." (app string, messages.ts).
- Entries intro: "Writing entries needs the entry permissions for that type." (proposal; the app has no string yet).
- Remaining "owners and admins" wording (activity export, content-types notice) stays as the app ships it.
- Article list body: {items, total, page, size, counts} (no X-Total-Count). counts keys: all, online, draft, suggestions.
- Users group has 7 routes: list, PATCH me, invite, cancel invite, renew invite, DELETE /v1/user/{id}?expected_role_id=N (permission, 409 target_role_not_found), GET /v1/auth/me. Profile routes use /v1/auth/me.
- 404 adds site_not_found (sitemap, unknown key). The 403 note sits under its row at full row width. Every 400 uses the generic body-mismatch text ("The request cannot be processed due to a mismatch in the format of the body."); "Invalid page or size." is gone.
## Custom content types round
Board: group "Integration", states 9a to 9j. Source: `IntegrationPage.dc.html`, `IntegrationSearch.dc.html`. Every route an API key can call is now documented.
### New groups
- Content types (`ctypes`): description "Define your own kind of content, like events or recipes. An owner or admin creates a type made of 1 to 50 ordered fields; the type then has its own entry routes." A "Field types" table (Type, Value in an entry, Rules) and a sample field object sit above the routes (anchor `ct-fields`).
- `GET /v1/content-type/` and `GET /v1/content-type/{key}`: Verified user. 404 `content_type_not_found`.
- `POST /v1/content-type/`: Owner or admin. Body `key` (2 to 40, lowercase letters, digits, hyphens), `name` (max 100), `icon` (optional), `fields` (1 to 50). 409 `content_type_key_taken`.
- `PUT /v1/content-type/{key}`: Owner or admin. Body `name`, `icon`, `fields`. 409 `schema_incompatible`.
- `DELETE /v1/content-type/{key}`: Owner or admin. 204. 409 `content_type_has_entries`, 409 `content_type_referenced`.
- Entries (`entries`): `GET` and `POST /v1/content-type/{key}/entry`, `GET`, `PUT` and `DELETE /v1/content-type/{key}/entry/{id}`. Verified user. List query `page`, `size` (5, 25, 50, 100), `sort` (`id`, `created_at`, `updated_at`, then `:asc` or `:desc`); the response is `{ items, total, page, size }`, not a bare array. Body `data` (object keyed by field key). `media` in a response is keyed by field key. 409 and 422 bodies are both `invalid_entry: <reason>`; 409 only when a unique field clashes. Id 400: "The server expects the ID to be in the format of an unsigned 32-bit integer (uint32)."
- Built-in types (`builtin`): `GET /v1/builtin-type/` and `/{key}`, Owner or admin. 404 `builtin_type_not_found`.
- Sites and authors (`sites`): `GET /v1/site/` and `GET /v1/author/` (paged, `{ items, total, page, size }`), Verified user.
- Media adds `GET` and `PATCH /v1/media/purge-settings` (`auto_purge_enabled`, `auto_purge_interval_days` 1 to 365; response also `last_purge_at`, `last_purge_merged`), `GET /v1/media/purge-preview` and `POST /v1/media/purge` (optional `fingerprint` from the preview). Owner or admin.
- PUT uses the PATCH badge colours.
### Access and errors
- 403 rows: "Only owners and admins can do this." (owner-or-admin routes) and "Only the owner can do this.", both listed in the 403 row; the existing note stays.
- 404 adds `content_type_not_found`, `entry_not_found`, `builtin_type_not_found`. 409 and 422 are real rows now (earlier text said there is no such row). Code-style text is the literal body.
- Authentication copy says a key can also manage content types and entries, and owner or admin routes answer 403 to a key whose creator is neither.
### Search
The index covers the new endpoints, body fields (`data`, and the events sample keys such as `capacity`) and error codes. "entry" also matches "entries". "N more endpoints" is singular for one.
### States 9a to 9j
9a create a content type, curl tab · 9b entries list, Response tab · 9c entry replace with the 409 and 422 errors · 9d Errors table · 9e Session only, 6 sub-groups · 9f search "entry" · 9g search "capacity" (Body field) · 9h search "schema_incompatible" (Error) · 9i search "content type" (Sections) · 9j navigation with scroll-spy on Content types. 8c now announces "17 results, showing 7" and 8d "22 results, showing 7" (the copy table above predates this; the board is right).
### Final round
- `POST /v1/media/purge` and the built-in type samples now match the API (no `icon`; keys `article`, `author`, `site`, `media`, `user`). Built-in types are read-only through the API.
- `GET /v1/media/` takes `page` (default 1) and `size` (5, 25, 50, 100; default 25), returns a JSON array and sends the total in `X-Total-Count`; 400 "Invalid page or size."
- Counts: Articles 7, Search and sharing 2, Content types 5, Entries 5, Built-in types 2, Media 10, Sites and authors 2, Users and invites 6, Settings 1, Session only 35. Search index: 75 endpoints (40 documented, 35 session-only).
- Announced: 8c "17 results, showing 7", 8d "22 results, showing 7", 8f "2 results", 9f "8 results, showing 7", 9g "2 results", 9h "1 result", 9i "12 results, showing 8".
- Illustrative only: built-in sample fields, purge-preview sample, the reason after `invalid_entry:`, session-only row labels, entry `created_by`/`updated_by`, `cover` media data.
- Not confirmed by the design tool: dark mode, the search palette on mobile and the Session only list on mobile. `task visual:check` is the gate.
- `POST /v1/content-type/` and `POST …/entry` answer 201; POST cards show only the JSON body.
@@ -0,0 +1,36 @@
# Localization: conflicts and article moves
Board: RenewCMS Screens Localization. Frame: LocaleFrame. Data: locale-fixtures.js (single fixture source), tables in locale-spec.js. UI copy says "article", never "story". No revision numbers, IDs or HTTP status names in user-facing text.
## L11 Conflicts and sessions
Route: editor
API: existing 401/403/404/409 patterns
The conflict dialog gives four choices. Keep my changes is the only filled button; the other three are secondary and equal. "Someone else saved this version at <time>". No revision numbers. On mobile the dialog is a bottom sheet with Keep my changes first, so it needs no scrolling at 390 px.
| ID | State | Trigger | Selector | Sizes | Fixture |
|---|---|---|---|---|---|
| loc.l11.session | Session expired | Draft kept in this browser; editor behind shows the unsaved changes | LocaleFrame{s:{v:"pm",x:"session"}} | 1440, 390 | Journal |
| loc.l11.restored | Restored after login | Editor shows "Restored unsaved changes from 14:18" | LocaleFrame{s:{v:"pm",x:"restored"}} | 1440, 390 | Journal |
| loc.conflict | Concurrent update | Four choices, local work kept; Save over theirs outlined in error colour with a warning icon | LocaleFrame{s:{v:"pm",x:"conflict"}} | 1440, 390 | Journal |
| loc.l11.conflictRestored | Concurrent update after session expiry | Restored changes notice above the choices | LocaleFrame{s:{v:"pm",x:"conflictRestored"}} | 1440, 390 | Journal |
| loc.l11.reloadConfirm | Reload theirs: confirm | "This discards your unsaved changes." | LocaleFrame{s:{v:"pm",x:"reloadConfirm"}} | 1440, 390 | Journal |
| loc.l11.conflict2 | Second conflict | Save over theirs failed again; nothing overwritten | LocaleFrame{s:{v:"pm",x:"conflict2"}} | 1440, 390 | Journal |
| loc.l11.download | Download started | Toast; changes still in the editor | LocaleFrame{s:{v:"pm",x:"download"}} | 1440, 390 | Journal |
## L11b Move article to another site
Route: editor → site select
API: proposed: POST /v1/story/{story_id}/move { site }
Entry point is the site select in the editor details. Articles move as a whole, only when the destination enables every language they contain (disabled ones included) and the user can edit all versions. The note lists readable versions only; versions the user can't read are not listed or counted. Moves are atomic and revalidate permissions and conflicts in the transaction.
| ID | State | Trigger | Selector | Sizes | Fixture |
|---|---|---|---|---|---|
| loc.l11b.moveSelect | Site select | Note lists all four versions, one tagged Read only | LocaleFrame{s:{v:"pm",x:"moveSelect"}} | 1440, 390 | Journal |
| loc.l11b.moveSelectHidden | Site select, hidden version | Arabic not readable: not listed or counted | LocaleFrame{s:{v:"pm",x:"moveSelectHidden"}} | 1440, 390 | Journal |
| loc.l11b.moveConfirm | Confirm | Move to Atelier? | LocaleFrame{s:{v:"pm",x:"moveConfirm"}} | 1440, 390 | Journal |
| loc.l11b.moveBusy | In progress | Dialog locked | LocaleFrame{s:{v:"pm",x:"moveBusy"}} | 1440, 390 | Journal |
| loc.l11b.moveDone | Moved | Toast | LocaleFrame{s:{v:"pm",x:"moveDone"}} | 1440, 390 | Journal |
| loc.l11b.move | Language missing in destination | Notes enables English only | LocaleFrame{s:{v:"pm",x:"move"}} | 1440, 390 | Journal, Notes |
| loc.l11b.moveSlug | Address conflict | Names the conflicting readable version and its address; unreadable ones are never named | LocaleFrame{s:{v:"pm",x:"moveSlug"}} | 1440, 390 | Journal, Atelier |
| loc.l11b.movePerm | No permission | Neutral | LocaleFrame{s:{v:"pm",x:"movePerm"}} | 1440, 390 | Journal |
| loc.l11b.moveFail | Move failed | Server error, nothing moved | LocaleFrame{s:{v:"pm",x:"moveFail"}} | 1440, 390 | Journal |
@@ -0,0 +1,80 @@
# Localization: editor header, permissions, publishing
Board: RenewCMS Screens Localization. Frame: LocaleFrame. Data: locale-fixtures.js (single fixture source), tables in locale-spec.js. UI copy says "article", never "story". No revision numbers, IDs or HTTP status names in user-facing text.
## L5 Editor: header, actions and title
Route: /article/{id}/edit (one id per version)
API: proposed: GET /v1/article/{id} → translations[], capabilities[]
Header priority and the action matrix are in the tables below. One filled primary button at most: Save and publish when allowed, dirty and offline; otherwise Save when dirty; otherwise Publish when clean and offline. Save stays separate and secondary. Desktop collapse order as width shrinks (1440 → 1024): reference button loses its label, Unpublish moves to the overflow menu, the freshness badge becomes icon-only. Mobile: title, language, publication and dirty badges stay at the top; Save, primary and an overflow button sit in a fixed bottom bar; reference, Unpublish, Edit slug, Move and Delete go to the overflow sheet. The language control is a menu button with a menu (not a listbox).
| ID | State | Trigger | Selector | Sizes | Fixture |
|---|---|---|---|---|---|
| loc.l5.default | Clean draft | Open a draft you can publish; title pristine | LocaleFrame{s:{v:"ed",x:"default"}} | 1440, 1024, 390 | Journal |
| loc.l5.dirty | Dirty draft | Can edit, can't publish: Save is primary | LocaleFrame{s:{v:"ed",x:"dirty"}} | 1440, 1024, 390 | Journal |
| loc.l5.dirtyPublish | Dirty draft, publish allowed | Save and publish French is primary; Save secondary | LocaleFrame{s:{v:"ed",x:"dirtyPublish"}} | 1440, 1024, 390 | Journal |
| loc.l5.cleanOnline | Clean online | Unpublish only; no primary | LocaleFrame{s:{v:"ed",x:"cleanOnline"}} | 1440, 1024, 390 | Journal |
| loc.l5.onlineDirty | Dirty online | Save updates the live page; Unpublish stays | LocaleFrame{s:{v:"ed",x:"onlineDirty"}} | 1440, 1024, 390 | Journal |
| loc.l5.saving | Saving | Save in flight | LocaleFrame{s:{v:"ed",x:"saving"}} | 1440, 390 | Journal |
| loc.l5.saved | Saved | Toast | LocaleFrame{s:{v:"ed",x:"saved"}} | 1440, 390 | Journal |
| loc.l5.saveFail | Save failed | Stays unsaved; Try saving again; nothing published | LocaleFrame{s:{v:"ed",x:"saveFail"}} | 1440, 1024, 390 | Journal |
| loc.l5.pubFail | Publish failed after save | Saved as a draft; Retry publish; edits shown as saved | LocaleFrame{s:{v:"ed",x:"pubFail"}} | 1440, 1024, 390 | Journal |
| loc.l5.ovf | Overflow menu | More actions (sheet on mobile) | LocaleFrame{s:{v:"ed",x:"ovf"}} | 1440, 390 | Journal |
| loc.l5.menu | Menu: four languages | Open menu | LocaleFrame{s:{v:"ed",x:"menu"}} | 1440, 390 | Journal |
| loc.l5.two | Menu: two languages | Two-language site | LocaleFrame{s:{v:"ed",x:"two"}} | 1440, 390 | Journal |
| loc.l5.many | Menu: many languages | Scrolls inside the viewport, with filter | LocaleFrame{s:{v:"ed",x:"many"}} | 1440, 390 | Journal |
| loc.l5.unsaved | Switch with unsaved changes | Choose English while dirty | LocaleFrame{s:{v:"ed",x:"unsaved"}} | 1440, 390 | Journal |
| loc.l5.loading | Loading version | Slow switch | LocaleFrame{s:{v:"ed",x:"loading"}} | 1440, 390 | Journal |
| loc.l5.navFail | Switch failed | Stays on current version | LocaleFrame{s:{v:"ed",x:"navFail"}} | 1440, 390 | Journal |
| loc.l5.gone | Version unavailable | Deleted or no access (neutral) | LocaleFrame{s:{v:"ed",x:"gone"}} | 1440, 390 | Journal |
| loc.l5.focus | Title: focus | Field focused, not changed | LocaleFrame{s:{v:"ed",x:"focus"}} | 1440, 390 | Journal |
| loc.l5.titleEdit | Title: editing | Typing; counter shown | LocaleFrame{s:{v:"ed",x:"titleEdit"}} | 1440, 390 | Journal |
| loc.l5.titleUnsaved | Title: unsaved | Changed, focus left | LocaleFrame{s:{v:"ed",x:"titleUnsaved"}} | 1440, 390 | Journal |
| loc.l5.invalid | Title: invalid | Empty: "Enter a title" | LocaleFrame{s:{v:"ed",x:"invalid"}} | 1440, 390 | Journal |
| loc.l5.titleShort | Title: too short | Under 3 characters | LocaleFrame{s:{v:"ed",x:"titleShort"}} | 1440, 390 | Journal |
| loc.l5.titleLong | Title: too long | Over 200 characters | LocaleFrame{s:{v:"ed",x:"titleLong"}} | 1440, 390 | Journal |
| loc.l5.titleSaving | Title: saving | Save in flight | LocaleFrame{s:{v:"ed",x:"titleSaving"}} | 1440, 390 | Journal |
| loc.l5.failed | Title: save failed | Text kept, still unsaved, Try again | LocaleFrame{s:{v:"ed",x:"failed"}} | 1440, 390 | Journal |
| loc.l5.menuDisabled | Language menu with a disabled language | Spanish is disabled: Disabled tag, version stays readable | LocaleFrame{s:{v:"ed",x:"menuDisabled"}} | 1440, 390 | Journal |
## L5b Permission states (per version)
Route: /article/{id}/edit
API: capabilities[] on GET /v1/article/{id}; every PATCH/DELETE rechecked on the server
Every action renders from its own capability (read, edit, publish, delete, create translation, review). See the capability matrix. Missing-translation rows appear only for users who can create; unreadable siblings are absent with no placeholder and no count. The formatting toolbar is hidden whenever edit is missing.
| ID | State | Trigger | Selector | Sizes | Fixture |
|---|---|---|---|---|---|
| loc.perm.readonly | P1 Read-only version | Banner, read-only fields, no Save, Publish, Delete, toolbar; reference stays | LocaleFrame{s:{v:"perm",x:"ro"}} | 1440, 1024, 390 | Journal |
| loc.l5b.roMenu | P1 menu | No Add translation row | LocaleFrame{s:{v:"perm",x:"roMenu"}} | 1440, 390 | Journal |
| loc.perm.editNoPublish | P2 Edit, no publish | Save only; hint about the publish permission | LocaleFrame{s:{v:"perm",x:"p2"}} | 1440, 1024, 390 | Journal |
| loc.perm.publishNoEdit | P3 Publish, no edit | Publish only; fields read-only | LocaleFrame{s:{v:"perm",x:"p3"}} | 1440, 1024, 390 | Journal |
| loc.perm.siblingReadOnly | P4 Sibling readable, not editable | Arabic row tagged Read only | LocaleFrame{s:{v:"perm",x:"p4"}} | 1440, 390 | Journal |
| loc.perm.siblingHidden | P5 Sibling not readable | German absent, no count, no placeholder | LocaleFrame{s:{v:"perm",x:"p5"}} | 1440, 390 | Journal |
| loc.perm.createNotAll | P6 Can create, not modify all | Delete article and Move disabled with the reason; Delete French version available | LocaleFrame{s:{v:"perm",x:"p6"}} | 1440, 390 | Journal |
| loc.l5b.noAdd | Menu without Add translation | No create permission; Arabic is missing but offers nothing | LocaleFrame{s:{v:"perm",x:"noAdd"}} | 1440, 390 | Journal |
| loc.l5b.withAdd | Menu with Add translation | Same article, user may create | LocaleFrame{s:{v:"perm",x:"withAdd"}} | 1440, 390 | Journal |
## L8 Publishing and deletion
Route: same as the editor
API: existing PATCH /v1/article/{id}/publish and /unpublish and DELETE per article id
Every action names its language. No bulk publish. With unsaved edits the primary reads Save and publish and saves first; if the save fails nothing is published and the edits stay unsaved; if the save works and publishing fails the edits show as saved. Unpublish never saves: the saved version goes offline and local edits stay in the editor. Saving an online version updates the live page immediately, and the editor says so. Deletion confirmations name only readable versions.
| ID | State | Trigger | Selector | Sizes | Fixture |
|---|---|---|---|---|---|
| loc.l8.publish | Publish French | Confirm, English untouched | LocaleFrame{s:{v:"pd",x:"publish"}} | 1440, 390 | Journal |
| loc.lang.publishDisabled | Publishing blocked: language disabled | French disabled on the site | LocaleFrame{s:{v:"pd",x:"publishDisabled"}} | 1440, 390 | Journal |
| loc.l8.saveAndPublish | Save and publish French | Unsaved edits: saves first, then publishes | LocaleFrame{s:{v:"pd",x:"saveAndPublish"}} | 1440, 390 | Journal |
| loc.l8.saveFailPublish | Save failed, nothing published | Error banner above the editor and an error toast; Save failed badge, primary Try saving again, edits kept, nothing published | LocaleFrame{s:{v:"pd",x:"saveFailPublish"}} | 1440, 390 | Journal |
| loc.l8.unpublish | Unpublish French | Confirm | LocaleFrame{s:{v:"pd",x:"unpublish"}} | 1440, 390 | Journal |
| loc.l8.unpublishDirty | Unpublish with unsaved edits | Saved version goes offline; edits kept; nothing saved | LocaleFrame{s:{v:"pd",x:"unpublishDirty"}} | 1440, 390 | Journal |
| loc.l8.delete | Delete French version | Confirm | LocaleFrame{s:{v:"pd",x:"delete"}} | 1440, 390 | Journal |
| loc.l8.deleteSource | Delete a source version | Names the readable versions that track the source; warns review tracking pauses | LocaleFrame{s:{v:"pd",x:"deleteSource"}} | 1440, 390 | Journal |
| loc.l8.deleteLast | Delete the only version | Deletes the article | LocaleFrame{s:{v:"pd",x:"deleteLast"}} | 1440, 390 | Journal |
| loc.l8.deleteStoryOk | Delete article (all readable versions) | Names readable versions only | LocaleFrame{s:{v:"pd",x:"deleteStoryOk"}} | 1440, 390 | Journal |
| loc.l8.deleteStory | Delete article blocked | Neutral, no version named | LocaleFrame{s:{v:"pd",x:"deleteStory"}} | 1440, 390 | Journal |
| loc.l8.done | Published | Toast "French published" and the online banner; badge Published, status Saved | LocaleFrame{s:{v:"pd",x:"done"}} | 1440, 390 | Journal |
| loc.l8.fail | Publish failed | Toast | LocaleFrame{s:{v:"pd",x:"fail"}} | 1440, 390 | Journal |
| loc.l8.deleteDone | French version deleted | Toast; editor opens English | LocaleFrame{s:{v:"pd",x:"deleteDone"}} | 1440, 390 | Journal |
| loc.l8.deleteStoryFail | Delete article failed | Dialog error; nothing deleted | LocaleFrame{s:{v:"pd",x:"deleteStoryFail"}} | 1440, 390 | Journal |
| loc.l8.deleteStoryDone | Article deleted | Toast on the Articles list | LocaleFrame{s:{v:"li",x:"deleteStoryDone"}} | 1440, 390 | Journal |
+43
View File
@@ -0,0 +1,43 @@
# Localization: article list and coverage
Board: RenewCMS Screens Localization. Frame: LocaleFrame. Data: locale-fixtures.js (single fixture source), tables in locale-spec.js. UI copy says "article", never "story". No revision numbers, IDs or HTTP status names in user-facing text.
## L7 Article list and coverage
Route: /articles?site&lang&tab=all|missing|review&q&status&author&seo&page&size
API: proposed: lang, tab=all|missing|review on GET /v1/article/ (same names as the URL)
Journal: 8 articles, 17 versions, page size 5. The list header shows the unit: "8 articles" (all languages, one row per article with its translations), "4 French versions" (language selected), "4 articles not in French" (missing tab), "7 articles need translation", "2 articles need review". Coverage chips: default language first, then other existing versions, then disabled-language versions, then dashed missing chips (only for languages the user can create). Chips collapse after 5 at 1440 and 4 at 1024 and 390, leaving a "+N" chip. Row actions are the same on every width: Open, Open another language, Add translation, Publish or Unpublish, Copy API URL, Delete version; every row has the row menu button. All state is in the URL.
| ID | State | Trigger | Selector | Sizes | Fixture |
|---|---|---|---|---|---|
| loc.l7.all | All languages, page 1 | 5 of 8 articles | LocaleFrame{s:{v:"li",x:"all"}} | 1440, 1024, 390 | Journal |
| loc.l7.page2 | All languages, page 2 (last) | 3 of 8 articles | LocaleFrame{s:{v:"li",x:"page2"}} | 1440, 1024, 390 | Journal |
| loc.l7.fr | French selected | 4 French versions | LocaleFrame{s:{v:"li",x:"fr"}} | 1440, 1024, 390 | Journal |
| loc.l7.frMissing | Not in French | 4 articles not in French | LocaleFrame{s:{v:"li",x:"frMissing"}} | 1440, 1024, 390 | Journal |
| loc.l7.emptyMissing | Nothing missing | Press: all articles translated; no summary, no pager | LocaleFrame{s:{v:"li",x:"emptyMissing"}} | 1440, 1024, 390 | Press |
| loc.l7.noResults | No results | Search "zinc"; every count 0 | LocaleFrame{s:{v:"li",x:"noResults"}} | 1440, 1024, 390 | Journal |
| loc.l7.frLoading | Loading | Counts shown as – | LocaleFrame{s:{v:"li",x:"frLoading"}} | 1440, 1024, 390 | Journal |
| loc.l7.listFail | Failed | Filters kept | LocaleFrame{s:{v:"li",x:"listFail"}} | 1440, 1024, 390 | Journal |
| loc.l7.limited | Limited access | Reads English only, can't create: no dashed chips | LocaleFrame{s:{v:"li",x:"limited"}} | 1440, 1024, 390 | Journal (limited scope) |
| loc.l7.review | Needs review tab | 2 articles need review | LocaleFrame{s:{v:"li",x:"review"}} | 1440, 1024, 390 | Journal |
| loc.l7.author | Author filter | Marta Alves: 3 articles, chips and Clear all | LocaleFrame{s:{v:"li",x:"author"}} | 1440, 1024, 390 | Journal |
| loc.l7.langFilter | Language filter | Enabled and Disabled groups | LocaleFrame{s:{v:"li",x:"langFilter"}} | 1440, 1024, 390 | Journal |
| loc.l7.rowMenu | Row menu | Same actions on desktop and mobile | LocaleFrame{s:{v:"li",x:"rowMenu"}} | 1440, 1024, 390 | Journal |
| loc.l7.filters | Mobile filter sheet | Journal, French, Draft: 2 results | LocaleFrame{s:{v:"li",x:"filters"}} | 1440, 1024, 390 | Journal |
| loc.l7.tabsScroll | Tabs scrolled | Not in French reachable; fade and chevrons | LocaleFrame{s:{v:"li",x:"tabsScroll"}} | 1440, 390 | Journal |
| loc.l7.long | Eight languages, long labels, filters | Atelier: chips collapse to +3, +4, +4; Draft and SEO filters | LocaleFrame{s:{v:"li",x:"long"}} | 1440, 1024, 390 | Atelier |
## L7s Article list, single-language site
Route: /articles?site=archive&q&status&page&size
API: GET /v1/article/?page=&size=&q=&status=&site= returns { items, total, page, size, counts }
Replaces the old Articles board frames as the pixel-gate reference for the list. A site with one language has no language filter, no coverage column, no Needs translation or Needs review tabs, and its menu labels name no language. The pager is AppPaginator: summary "Showing 1–5 of 5", rows-per-page select, first, previous, page numbers, next and last (390 px: summary and select, then Previous, "Page N of M", Next). Hidden controls when everything fits on one page; the summary stays.
| ID | State | Trigger | Selector | Sizes | Fixture |
|---|---|---|---|---|---|
| loc.l7s.default | Default | Archive: 5 articles on one page, no language filter, coverage column or tabs | LocaleFrame{s:{v:"li",x:"single"}} | 1440, 390 | Archive |
| loc.l7s.draft | Draft filter | Status: Draft | LocaleFrame{s:{v:"li",x:"singleDraft"}} | 1440, 390 | Archive |
| loc.l7s.noResults | No results | Search "zinc" | LocaleFrame{s:{v:"li",x:"singleNoResults"}} | 1440, 390 | Archive |
| loc.l7s.empty | Empty | Gallery: no articles | LocaleFrame{s:{v:"li",x:"singleEmpty"}} | 1440, 390 | Gallery |
| loc.l7s.loading | Loading | Counts shown as – | LocaleFrame{s:{v:"li",x:"singleLoading"}} | 1440, 390 | Archive |
| loc.l7s.fail | Failed | Filters kept | LocaleFrame{s:{v:"li",x:"singleFail"}} | 1440, 390 | Archive |
| loc.l7s.menu | Row menu | Open, Unpublish, Copy API URL, Delete article: no language named | LocaleFrame{s:{v:"li",x:"singleMenu"}} | 1440, 390 | Archive |
@@ -0,0 +1,16 @@
# Localization: metadata and public API
Board: RenewCMS Screens Localization. Frame: LocaleFrame. Data: locale-fixtures.js (single fixture source), tables in locale-spec.js. UI copy says "article", never "story". No revision numbers, IDs or HTTP status names in user-facing text.
## L10 Metadata and public API
Route: Search and sharing panel · /integration
API: existing slug, SEO fields; proposed alternates[], lang; exact lookup by site + lang + slug; resolution by story_id
Slug is unique per (site, lang). Exact lookup is by site + language + slug and never falls back. Language resolution and fallback use the stable story_id. Website URLs come from the site's Public URL pattern; without it the panel says "Public URL not configured" and links to the setting. Canonical is the localized page itself unless an override is set. SEO labels: "Fallback: French title", "No fallback", "Empty. English site default not used."
| ID | State | Trigger | Selector | Sizes | Fixture |
|---|---|---|---|---|---|
| loc.seo.noFallback | Search and sharing: French | Search and sharing slide-over on the editor: localized slug, canonical, alternates, fallback labels, Edit slug | LocaleFrame{s:{v:"seo",x:""}} | 1440, 390 | Journal |
| loc.slug.published | Edit slug | Edit slug dialog over the Search and sharing slide-over: published version warns about old links | LocaleFrame{s:{v:"seo",x:"editSlug"}} | 1440, 390 | Journal |
| loc.url.unset | Public URL not configured | Search and sharing slide-over: no pattern, no fabricated URL | LocaleFrame{s:{v:"seo",x:"unset"}} | 1440, 390 | Journal |
| loc.l10.noSocial | Social locale not set | Search and sharing slide-over: fr has no region and none is set, og:locale omitted | LocaleFrame{s:{v:"seo",x:"noSocial"}} | 1440, 390 | Journal |
| loc.l10.api | Integration: languages | Integration page: exact lookup, resolve by article group, errors | LocaleFrame{s:{v:"api",x:""}} | 1440, 390 | Journal |
@@ -0,0 +1,34 @@
# Localization: new article and add translation
Board: RenewCMS Screens Localization. Frame: LocaleFrame. Data: locale-fixtures.js (single fixture source), tables in locale-spec.js. UI copy says "article", never "story". No revision numbers, IDs or HTTP status names in user-facing text.
## L3 New article
Route: /articles (New article modal)
API: existing POST /v1/article/ + proposed lang, story_id
Single-language sites show no language field. Multilingual sites show Language and a New article / Translation of an existing article choice. The translation path uses the same endpoint and rules as Add translation. The picker lists only articles the user can read; the chosen version is the source.
| ID | State | Trigger | Selector | Sizes | Fixture |
|---|---|---|---|---|---|
| loc.l3.single | Single language | Title and site only | LocaleFrame{s:{v:"na",x:"single"}} | 1440, 390 | Archive |
| loc.l3.multi | Multilingual: new article | Language defaults to the site default | LocaleFrame{s:{v:"na",x:"multi"}} | 1440, 390 | Journal |
| loc.l3.translation | Translation of an article | Same fields as Add translation: article, language, source version, title, starting content | LocaleFrame{s:{v:"na",x:"translation"}} | 1440, 390 | Journal |
| loc.l3.sitechange | Site changed | Selected language not offered by the new site | LocaleFrame{s:{v:"na",x:"sitechange"}} | 1440, 390 | Journal, Notes |
## L4 Add a translation
Route: /article/{id}/edit?dialog=add-translation&lang=fr
API: proposed: POST /v1/article/{id}/translations
Always creates a draft. Source: the user picks which readable version to copy from (default: the default-language version if readable, else the first readable). The source version is captured in the same transaction as the copy. Copied text stays in the source language until edited; the version starts as Needs review. Start empty: no tracked source, so freshness shows No source. The primary action stays in the sticky footer on mobile; the body scrolls.
| ID | State | Trigger | Selector | Sizes | Fixture |
|---|---|---|---|---|---|
| loc.l4.form | Copy from source | Editor → language menu → Add translation | LocaleFrame{s:{v:"at",x:"form"}} | 1440, 390 | Journal |
| loc.l4.empty | Start empty | Title only; Source version reads No source, Freshness will show No source | LocaleFrame{s:{v:"at",x:"empty"}} | 1440, 390 | Journal |
| loc.l4.saving | Creating | Submit in flight | LocaleFrame{s:{v:"at",x:"saving"}} | 1440, 390 | Journal |
| loc.dup.readable | Exists, readable | Conflict; Open offered | LocaleFrame{s:{v:"at",x:"dup"}} | 1440, 390 | Journal |
| loc.dup.hidden | Exists, not readable | Neutral error, no Open | LocaleFrame{s:{v:"at",x:"dupHidden"}} | 1440, 390 | Journal |
| loc.l4.fail | Failed | Server error, entries kept | LocaleFrame{s:{v:"at",x:"fail"}} | 1440, 390 | Journal |
| loc.l4.gone | Source deleted | Deleted while the dialog was open: same neutral message as unreadable, no distinction shown | LocaleFrame{s:{v:"at",x:"gone"}} | 1440, 390 | Journal |
| loc.l4.unreadable | Source no longer readable | Access lost between opening and submitting: same neutral message as deleted | LocaleFrame{s:{v:"at",x:"unreadable"}} | 1440, 390 | Journal |
| loc.l4.langOff | Language disabled mid-flow | An owner disabled French while the dialog was open | LocaleFrame{s:{v:"at",x:"langOff"}} | 1440, 390 | Journal |
| loc.l4.long | Long dialog | Long title, many authors and images; body scrolls, footer stays | LocaleFrame{s:{v:"at",x:"long"}} | 1440, 390 | Journal |
@@ -0,0 +1,43 @@
# Localization: source reference and review (release 2)
Board: RenewCMS Screens Localization. Frame: LocaleFrame. Data: locale-fixtures.js (single fixture source), tables in locale-spec.js. UI copy says "article", never "story". No revision numbers, IDs or HTTP status names in user-facing text.
## L6 Source reference (release 2) (release 2)
Route: /article/{id}/edit?ref=:sourceId
API: proposed: GET /v1/article/{id} (read-only fetch of the reference)
Release 2. The temporary reference (?ref=, dashed outline, "Temporary reference") and the tracked review source (solid "Tracked source" badge in the review banner) are separate: changing the reference never changes the tracked source. Show source reference is in the editor header (desktop, icon-only at 1024) and the overflow sheet (mobile). Each pane scrolls independently. dir and lang go on the title and body of the editing pane and of the reference, never on the app shell.
| ID | State | Trigger | Selector | Sizes | Fixture |
|---|---|---|---|---|---|
| loc.l6.split | Side by side | Show source reference | LocaleFrame{s:{v:"src",x:"split"}} | 1440, 1024, 390 | Journal |
| loc.l6.closed | Reference hidden | Hide source reference; button returns | LocaleFrame{s:{v:"src",x:"closed"}} | 1440, 390 | Journal |
| loc.l6.reopen | Reopened | Scroll positions kept | LocaleFrame{s:{v:"src",x:"reopen"}} | 1440, 390 | Journal |
| loc.l6.changeRef | Change reference | Menu; tracked source stays English | LocaleFrame{s:{v:"src",x:"changeRef"}} | 1440, 390 | Journal |
| loc.l6.narrow | Narrow desktop (1024) | True 1024 frame | LocaleFrame{s:{v:"src",x:"narrow"}} | 1024, 390 | Journal |
| loc.l6.long | Long content | Both panes scroll independently | LocaleFrame{s:{v:"src",x:"long"}} | 1440, 390 | Journal |
| loc.l6.rtl | Arabic editing, English reference | dir=rtl on the Arabic title and body only | LocaleFrame{s:{v:"src",x:"rtl"}} | 1440, 390 | Journal |
| loc.l6.arRef | French editing, Arabic reference | dir=rtl on the reference pane only | LocaleFrame{s:{v:"src",x:"arRef"}} | 1440, 390 | Journal |
| loc.l6.mobileEdit | Mobile: editing | Segment | LocaleFrame{s:{v:"src",x:"mobileEdit"}} | 1440, 390 | Journal |
| loc.l6.mobileSrc | Mobile: source | Segment | LocaleFrame{s:{v:"src",x:"mobileSrc"}} | 1440, 390 | Journal |
| loc.l6.mobileClosed | Mobile: closed | Show source reference in the bottom bar or sheet | LocaleFrame{s:{v:"src",x:"mobileClosed"}} | 1440, 390 | Journal |
| loc.l6.unavail | Reference unavailable | Deleted or unreadable | LocaleFrame{s:{v:"src",x:"unavail"}} | 1440, 390 | Journal |
## L9 Freshness and review (release 2) (release 2)
Route: editor banner · list badge
API: proposed: POST /v1/article/{id}/review { source_article_id, source_revision, translation_revision } (internal fields; never shown)
Release 2. Publication (solid badge) and freshness (outlined badge with refresh icon) are separate. Labels: No version, Draft, Needs review, Reviewed. A copied draft starts as Needs review. The dialog shows "Changed fields: Title, Body", the source version with its date and the translation version with its date. No revision numbers appear in the UI.
| ID | State | Trigger | Selector | Sizes | Fixture |
|---|---|---|---|---|---|
| loc.l9.warn | Source updated | English changed after review | LocaleFrame{s:{v:"fr",x:"warn"}} | 1440, 390 | Journal |
| loc.l9.pub | Published, needs review | Still online | LocaleFrame{s:{v:"fr",x:"pub"}} | 1440, 390 | Journal |
| loc.l9.review | Mark reviewed | Confirm with changed fields and dates | LocaleFrame{s:{v:"fr",x:"review"}} | 1440, 390 | Journal |
| loc.review.changed | Source changed again | During the review | LocaleFrame{s:{v:"fr",x:"changed"}} | 1440, 390 | Journal |
| loc.l9.changedTr | Translation changed | Saved by someone else while confirming | LocaleFrame{s:{v:"fr",x:"changedTr"}} | 1440, 390 | Journal |
| loc.l9.replace | Choose tracked source | Cycle prevented | LocaleFrame{s:{v:"fr",x:"replace"}} | 1440, 390 | Journal |
| loc.src.inaccessible | Source unavailable (access) | History kept | LocaleFrame{s:{v:"fr",x:"inaccessible"}} | 1440, 390 | Journal |
| loc.src.deleted | Source deleted | Choose a new source | LocaleFrame{s:{v:"fr",x:"gone"}} | 1440, 390 | Journal |
| loc.l9.done | Reviewed | Toast | LocaleFrame{s:{v:"fr",x:"done"}} | 1440, 390 | Journal |
| loc.l9.fail | Review failed | Toast | LocaleFrame{s:{v:"fr",x:"fail"}} | 1440, 390 | Journal |
| loc.l9.frReview | Published and needs review in the list | French tab, Needs review: 2 versions | LocaleFrame{s:{v:"li",x:"frReview"}} | 1440, 1024, 390 | Journal |
@@ -0,0 +1,71 @@
# Localization: site languages, public URL and setup
Board: RenewCMS Screens Localization. Frame: LocaleFrame. Data: locale-fixtures.js (single fixture source), tables in locale-spec.js. UI copy says "article", never "story". No revision numbers, IDs or HTTP status names in user-facing text.
## L1 Site languages
Route: /settings/sites/:key/languages
API: proposed: GET/PUT /v1/site/{key}/languages
Navigation: Settings → Sites → [site] → Languages only. The site name is in the heading and breadcrumb. Site formatting locale, default content language, article language and social locale are four separate values. At least one language stays enabled and the default must be enabled: to retire the default, first Make default on another language, then Disable. Disable and Remove never delete or unpublish content. Disabled languages show a Disabled tag and a Re-enable action; their versions stay readable and editable per permission. Drafts can be published only after Re-enable ("French is disabled on this site. Re-enable it to publish."). The language filter lists them under Disabled. Social locale per language has three states: Derived (from the language code, e.g. pt-BR gives pt_BR), Set (an owner typed it, e.g. fr_FR) and Not set (og:locale left out). Only owners edit it.
| ID | State | Trigger | Selector | Sizes | Fixture |
|---|---|---|---|---|---|
| loc.l1.single | Single language | Owner opens Languages on Archive (one language, pt-BR kept) | LocaleFrame{s:{v:"sl",x:"single"}} | 1440, 390 | Archive |
| loc.l1.multi | Multilingual | Journal: four enabled, two disabled (Spanish, Italian) | LocaleFrame{s:{v:"sl",x:"multi"}} | 1440, 1024, 390 | Journal |
| loc.l1.loading | Loading | Request in flight | LocaleFrame{s:{v:"sl",x:"loading"}} | 1440, 390 | Journal |
| loc.l1.error | Load failed | Network or server error | LocaleFrame{s:{v:"sl",x:"error"}} | 1440, 390 | Journal |
| loc.l1.add | Add a language | Add language | LocaleFrame{s:{v:"sl",x:"add"}} | 1440, 390 | Journal |
| loc.l1.saveFail | Add failed | Server error, selection kept | LocaleFrame{s:{v:"sl",x:"saveFail"}} | 1440, 390 | Journal |
| loc.l1.adddup | Duplicate language | Already enabled | LocaleFrame{s:{v:"sl",x:"adddup"}} | 1440, 390 | Journal |
| loc.l1.broader | Only a broader tag supported | Add Portuguese (Portugal): substitution explained, confirmation required | LocaleFrame{s:{v:"sl",x:"broader"}} | 1440, 390 | Journal |
| loc.l1.default | Make default | Row menu | LocaleFrame{s:{v:"sl",x:"default"}} | 1440, 390 | Journal |
| loc.l1.defaultFail | Set default failed | Server error, nothing changed | LocaleFrame{s:{v:"sl",x:"defaultFail"}} | 1440, 390 | Journal |
| loc.l1.disable | Disable with content | Row menu → Disable German | LocaleFrame{s:{v:"sl",x:"disable"}} | 1440, 390 | Journal |
| loc.l1.stale | Languages changed | Another owner changed them: "Languages changed. Reload." | LocaleFrame{s:{v:"sl",x:"stale"}} | 1440, 390 | Journal |
| loc.lang.disableDefault | Disable default blocked | Disable English | LocaleFrame{s:{v:"sl",x:"disableDefault"}} | 1440, 390 | Journal |
| loc.lang.disableLast | Disable last blocked | Only one enabled | LocaleFrame{s:{v:"sl",x:"disableLast"}} | 1440, 390 | Journal |
| loc.l1.reenable | Re-enable | Spanish row → Re-enable | LocaleFrame{s:{v:"sl",x:"reenable"}} | 1440, 390 | Journal |
| loc.l1.reenableDone | Re-enabled | Toast after success | LocaleFrame{s:{v:"sl",x:"reenableDone"}} | 1440, 390 | Journal |
| loc.l1.reenableFail | Re-enable failed | Dialog error, still disabled | LocaleFrame{s:{v:"sl",x:"reenableFail"}} | 1440, 390 | Journal |
| loc.l1.remove | Remove (no content) | Italian (0 versions) | LocaleFrame{s:{v:"sl",x:"remove"}} | 1440, 390 | Journal |
| loc.l1.removeFail | Remove failed | Dialog error, still listed | LocaleFrame{s:{v:"sl",x:"removeFail"}} | 1440, 390 | Journal |
| loc.l1.removeBlocked | Remove blocked | Spanish has versions | LocaleFrame{s:{v:"sl",x:"removeBlocked"}} | 1440, 390 | Journal |
| loc.l1.readonly | Read-only view | Non-owner: list and social locale readable; no controls | LocaleFrame{s:{v:"sl",x:"readonly"}} | 1440, 390 | Journal |
| loc.l1.saved | Saved | After Add language | LocaleFrame{s:{v:"sl",x:"saved"}} | 1440, 390 | Journal |
| loc.l1.social | Social locale: three states | Atelier: Derived en_GB and pt_BR, Set fr_FR, Not set | LocaleFrame{s:{v:"sl",x:"social"}} | 1440, 1024, 390 | Atelier |
| loc.l1.socialEdit | Social locale: edit | Edit on French (Set: fr_FR) | LocaleFrame{s:{v:"sl",x:"socialEdit"}} | 1440, 390 | Atelier |
| loc.l1.socialInvalid | Social locale: invalid | fr-FR typed with a hyphen | LocaleFrame{s:{v:"sl",x:"socialInvalid"}} | 1440, 390 | Atelier |
## L1b Public URL pattern (owner setting)
Route: /settings/sites/:key/public-url
API: proposed: GET/PUT /v1/site/{key} { public_url_pattern }
Owner-only. One pattern per site, for example https://example.com/{lang}/{slug}. Supported placeholders: {lang} (language code) and {slug} (the article address in that language). {slug} is required: without it every article would share one address. The preview uses a real article of the site. When unset, article panels show "Public URL not configured" and link here. No URL is invented.
| ID | State | Trigger | Selector | Sizes | Fixture |
|---|---|---|---|---|---|
| loc.l1b.set | Set | Pattern saved, preview shown | LocaleFrame{s:{v:"pu",x:"set"}} | 1440, 390 | Journal |
| loc.l1b.editing | Editing | Live preview follows the field | LocaleFrame{s:{v:"pu",x:"editing"}} | 1440, 390 | Journal |
| loc.l1b.unknown | Unknown placeholder | {language} typed | LocaleFrame{s:{v:"pu",x:"unknown"}} | 1440, 390 | Journal |
| loc.l1b.scheme | Bad scheme | ftp:// typed | LocaleFrame{s:{v:"pu",x:"scheme"}} | 1440, 390 | Journal |
| loc.l1b.encoded | Not encoded | A space in the path | LocaleFrame{s:{v:"pu",x:"encoded"}} | 1440, 390 | Journal |
| loc.l1b.noSlug | Missing {slug} | Pattern without {slug} | LocaleFrame{s:{v:"pu",x:"noSlug"}} | 1440, 390 | Journal |
| loc.l1b.saved | Saved | Toast | LocaleFrame{s:{v:"pu",x:"saved"}} | 1440, 390 | Journal |
| loc.l1b.unset | Unset | No pattern; opened from "Public URL not configured" | LocaleFrame{s:{v:"pu",x:"unset"}} | 1440, 390 | Journal |
| loc.l1b.viewOnly | Read-only view | Non-owner: pattern readable, no controls | LocaleFrame{s:{v:"pu",x:"viewOnly"}} | 1440, 390 | Journal |
| loc.l1b.invalidHost | Invalid host | Pattern with an empty host label | LocaleFrame{s:{v:"pu",x:"invalidHost"}} | 1440, 390 | Journal |
## L2 First-time setup for existing articles
Route: /settings/sites/:key/languages/setup
API: proposed: GET /v1/language/setup, POST /v1/language/setup { sites:[{ key, lang }] } (lang is the full tag, e.g. pt-BR)
Opened from the Languages banner of any site; :key is the site it was opened from, and the page lists every site that still has unlabelled articles. Setup assigns a language per site and applies in one transaction. It never translates, links or moves articles. Each site is seeded from its full Site.Locale when a matching language entry exists: pt-BR becomes Portuguese (Brazil). A site with no locale has no seed and the owner must choose. Nothing applies until the owner confirms every row, including a site with no articles. Retrying is safe.
| ID | State | Trigger | Selector | Sizes | Fixture |
|---|---|---|---|---|---|
| loc.l2.ready | Ready to assign | Journal (en), Notes (no locale, must choose), Archive (pt-BR kept) | LocaleFrame{s:{v:"su",x:"ready"}} | 1440, 390 | Journal, Notes, Archive |
| loc.l2.noLocale | No-locale site | Notes only: the owner must choose | LocaleFrame{s:{v:"su",x:"noLocale"}} | 1440, 390 | Notes |
| loc.l2.empty | Site with no articles | Gallery has no articles; en-GB kept, confirm and Save | LocaleFrame{s:{v:"su",x:"empty"}} | 1440, 390 | Gallery |
| loc.l2.applying | Applying | Request in flight | LocaleFrame{s:{v:"su",x:"applying"}} | 1440, 390 | Journal, Notes, Archive |
| loc.l2.inProgress | Setup already running | Another owner started it; starting again is safe | LocaleFrame{s:{v:"su",x:"inProgress"}} | 1440, 390 | Journal, Notes, Archive |
| loc.l2.done | Done | 16 articles labelled | LocaleFrame{s:{v:"su",x:"done"}} | 1440, 390 | Journal, Notes, Archive |
| loc.l2.fail | Failed | Nothing changed; choices kept; retry is safe | LocaleFrame{s:{v:"su",x:"fail"}} | 1440, 390 | Journal, Notes, Archive |
@@ -0,0 +1,20 @@
# Localization: existing surfaces
Board: RenewCMS Screens Localization. Frame: LocaleFrame. Data: locale-fixtures.js (single fixture source), tables in locale-spec.js. UI copy says "article", never "story". No revision numbers, IDs or HTTP status names in user-facing text.
## L12 Existing surfaces
Route: Home · Activity · Media · editor details
API: existing; language added where it applies
Single-language sites show none of this. Home counts articles, not versions.
| ID | State | Trigger | Selector | Sizes | Fixture |
|---|---|---|---|---|---|
| loc.l12.home | Home: recent articles | Default-language title; code only when not default | LocaleFrame{s:{v:"sf",x:"home"}} | 1440, 1024, 390 | Journal |
| loc.l12.homeFr | Home: reader of French only | Titles in French with code FR | LocaleFrame{s:{v:"sf",x:"homeFr"}} | 1440, 1024, 390 | Journal |
| loc.l12.activity | Activity | Events name the language | LocaleFrame{s:{v:"sf",x:"activity"}} | 1440, 1024, 390 | Journal |
| loc.l12.media | Media usage | Media page with the image detail panel: shared image counted once, versions listed, "Used in 2" | LocaleFrame{s:{v:"sf",x:"media"}} | 1440, 1024, 390 | Journal |
| loc.l12.mediaElsewhere | Media usage: used elsewhere only | Image used only as an author avatar: badge "Used in 1", "Articles" with "No article shows it.", "Used elsewhere" with Author avatar linking to /authors | LocaleFrame{s:{v:"sf",x:"mediaElsewhere"}} | 1440, 390 | Journal |
| loc.l12.menu | Article menu labels | Articles list, French selected: row menu names the language (Publish French, Delete French version). Bottom sheet at 390 | LocaleFrame{s:{v:"li",x:"menuLang"}} | 1440, 390 | Journal |
| loc.l12.apiCopy | API URL copy | Articles list: toast after Copy API URL with the ?lang= address. Bottom toast at 390 | LocaleFrame{s:{v:"li",x:"apiCopy"}} | 1440, 390 | Journal |
| loc.l12.seoPreview | SEO preview | Search and sharing slide-over: localized address and canonical | LocaleFrame{s:{v:"seo",x:"preview"}} | 1440, 390 | Journal |
| loc.l12.siteFallback | Site text fallback | Search and sharing slide-over: site text used only in its own language | LocaleFrame{s:{v:"seo",x:"siteFallback"}} | 1440, 390 | Journal |
+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.md`, section 3.7. Board groups: 10 Media picker for a field.
+10 -1
View File
@@ -10,7 +10,7 @@ Visual reference: `RenewCMS Screens Back-office.dc.html`, groups "Media", "Media
Every state below is drawn in light and dark (theme switch on the board), at 1440×900 and 390×844 (both frames sit side by side). Board: `RenewCMS Screens Back-office.dc.html`. Copy is exact; where a cell is empty the state reuses the fixed copy. Every state below is drawn in light and dark (theme switch on the board), at 1440×900 and 390×844 (both frames sit side by side). Board: `RenewCMS Screens Back-office.dc.html`. Copy is exact; where a cell is empty the state reuses the fixed copy.
### Media (group "Media", 52 states) ### Media (group "Media", 56 states)
Route: `/media`. API: GET /v1/media/ · POST /v1/media/ · PATCH /v1/media/{id} · DELETE /v1/media/{id} · POST /v1/media/merge · GET /v1/media/{id}/usage. Route: `/media`. API: GET /v1/media/ · POST /v1/media/ · PATCH /v1/media/{id} · DELETE /v1/media/{id} · POST /v1/media/merge · GET /v1/media/{id}/usage.
@@ -113,3 +113,12 @@ 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.md`, section 3.8. Board groups: 11 Media library usage.
## App sync (batch A)
- Detail panel, "Used elsewhere" below the articles and entries lists: rows "Author avatar" (/authors) and "Site default social image" (/settings/sites). States: avatar only, site only, both, none (section absent). The "Used in N" badge includes these, N = articles + entries + elsewhere. "Not used in any article" appears only when N is 0; otherwise the line reads "No article shows it."
- Selected card (grid, mobile list): outline badges ("Used in N", "Draft") keep opaque bg-default over the sand tint, text colour unchanged. --ui-text-toned on --ui-bg: 9.7:1 light (#444 on #fff), 11.7:1 dark (#cfccc7 on #111).
- Media library board (variants): adds tabs (All, Unused, Duplicates), Select all, grid/list toggle, Duplicate badges, the variants filter row and the Details | Variants tab row. Variant URL: /static/uploadedImages/photo.png?v=thumb.
- Not yet done: mobile picker sheet height and tile count, desktop frame of the mobile-only state, stray miniatures.
+3
View File
@@ -23,3 +23,6 @@ Recommendation: a modal. Title is the only field. The body is not asked for here
| 3 | Submitting | Request in flight. Fields are disabled and the dialog can't be dismissed. | "Creating…" / "Choosing tiles for a small bathroom" | | 3 | Submitting | Request in flight. Fields are disabled and the dialog can't be dismissed. | "Creating…" / "Choosing tiles for a small bathroom" |
| 4 | Title rejected (400) | A server 400 that got past the browser checks. The raw error isn't shown. | "Something in the form isn't valid. Check the highlighted fields." / "Choosing tiles for a small bathroom" / "Check this title and try again." | | 4 | Title rejected (400) | A server 400 that got past the browser checks. The raw error isn't shown. | "Something in the form isn't valid. Check the highlighted fields." / "Choosing tiles for a small bathroom" / "Check this title and try again." |
| 5 | Error | 500 or network failure. | "Couldn't create the article. Your text is still here. Try again in a moment." / "Choosing tiles for a small bathroom" | | 5 | Error | 500 or network failure. | "Couldn't create the article. Your text is still here. Try again in a moment." / "Choosing tiles for a small bathroom" |
## Localization
Localization: multilingual sites show Language and New story / Translation of; same rules as POST /v1/article/{id}/translations.
+4
View File
@@ -64,3 +64,7 @@ The "Author profile" card sits between Account and Password in every Profile fra
| 3 | Created | 201: the card shows the author. The author is named from the display name and linked to the user. | Author profile created · Marta Alves is now your byline. · Edit author · Linked to your account. New articles start with this author. | | 3 | Created | 201: the card shows the author. The author is named from the display name and linked to the user. | Author profile created · Marta Alves is now your byline. · Edit author · Linked to your account. New articles start with this author. |
| 4 | Created, slug adjusted | The slug was taken, so the server added a number. No error is shown. | Your slug is marta-alves-2 · marta-alves was already used by another author. You can change it in Edit author. | | 4 | Created, slug adjusted | The slug was taken, so the server added a number. No error is shown. | Your slug is marta-alves-2 · marta-alves was already used by another author. You can change it in Edit author. |
| 5 | Edit own author | Edit author on the card, by a role without author rights. The form opens with the linked user locked and no Unlink. There is no delete action in the form or on this screen. | Edit Marta Alves · Linked user · marta@renew.example · This is your author profile. Only an owner or admin can change the link. · Save changes | | 5 | Edit own author | Edit author on the card, by a role without author rights. The form opens with the linked user locked and no Unlink. There is no delete action in the form or on this screen. | Edit Marta Alves · Linked user · marta@renew.example · This is your author profile. Only an owner or admin can change the link. · Save changes |
| 6 | No author profile, no display name | The user has no linked author and has not set a display name. | Uses your username, marta. You can change it afterwards. |
| 7 | Edit own author: owner or admin | Edit author on the card, by an owner or admin. The form opens with the linked user and Unlink is allowed. | Edit Marta Alves · Linked user · marta@renew.example · Unlink · Save changes |
Order on the page: Display name, Account, Your role (role card), Author profile, Password.
Loaded 100 of 1429 files, more files were not shown because too many files have changed in this diff. Show more