Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e01c29657 | ||
|
|
acd392c29d | ||
|
|
514a082c96 | ||
|
|
844842fdae | ||
|
|
7e9bd9ba30 | ||
|
|
68401d66e0 | ||
|
|
daf497576f | ||
|
|
0490a4c494 | ||
|
|
2c8f39273c | ||
|
|
721311a643 | ||
|
|
7f1e8e572d | ||
|
|
02a0a36dc3 | ||
|
|
5a430c08f4 | ||
|
|
54e8fd5fed | ||
|
|
70460e4170 | ||
|
|
834493a4f5 | ||
|
|
a49eec909c |
No files matched your search
@@ -14,3 +14,4 @@ CORS_ALLOWED_ORIGINS=
|
||||
AUTH_RATE_LIMIT_MAX_ATTEMPTS=5
|
||||
AUTH_RATE_LIMIT_WINDOW_SECONDS=60
|
||||
TRUSTED_PROXIES=
|
||||
UPDATE_FEED_URL=https://git.floriansylvain.fr
|
||||
+6
-1
@@ -4,7 +4,7 @@
|
||||
|
||||
# DB
|
||||
*.db
|
||||
data/
|
||||
/data/
|
||||
|
||||
# Build
|
||||
bin
|
||||
@@ -20,5 +20,10 @@ build-errors.log
|
||||
uploadedImages/
|
||||
*.exe
|
||||
|
||||
# AI fest
|
||||
.claude/
|
||||
CLAUDE.md
|
||||
.codex/
|
||||
.agents/
|
||||
AGENTS.md
|
||||
codex-workflow.md
|
||||
@@ -15,6 +15,10 @@ cp .env.example .env # fill in PUBLIC_URL, JWT_SECRET and SMTP_*
|
||||
|
||||
Data is stored in `./data/` by default. For a real server (systemd, HTTPS, backups), see **[docs/deployment.md](docs/deployment.md)**.
|
||||
|
||||
### 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.
|
||||
|
||||
### Develop
|
||||
|
||||
Requires Go 1.27+, Node.js 22, [Bun](https://bun.sh) and [Task](https://taskfile.dev).
|
||||
|
||||
+25
-2
@@ -122,14 +122,37 @@ tasks:
|
||||
- go build -trimpath -ldflags "{{.LDFLAGS}}" -o bin/{{.BINARY}}{{exeExt}} ./cmd/server
|
||||
|
||||
release:
|
||||
desc: Cross-compile production binaries for all release targets → bin/
|
||||
deps: [build:web]
|
||||
desc: Cross-compile and sign production binaries for all release targets → bin/ (needs RELEASE_SIGNING_KEY)
|
||||
cmds:
|
||||
- task: release:check
|
||||
- task: build:web
|
||||
- for: { var: RELEASE_TARGETS }
|
||||
task: build:target
|
||||
vars:
|
||||
GOOS: '{{index (splitList "/" .ITEM) 0}}'
|
||||
GOARCH: '{{index (splitList "/" .ITEM) 1}}'
|
||||
- go run ./cmd/releasesign checksums bin --match "{{.BINARY}}_{{.VERSION}}_*"
|
||||
- go run ./cmd/releasesign sign bin/checksums.txt
|
||||
- go run ./cmd/releasesign verify bin/checksums.txt
|
||||
|
||||
release:check:
|
||||
internal: true
|
||||
cmds:
|
||||
- cmd: 'test -n "$RELEASE_SIGNING_KEY" || { echo "RELEASE_SIGNING_KEY is not set. Point it at the private release key file (see task release:keygen)." >&2; exit 1; }'
|
||||
silent: true
|
||||
- cmd: 'test -f "$RELEASE_SIGNING_KEY" || { echo "RELEASE_SIGNING_KEY points to a missing file: $RELEASE_SIGNING_KEY" >&2; exit 1; }'
|
||||
silent: true
|
||||
- mkdir -p tmp
|
||||
- echo probe > tmp/release-probe.txt
|
||||
- defer: rm -f tmp/release-probe.txt tmp/release-probe.txt.sig
|
||||
- go run ./cmd/releasesign sign tmp/release-probe.txt
|
||||
|
||||
release:keygen:
|
||||
desc: One-time release key pair. Usage, task release:keygen -- <private key path outside the repository>
|
||||
cmds:
|
||||
- cmd: 'test -n "{{.CLI_ARGS}}" || { echo "usage: task release:keygen -- <private key path outside the repository>" >&2; exit 1; }'
|
||||
silent: true
|
||||
- go run ./cmd/releasesign keygen {{.CLI_ARGS}}
|
||||
|
||||
build:target:
|
||||
internal: true
|
||||
|
||||
+138
-7
@@ -1,20 +1,30 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
domainAPIKey "RenewCMS/internal/domain/apikey"
|
||||
domainArticle "RenewCMS/internal/domain/article"
|
||||
domainImage "RenewCMS/internal/domain/image"
|
||||
domainInvite "RenewCMS/internal/domain/invite"
|
||||
domainMail "RenewCMS/internal/domain/mail"
|
||||
domainUpdate "RenewCMS/internal/domain/update"
|
||||
domainUser "RenewCMS/internal/domain/user"
|
||||
"RenewCMS/internal/infrastructure/config"
|
||||
"RenewCMS/internal/infrastructure/hashing"
|
||||
"RenewCMS/internal/infrastructure/mailer"
|
||||
"RenewCMS/internal/infrastructure/markdown"
|
||||
"RenewCMS/internal/infrastructure/persistence/models"
|
||||
persistence "RenewCMS/internal/infrastructure/persistence/repositories"
|
||||
"RenewCMS/internal/infrastructure/update"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"crypto/ed25519"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/glebarez/sqlite"
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
@@ -22,6 +32,8 @@ import (
|
||||
)
|
||||
|
||||
type UseCases struct {
|
||||
apiKeyAuthOnce sync.Once
|
||||
apiKeyAuthMiddleware func(http.Handler) http.Handler
|
||||
Token *jwtauth.JWTAuth
|
||||
CreateArticleUseCase *useCases.CreateArticleUseCase
|
||||
GetArticleUseCase *useCases.GetArticleUseCase
|
||||
@@ -51,6 +63,15 @@ type UseCases struct {
|
||||
MergeMediaUseCase *useCases.MergeMediaUseCase
|
||||
GetMediaUsageUseCase *useCases.GetMediaUsageUseCase
|
||||
GetSettingsUseCase *useCases.GetSettingsUseCase
|
||||
GetUpdateStatusUseCase *useCases.GetUpdateStatusUseCase
|
||||
CheckForUpdateUseCase *useCases.CheckForUpdateUseCase
|
||||
StartUpdateDownloadUseCase *useCases.StartUpdateDownloadUseCase
|
||||
RequestRestartUseCase *useCases.RequestRestartUseCase
|
||||
RecordRunningInfoUseCase *useCases.RecordRunningInfoUseCase
|
||||
CreateAPIKeyUseCase *useCases.CreateAPIKeyUseCase
|
||||
ListAPIKeysUseCase *useCases.ListAPIKeysUseCase
|
||||
RevokeAPIKeyUseCase *useCases.RevokeAPIKeyUseCase
|
||||
AuthenticateAPIKeyUseCase *useCases.AuthenticateAPIKeyUseCase
|
||||
}
|
||||
|
||||
type Repositories struct {
|
||||
@@ -58,10 +79,29 @@ type Repositories struct {
|
||||
UserRepo domainUser.Repository
|
||||
ImageRepo domainImage.Repository
|
||||
InviteRepo domainInvite.Repository
|
||||
APIKeyRepo domainAPIKey.Repository
|
||||
MailRepo domainMail.Repository
|
||||
ReleaseFeed domainUpdate.ReleaseFeed
|
||||
UpdateStore domainUpdate.StatusStore
|
||||
UpdateJobs domainUpdate.JobStore
|
||||
UpdateHelper domainUpdate.HelperDetector
|
||||
AssetFetcher domainUpdate.AssetFetcher
|
||||
SignatureVerifier domainUpdate.SignatureVerifier
|
||||
StagedRunner domainUpdate.StagedBinaryRunner
|
||||
DatabaseBackup domainUpdate.DatabaseBackup
|
||||
UpdateResults domainUpdate.ResultStore
|
||||
RestartRequests domainUpdate.RestartRequestStore
|
||||
RunningInfo domainUpdate.RunningInfoStore
|
||||
}
|
||||
|
||||
const sqliteBusyTimeoutMs = 5000
|
||||
const (
|
||||
sqliteBusyTimeoutMs = 5000
|
||||
updateStatusFileName = "update-status.json"
|
||||
updateJobFileName = "update-job.json"
|
||||
updateHelperFileName = "update-helper.json"
|
||||
updatesDirName = "updates"
|
||||
backupsDirName = "backups"
|
||||
)
|
||||
|
||||
func SQLiteDSN(dbName string) string {
|
||||
return fmt.Sprintf("%s?_pragma=busy_timeout(%d)", dbName, sqliteBusyTimeoutMs)
|
||||
@@ -76,7 +116,7 @@ func getDb(dbName string, uploadDir string) *gorm.DB {
|
||||
panic("Unable to open the database: " + err.Error())
|
||||
}
|
||||
|
||||
if err := db.AutoMigrate(&models.Article{}, &models.Image{}, &models.User{}, &models.Invite{}); err != nil {
|
||||
if err := db.AutoMigrate(&models.Article{}, &models.Image{}, &models.User{}, &models.Invite{}, &models.APIKey{}); err != nil {
|
||||
panic("Failed to migrate database: " + err.Error())
|
||||
}
|
||||
|
||||
@@ -91,25 +131,48 @@ func getDb(dbName string, uploadDir string) *gorm.DB {
|
||||
return db
|
||||
}
|
||||
|
||||
func releasePublicKey() ed25519.PublicKey {
|
||||
key, err := update.EmbeddedPublicKey()
|
||||
if err != nil {
|
||||
panic("Unable to read the embedded release key: " + err.Error())
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
func getRepositories(db *gorm.DB, settings config.Settings) *Repositories {
|
||||
dataDir := filepath.Dir(settings.DBFile)
|
||||
return &Repositories{
|
||||
ArticleRepo: persistence.NewArticleRepository(db),
|
||||
UserRepo: persistence.NewUserRepository(db),
|
||||
ImageRepo: persistence.NewImageRepository(db, settings.UploadDir),
|
||||
InviteRepo: persistence.NewInviteRepository(db),
|
||||
APIKeyRepo: persistence.NewAPIKeyRepository(db),
|
||||
MailRepo: mailer.NewMailRepository(settings.Smtp),
|
||||
ReleaseFeed: update.NewGiteaReleaseFeed(settings.UpdateFeedURL),
|
||||
UpdateStore: update.NewJSONStatusStore(filepath.Join(dataDir, updateStatusFileName)),
|
||||
UpdateJobs: update.NewJSONJobStore(filepath.Join(dataDir, updateJobFileName)),
|
||||
UpdateHelper: update.NewFileHelperDetector(filepath.Join(dataDir, updateHelperFileName)),
|
||||
AssetFetcher: update.NewHTTPAssetFetcher(settings.UpdateFeedURL),
|
||||
SignatureVerifier: update.NewEd25519SignatureVerifier(releasePublicKey()),
|
||||
StagedRunner: update.NewExecStagedBinaryRunner(),
|
||||
DatabaseBackup: update.NewSQLiteDatabaseBackup(db, filepath.Join(dataDir, backupsDirName), time.Now),
|
||||
UpdateResults: update.NewJSONResultStore(filepath.Join(dataDir, domainUpdate.ResultFileName)),
|
||||
RestartRequests: update.NewJSONRestartRequestStore(filepath.Join(dataDir, domainUpdate.RestartRequestFileName)),
|
||||
RunningInfo: update.NewJSONRunningInfoStore(filepath.Join(dataDir, domainUpdate.RunningInfoFileName)),
|
||||
}
|
||||
}
|
||||
|
||||
func getUseCases(repos *Repositories, settings config.Settings) *UseCases {
|
||||
hasher := hashing.NewBcryptHasher()
|
||||
renderer := markdown.NewConverter()
|
||||
keyGenerator := hashing.NewSHA256KeyGenerator()
|
||||
|
||||
return &UseCases{
|
||||
Token: jwtauth.New("HS256", []byte(settings.JWTSecret), nil),
|
||||
CreateArticleUseCase: useCases.NewCreateArticleUseCase(repos.ArticleRepo),
|
||||
GetArticleUseCase: useCases.NewGetArticleUseCase(repos.ArticleRepo),
|
||||
ListArticlesUseCase: useCases.NewListArticlesUseCase(repos.ArticleRepo),
|
||||
UpdateArticleUseCase: useCases.NewUpdateArticleUseCase(repos.ArticleRepo),
|
||||
CreateArticleUseCase: useCases.NewCreateArticleUseCase(repos.ArticleRepo, renderer),
|
||||
GetArticleUseCase: useCases.NewGetArticleUseCase(repos.ArticleRepo, renderer),
|
||||
ListArticlesUseCase: useCases.NewListArticlesUseCase(repos.ArticleRepo, renderer),
|
||||
UpdateArticleUseCase: useCases.NewUpdateArticleUseCase(repos.ArticleRepo, renderer),
|
||||
DeleteArticleUseCase: useCases.NewDeleteArticleUseCase(repos.ArticleRepo),
|
||||
GetUserUseCase: useCases.NewGetUserUseCase(repos.UserRepo),
|
||||
CreateUserUseCase: useCases.NewCreateUserUseCase(repos.UserRepo, hasher, repos.MailRepo, settings.PublicURL),
|
||||
@@ -117,7 +180,7 @@ func getUseCases(repos *Repositories, settings config.Settings) *UseCases {
|
||||
VerifyUserUseCase: useCases.NewVerifyUserUseCase(repos.UserRepo, hasher),
|
||||
CancelRegistrationUseCase: useCases.NewCancelRegistrationUseCase(repos.UserRepo),
|
||||
RequestPasswordResetUseCase: useCases.NewRequestPasswordResetUseCase(repos.UserRepo, hasher, repos.MailRepo, settings.PublicURL),
|
||||
ResetPasswordUseCase: useCases.NewResetPasswordUseCase(repos.UserRepo, hasher),
|
||||
ResetPasswordUseCase: useCases.NewResetPasswordUseCase(repos.UserRepo, hasher, repos.APIKeyRepo, time.Now),
|
||||
UpdateUserProfileUseCase: useCases.NewUpdateUserProfileUseCase(repos.UserRepo),
|
||||
ListUsersUseCase: useCases.NewListUsersUseCase(repos.UserRepo),
|
||||
CreateInviteUseCase: useCases.NewCreateInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher, repos.MailRepo, settings.PublicURL),
|
||||
@@ -134,9 +197,38 @@ func getUseCases(repos *Repositories, settings config.Settings) *UseCases {
|
||||
MergeMediaUseCase: useCases.NewMergeMediaUseCase(repos.ImageRepo, repos.ArticleRepo),
|
||||
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(repos.ImageRepo, repos.ArticleRepo),
|
||||
GetSettingsUseCase: useCases.NewGetSettingsUseCase(settings.Version),
|
||||
GetUpdateStatusUseCase: useCases.NewGetUpdateStatusUseCase(repos.UpdateStore, repos.UpdateJobs, repos.UpdateHelper, repos.UpdateResults, repos.RestartRequests, settings.Version, time.Now),
|
||||
CheckForUpdateUseCase: useCases.NewCheckForUpdateUseCase(repos.ReleaseFeed, repos.UpdateStore, settings.Version, time.Now),
|
||||
StartUpdateDownloadUseCase: startUpdateDownloadUseCase(repos, settings),
|
||||
RequestRestartUseCase: useCases.NewRequestRestartUseCase(repos.UpdateStore, repos.UpdateJobs, repos.UpdateHelper, repos.UpdateResults, repos.RestartRequests, settings.Version, time.Now),
|
||||
RecordRunningInfoUseCase: useCases.NewRecordRunningInfoUseCase(repos.RunningInfo, settings.Version, os.Getpid(), time.Now),
|
||||
CreateAPIKeyUseCase: useCases.NewCreateAPIKeyUseCase(repos.APIKeyRepo, keyGenerator, time.Now),
|
||||
ListAPIKeysUseCase: useCases.NewListAPIKeysUseCase(repos.APIKeyRepo, repos.UserRepo, time.Now),
|
||||
RevokeAPIKeyUseCase: useCases.NewRevokeAPIKeyUseCase(repos.APIKeyRepo, repos.UserRepo, time.Now),
|
||||
AuthenticateAPIKeyUseCase: useCases.NewAuthenticateAPIKeyUseCase(repos.APIKeyRepo, keyGenerator, repos.UserRepo, time.Now),
|
||||
}
|
||||
}
|
||||
|
||||
func startUpdateDownloadUseCase(repos *Repositories, settings config.Settings) *useCases.StartUpdateDownloadUseCase {
|
||||
return useCases.NewStartUpdateDownloadUseCase(useCases.StartUpdateDownloadDependencies{
|
||||
Store: repos.UpdateStore,
|
||||
Jobs: repos.UpdateJobs,
|
||||
Helper: repos.UpdateHelper,
|
||||
Results: repos.UpdateResults,
|
||||
Requests: repos.RestartRequests,
|
||||
Fetcher: repos.AssetFetcher,
|
||||
Verifier: repos.SignatureVerifier,
|
||||
Runner: repos.StagedRunner,
|
||||
Backup: repos.DatabaseBackup,
|
||||
Staging: update.NewOSStagingArea(filepath.Join(filepath.Dir(settings.DBFile), updatesDirName)),
|
||||
Logger: log.Default(),
|
||||
CurrentVersion: settings.Version,
|
||||
Platform: domainUpdate.Platform{OS: runtime.GOOS, Arch: runtime.GOARCH},
|
||||
FeedURL: settings.UpdateFeedURL,
|
||||
Now: time.Now,
|
||||
})
|
||||
}
|
||||
|
||||
func InitContainer(settings config.Settings) (*UseCases, func() error) {
|
||||
db := getDb(settings.DBFile, settings.UploadDir)
|
||||
repos := getRepositories(db, settings)
|
||||
@@ -152,3 +244,42 @@ func closeDb(db *gorm.DB) func() error {
|
||||
return sqlDb.Close()
|
||||
}
|
||||
}
|
||||
|
||||
type BrowserUpdateCommands struct {
|
||||
Enable *useCases.EnableBrowserUpdatesUseCase
|
||||
Disable *useCases.DisableBrowserUpdatesUseCase
|
||||
}
|
||||
|
||||
func InitBrowserUpdateCommands() *BrowserUpdateCommands {
|
||||
units := update.NewSystemdUnits()
|
||||
dependencies := useCases.ManageBrowserUpdatesDependencies{
|
||||
Probe: update.NewSystemMachineProbe(),
|
||||
Locator: units,
|
||||
Units: units,
|
||||
Manager: update.NewSystemctlControl(domainUpdate.ServiceUnitName),
|
||||
Status: update.NewJSONHelperStatusWriter(),
|
||||
Now: time.Now,
|
||||
}
|
||||
return &BrowserUpdateCommands{
|
||||
Enable: useCases.NewEnableBrowserUpdatesUseCase(dependencies),
|
||||
Disable: useCases.NewDisableBrowserUpdatesUseCase(dependencies),
|
||||
}
|
||||
}
|
||||
|
||||
func InitApplyUpdateCommand(options domainUpdate.InstallOptions) *useCases.ApplyRestartRequestUseCase {
|
||||
layout := domainUpdate.HelperLayout{DataDir: options.DataDir, BinaryPath: options.Binary}
|
||||
files := update.NewNoFollowFilesystem()
|
||||
return useCases.NewApplyRestartRequestUseCase(useCases.ApplyRestartRequestDependencies{
|
||||
Requests: update.NewFSRestartRequestStore(files, layout.RestartRequestPath()),
|
||||
Results: update.NewFSResultStore(files, layout.ResultPath()),
|
||||
Running: update.NewJSONRunningInfoStore(filepath.Join(options.DataDir, domainUpdate.RunningInfoFileName)),
|
||||
Files: files,
|
||||
Service: update.NewSystemctlControl(options.Service),
|
||||
Health: update.NewHTTPHealthChecker(options.Port),
|
||||
Verifier: update.NewEd25519SignatureVerifier(releasePublicKey()),
|
||||
Clock: update.NewSystemClock(),
|
||||
Logger: log.Default(),
|
||||
Layout: layout,
|
||||
Platform: domainUpdate.Platform{OS: runtime.GOOS, Arch: runtime.GOARCH},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package apikey
|
||||
|
||||
import (
|
||||
"RenewCMS/api/pkg/apperr"
|
||||
"RenewCMS/api/pkg/claims"
|
||||
validator "RenewCMS/api/pkg/validator"
|
||||
domain "RenewCMS/internal/domain/apikey"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
CreateUseCase *useCases.CreateAPIKeyUseCase
|
||||
ListUseCase *useCases.ListAPIKeysUseCase
|
||||
RevokeUseCase *useCases.RevokeAPIKeyUseCase
|
||||
}
|
||||
|
||||
type CreateAPIKeyRequest struct {
|
||||
Name string `json:"name" validate:"required,max=60"`
|
||||
ExpiresAt *time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
type createdKeyResponse struct {
|
||||
ID uint32 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Prefix string `json:"prefix"`
|
||||
Key string `json:"key"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ExpiresAt *time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
type keyListItem struct {
|
||||
ID uint32 `json:"id"`
|
||||
UserID uint32 `json:"user_id"`
|
||||
Name string `json:"name"`
|
||||
Prefix string `json:"prefix"`
|
||||
Status domain.Status `json:"status"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
LastUsedAt *time.Time `json:"last_used_at"`
|
||||
ExpiresAt *time.Time `json:"expires_at"`
|
||||
RevokedAt *time.Time `json:"revoked_at"`
|
||||
CreatedByName *string `json:"created_by_name,omitempty"`
|
||||
}
|
||||
|
||||
func NewHandler(create *useCases.CreateAPIKeyUseCase, list *useCases.ListAPIKeysUseCase, revoke *useCases.RevokeAPIKeyUseCase) *Handler {
|
||||
return &Handler{CreateUseCase: create, ListUseCase: list, RevokeUseCase: revoke}
|
||||
}
|
||||
|
||||
func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
var request CreateAPIKeyRequest
|
||||
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
|
||||
}
|
||||
|
||||
created, err := h.CreateUseCase.CreateAPIKey(useCases.CreateAPIKeyCommand{
|
||||
UserID: userId,
|
||||
Name: request.Name,
|
||||
ExpiresAt: request.ExpiresAt,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrExpiryNotInFuture) {
|
||||
http.Error(w, apperr.APIKeyExpiryErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
body, err := json.Marshal(createdKeyResponse{
|
||||
ID: created.Key.ID,
|
||||
Name: created.Key.Name,
|
||||
Prefix: created.Key.Prefix,
|
||||
Key: created.RawKey,
|
||||
CreatedAt: created.Key.CreatedAt,
|
||||
ExpiresAt: created.Key.ExpiresAt,
|
||||
})
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_, _ = w.Write(body)
|
||||
}
|
||||
|
||||
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
|
||||
userId, ok := claims.UserId(r)
|
||||
if !ok {
|
||||
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
entries, err := h.ListUseCase.ListAPIKeys(userId)
|
||||
if err != nil {
|
||||
if errors.Is(err, user.ErrUserNotFound) {
|
||||
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
items := make([]keyListItem, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
key := entry.Key
|
||||
item := keyListItem{
|
||||
ID: key.ID,
|
||||
UserID: key.UserID,
|
||||
Name: key.Name,
|
||||
Prefix: key.Prefix,
|
||||
Status: entry.Status,
|
||||
CreatedAt: key.CreatedAt,
|
||||
LastUsedAt: key.LastUsedAt,
|
||||
ExpiresAt: key.ExpiresAt,
|
||||
RevokedAt: key.RevokedAt,
|
||||
}
|
||||
if entry.ListsCreator {
|
||||
item.CreatedByName = &entry.CreatorName
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
|
||||
body, err := json.Marshal(items)
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
_, _ = w.Write(body)
|
||||
}
|
||||
|
||||
func (h *Handler) Revoke(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
|
||||
if err != nil {
|
||||
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
userId, ok := claims.UserId(r)
|
||||
if !ok {
|
||||
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.RevokeUseCase.RevokeAPIKey(userId, uint32(id)); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrAPIKeyNotFound):
|
||||
http.Error(w, apperr.APIKeyNotFoundErrorMessage, http.StatusNotFound)
|
||||
case errors.Is(err, user.ErrUserNotFound):
|
||||
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||
default:
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
@@ -41,6 +42,53 @@ func NewHandler(create *useCases.CreateArticleUseCase, get *useCases.GetArticleU
|
||||
}
|
||||
}
|
||||
|
||||
type articleResponse struct {
|
||||
ID uint32 `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Body json.RawMessage `json:"body"`
|
||||
BodyFormat domain.BodyFormat `json:"body_format"`
|
||||
IsOnline bool `json:"is_online"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func toArticleResponse(article domain.Article, format domain.BodyFormat) (articleResponse, error) {
|
||||
body := json.RawMessage(article.Body)
|
||||
if format != domain.BodyFormatJSON {
|
||||
encoded, err := json.Marshal(article.Body)
|
||||
if err != nil {
|
||||
return articleResponse{}, err
|
||||
}
|
||||
body = encoded
|
||||
}
|
||||
return articleResponse{
|
||||
ID: article.ID,
|
||||
Title: article.Title,
|
||||
Body: body,
|
||||
BodyFormat: format,
|
||||
IsOnline: article.IsOnline,
|
||||
CreatedAt: article.CreatedAt,
|
||||
UpdatedAt: article.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func encodeArticle(article domain.Article, format domain.BodyFormat) ([]byte, error) {
|
||||
response, err := toArticleResponse(article, format)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(response)
|
||||
}
|
||||
|
||||
func parseBodyFormat(w http.ResponseWriter, r *http.Request) (domain.BodyFormat, bool) {
|
||||
format, err := domain.ParseBodyFormat(r.URL.Query().Get("format"))
|
||||
if err != nil {
|
||||
http.Error(w, apperr.ArticleBodyFormatErrorMessage, http.StatusBadRequest)
|
||||
return "", false
|
||||
}
|
||||
return format, true
|
||||
}
|
||||
|
||||
func parseArticleId(r *http.Request) (uint32, error) {
|
||||
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
|
||||
return uint32(id), err
|
||||
@@ -53,11 +101,16 @@ func (h *Handler) GetArticle(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
format, ok := parseBodyFormat(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var article domain.Article
|
||||
if h.callerIsVerified(r) {
|
||||
article, err = h.GetUseCase.GetArticle(id)
|
||||
article, err = h.GetUseCase.GetArticle(id, format)
|
||||
} else {
|
||||
article, err = h.GetUseCase.GetOnlineArticle(id)
|
||||
article, err = h.GetUseCase.GetOnlineArticle(id, format)
|
||||
}
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrArticleNotFound) {
|
||||
@@ -68,7 +121,7 @@ func (h *Handler) GetArticle(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
articleJson, err := json.Marshal(article)
|
||||
articleJson, err := encodeArticle(article, format)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
@@ -80,6 +133,11 @@ func (h *Handler) GetArticle(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (h *Handler) PostArticle(w http.ResponseWriter, r *http.Request) {
|
||||
format, ok := parseBodyFormat(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var localArticle PostArticle
|
||||
if err := json.NewDecoder(r.Body).Decode(&localArticle); err != nil {
|
||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||
@@ -94,6 +152,7 @@ func (h *Handler) PostArticle(w http.ResponseWriter, r *http.Request) {
|
||||
createdArticle, err := h.CreateUseCase.CreateArticle(useCases.CreateArticleCommand{
|
||||
Title: localArticle.Title,
|
||||
Body: localArticle.Body,
|
||||
Format: format,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrInvalidTitle) {
|
||||
@@ -104,16 +163,7 @@ func (h *Handler) PostArticle(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
articleJson, err := json.Marshal(createdArticle)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
if _, err := w.Write(articleJson); err != nil {
|
||||
log.Printf("Failed to write response: %v", err)
|
||||
}
|
||||
writeArticleJsonResponse(w, http.StatusCreated, createdArticle, format)
|
||||
}
|
||||
|
||||
func writeArticleErrorResponse(w http.ResponseWriter, err error) {
|
||||
@@ -124,13 +174,16 @@ func writeArticleErrorResponse(w http.ResponseWriter, err error) {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
func writeArticleJsonResponse(w http.ResponseWriter, article domain.Article) {
|
||||
articleJson, err := json.Marshal(article)
|
||||
func writeArticleJsonResponse(w http.ResponseWriter, status int, article domain.Article, format domain.BodyFormat) {
|
||||
articleJson, err := encodeArticle(article, format)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if status != http.StatusOK {
|
||||
w.WriteHeader(status)
|
||||
}
|
||||
if _, err := w.Write(articleJson); err != nil {
|
||||
log.Printf("Failed to write response: %v", err)
|
||||
}
|
||||
@@ -143,13 +196,18 @@ func (h *Handler) setIsOnline(w http.ResponseWriter, r *http.Request, isOnline b
|
||||
return
|
||||
}
|
||||
|
||||
updatedArticle, err := h.UpdateUseCase.UpdateIsOnline(id, isOnline)
|
||||
format, ok := parseBodyFormat(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
updatedArticle, err := h.UpdateUseCase.UpdateIsOnline(id, isOnline, format)
|
||||
if err != nil {
|
||||
writeArticleErrorResponse(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeArticleJsonResponse(w, updatedArticle)
|
||||
writeArticleJsonResponse(w, http.StatusOK, updatedArticle, format)
|
||||
}
|
||||
|
||||
type UpdateArticleBody struct {
|
||||
@@ -163,6 +221,11 @@ func (h *Handler) UpdateArticleBody(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
format, ok := parseBodyFormat(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var localArticle UpdateArticleBody
|
||||
if err := json.NewDecoder(r.Body).Decode(&localArticle); err != nil {
|
||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||
@@ -174,13 +237,13 @@ func (h *Handler) UpdateArticleBody(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
updatedArticle, err := h.UpdateUseCase.UpdateBody(id, localArticle.Body)
|
||||
updatedArticle, err := h.UpdateUseCase.UpdateBody(id, localArticle.Body, format)
|
||||
if err != nil {
|
||||
writeArticleErrorResponse(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeArticleJsonResponse(w, updatedArticle)
|
||||
writeArticleJsonResponse(w, http.StatusOK, updatedArticle, format)
|
||||
}
|
||||
|
||||
func (h *Handler) PublishArticle(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -206,19 +269,34 @@ func (h *Handler) callerIsVerified(r *http.Request) bool {
|
||||
}
|
||||
|
||||
func (h *Handler) ListArticles(w http.ResponseWriter, r *http.Request) {
|
||||
format, ok := parseBodyFormat(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var articles []domain.Article
|
||||
var err error
|
||||
if h.callerIsVerified(r) {
|
||||
articles, err = h.ListUseCase.ListAllArticles()
|
||||
articles, err = h.ListUseCase.ListAllArticles(format)
|
||||
} else {
|
||||
articles, err = h.ListUseCase.ListOnlineArticles()
|
||||
articles, err = h.ListUseCase.ListOnlineArticles(format)
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to retrieve articles", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
articlesJson, err := json.Marshal(articles)
|
||||
responses := make([]articleResponse, 0, len(articles))
|
||||
for _, article := range articles {
|
||||
response, err := toArticleResponse(article, format)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
responses = append(responses, response)
|
||||
}
|
||||
|
||||
articlesJson, err := json.Marshal(responses)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"RenewCMS/api/pkg/apperr"
|
||||
"RenewCMS/api/pkg/claims"
|
||||
validator "RenewCMS/api/pkg/validator"
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const restartBodyLimitBytes = 1024
|
||||
|
||||
type Handler struct {
|
||||
GetUpdateStatusUseCase *useCases.GetUpdateStatusUseCase
|
||||
CheckForUpdateUseCase *useCases.CheckForUpdateUseCase
|
||||
StartUpdateDownloadUseCase *useCases.StartUpdateDownloadUseCase
|
||||
RequestRestartUseCase *useCases.RequestRestartUseCase
|
||||
GetUserUseCase *useCases.GetUserUseCase
|
||||
}
|
||||
|
||||
type restartRequest struct {
|
||||
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 {
|
||||
return &Handler{
|
||||
GetUpdateStatusUseCase: getStatus,
|
||||
CheckForUpdateUseCase: checkForUpdate,
|
||||
StartUpdateDownloadUseCase: startDownload,
|
||||
RequestRestartUseCase: requestRestart,
|
||||
GetUserUseCase: getUser,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) GetStatus(w http.ResponseWriter, r *http.Request) {
|
||||
isOwner, ok := h.isOwner(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeStatus(w, http.StatusOK, h.GetUpdateStatusUseCase.GetStatus(isOwner))
|
||||
}
|
||||
|
||||
func (h *Handler) Check(w http.ResponseWriter, r *http.Request) {
|
||||
if _, err := h.CheckForUpdateUseCase.Check(); err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
isOwner, ok := h.isOwner(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeStatus(w, http.StatusOK, h.GetUpdateStatusUseCase.GetStatus(isOwner))
|
||||
}
|
||||
|
||||
func (h *Handler) Download(w http.ResponseWriter, _ *http.Request) {
|
||||
status, err := h.StartUpdateDownloadUseCase.Start()
|
||||
if err != nil {
|
||||
writeDownloadError(w, err)
|
||||
return
|
||||
}
|
||||
writeStatus(w, http.StatusAccepted, status)
|
||||
}
|
||||
|
||||
func (h *Handler) Restart(w http.ResponseWriter, r *http.Request) {
|
||||
kind, ok := decodeRestartKind(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
userId, ok := claims.UserId(r)
|
||||
if !ok {
|
||||
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
status, err := h.RequestRestartUseCase.Request(userId, kind)
|
||||
if err != nil {
|
||||
writeRestartError(w, err)
|
||||
return
|
||||
}
|
||||
writeStatus(w, http.StatusAccepted, status)
|
||||
}
|
||||
|
||||
func decodeRestartKind(w http.ResponseWriter, r *http.Request) (string, bool) {
|
||||
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, restartBodyLimitBytes))
|
||||
if err != nil {
|
||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||
return "", false
|
||||
}
|
||||
if strings.TrimSpace(string(body)) == "" {
|
||||
return "", true
|
||||
}
|
||||
var request restartRequest
|
||||
if err := json.Unmarshal(body, &request); err != nil || validator.Validate.Struct(request) != nil {
|
||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||
return "", false
|
||||
}
|
||||
if request.Kind == nil {
|
||||
return "", true
|
||||
}
|
||||
return *request.Kind, true
|
||||
}
|
||||
|
||||
func (h *Handler) isOwner(w http.ResponseWriter, r *http.Request) (bool, bool) {
|
||||
userId, ok := claims.UserId(r)
|
||||
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) {
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotPrepared):
|
||||
http.Error(w, apperr.UpdateNotPreparedErrorMessage, http.StatusConflict)
|
||||
case errors.Is(err, domain.ErrJobInProgress), errors.Is(err, domain.ErrRestartPending):
|
||||
http.Error(w, apperr.UpdateAlreadyRunningErrorMessage, http.StatusConflict)
|
||||
case errors.Is(err, domain.ErrNothingToUpdate):
|
||||
http.Error(w, apperr.NothingToUpdateErrorMessage, http.StatusBadRequest)
|
||||
case errors.Is(err, domain.ErrPreflightRefused):
|
||||
http.Error(w, apperr.UpdateRefusedErrorMessage, http.StatusUnprocessableEntity)
|
||||
default:
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
func writeRestartError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotPrepared):
|
||||
http.Error(w, apperr.UpdateNotPreparedErrorMessage, http.StatusConflict)
|
||||
case errors.Is(err, domain.ErrJobInProgress), errors.Is(err, domain.ErrRestartPending):
|
||||
http.Error(w, apperr.UpdateAlreadyRunningErrorMessage, http.StatusConflict)
|
||||
case errors.Is(err, domain.ErrRestartKindMismatch):
|
||||
http.Error(w, apperr.UpdateRestartMismatchErrorMessage, http.StatusConflict)
|
||||
default:
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
func writeStatus(w http.ResponseWriter, code int, status domain.UpdateStatus) {
|
||||
body, err := json.Marshal(status)
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(code)
|
||||
_, _ = w.Write(body)
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"RenewCMS/api/pkg/apperr"
|
||||
"RenewCMS/internal/domain/apikey"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
"github.com/lestrrat-go/jwx/v2/jwt"
|
||||
)
|
||||
|
||||
const bearerScheme = "bearer "
|
||||
|
||||
type apiKeyIdContextKey struct{}
|
||||
|
||||
func bearerAPIKey(r *http.Request) (string, bool) {
|
||||
header := r.Header.Get("Authorization")
|
||||
if len(header) < len(bearerScheme) || !strings.EqualFold(header[:len(bearerScheme)], bearerScheme) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
credential := strings.TrimSpace(header[len(bearerScheme):])
|
||||
return credential, strings.HasPrefix(credential, apikey.RawKeyPrefix)
|
||||
}
|
||||
|
||||
func apiKeyIdFrom(r *http.Request) (uint32, bool) {
|
||||
id, ok := r.Context().Value(apiKeyIdContextKey{}).(uint32)
|
||||
return id, ok
|
||||
}
|
||||
|
||||
func RequireSession(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if _, isKey := bearerAPIKey(r); isKey {
|
||||
http.Error(w, apperr.SessionRequiredErrorMessage, http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func APIKeyAuth(authenticate *useCases.AuthenticateAPIKeyUseCase, maxRequests int, window time.Duration) func(http.Handler) http.Handler {
|
||||
limiter := newKeyedRateLimiter(maxRequests, window, apiKeyRateLimitKey)
|
||||
|
||||
return func(next http.Handler) http.Handler {
|
||||
limited := limiter(next)
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
rawKey, isKey := bearerAPIKey(r)
|
||||
if !isKey {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
authenticated, err := authenticate.AuthenticateAPIKey(rawKey)
|
||||
if err != nil {
|
||||
writeAPIKeyError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
token, err := sessionTokenFor(authenticated)
|
||||
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)
|
||||
limited.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func writeAPIKeyError(w http.ResponseWriter, err error) {
|
||||
if errors.Is(err, apikey.ErrAPIKeyInvalid) {
|
||||
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
func sessionTokenFor(authenticated useCases.AuthenticatedAPIKey) (jwt.Token, error) {
|
||||
token := jwt.New()
|
||||
if err := token.Set("user_id", float64(authenticated.User.ID)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := token.Set("token_version", float64(authenticated.User.TokenVersion)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return token, nil
|
||||
}
|
||||
|
||||
func apiKeyRateLimitKey(r *http.Request) string {
|
||||
id, _ := apiKeyIdFrom(r)
|
||||
return strconv.FormatUint(uint64(id), 10)
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package middleware
|
||||
|
||||
import (
|
||||
"RenewCMS/api/pkg/apperr"
|
||||
"RenewCMS/api/pkg/claims"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"sync"
|
||||
@@ -14,12 +15,25 @@ type rateLimitWindow struct {
|
||||
}
|
||||
|
||||
func NewRateLimiter(maxAttempts int, window time.Duration) func(http.Handler) http.Handler {
|
||||
return newKeyedRateLimiter(maxAttempts, window, func(r *http.Request) string { return r.RemoteAddr })
|
||||
}
|
||||
|
||||
func NewUserRateLimiter(maxAttempts int, window time.Duration) func(http.Handler) http.Handler {
|
||||
return newKeyedRateLimiter(maxAttempts, window, userRateLimitKey)
|
||||
}
|
||||
|
||||
func userRateLimitKey(r *http.Request) string {
|
||||
userId, _ := claims.UserId(r)
|
||||
return strconv.FormatUint(uint64(userId), 10)
|
||||
}
|
||||
|
||||
func newKeyedRateLimiter(maxAttempts int, window time.Duration, keyOf func(*http.Request) string) func(http.Handler) http.Handler {
|
||||
var mu sync.Mutex
|
||||
windows := make(map[string]*rateLimitWindow)
|
||||
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
retryAfter, allowed := recordAttempt(&mu, windows, r.RemoteAddr, maxAttempts, window)
|
||||
retryAfter, allowed := recordAttempt(&mu, windows, keyOf(r), maxAttempts, window)
|
||||
if !allowed {
|
||||
w.Header().Set("Retry-After", strconv.Itoa(retryAfter))
|
||||
http.Error(w, apperr.TooManyRequestsErrorMessage, http.StatusTooManyRequests)
|
||||
|
||||
@@ -29,3 +29,12 @@ const MediaQueryErrorMessage = "The media query is invalid."
|
||||
const MediaFilenameErrorMessage = "Enter a filename."
|
||||
const MediaMergeConflictErrorMessage = "Some of the images to merge changed. Refresh and try again."
|
||||
const MediaMergeRequestErrorMessage = "Choose an image to keep and at least one other image to merge into it."
|
||||
const UpdateNotPreparedErrorMessage = "This server cannot update itself yet."
|
||||
const UpdateAlreadyRunningErrorMessage = "An update is already running or waiting to be installed."
|
||||
const NothingToUpdateErrorMessage = "There is nothing to update."
|
||||
const UpdateRefusedErrorMessage = "This update cannot be downloaded."
|
||||
const UpdateRestartMismatchErrorMessage = "The update state changed. Reload the page and try again."
|
||||
const ArticleBodyFormatErrorMessage = "The format must be one of: markdown, html, json."
|
||||
const APIKeyNotFoundErrorMessage = "API key not found"
|
||||
const APIKeyExpiryErrorMessage = "The expiry must be a date in the future."
|
||||
const SessionRequiredErrorMessage = "This action needs a real session."
|
||||
+80
-1
@@ -1,17 +1,20 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"RenewCMS/api/handlers/apikey"
|
||||
"RenewCMS/api/handlers/article"
|
||||
"RenewCMS/api/handlers/auth"
|
||||
"RenewCMS/api/handlers/frontend"
|
||||
"RenewCMS/api/handlers/media"
|
||||
"RenewCMS/api/handlers/settings"
|
||||
"RenewCMS/api/handlers/staticimages"
|
||||
"RenewCMS/api/handlers/update"
|
||||
"RenewCMS/api/handlers/user"
|
||||
"RenewCMS/api/middleware"
|
||||
"RenewCMS/internal/infrastructure/config"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/MadAppGang/httplog"
|
||||
"github.com/go-chi/chi/v5"
|
||||
@@ -31,8 +34,21 @@ func GetHelloWorld(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write(msg)
|
||||
}
|
||||
|
||||
const (
|
||||
apiKeyMaxRequests = 120
|
||||
apiKeyWindow = time.Minute
|
||||
)
|
||||
|
||||
func (c *UseCases) apiKeyAuth() func(http.Handler) http.Handler {
|
||||
c.apiKeyAuthOnce.Do(func() {
|
||||
c.apiKeyAuthMiddleware = middleware.APIKeyAuth(c.AuthenticateAPIKeyUseCase, apiKeyMaxRequests, apiKeyWindow)
|
||||
})
|
||||
return c.apiKeyAuthMiddleware
|
||||
}
|
||||
|
||||
func NewArticleRouter(container *UseCases) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
r.Use(container.apiKeyAuth())
|
||||
|
||||
articleHandler := article.NewHandler(container.CreateArticleUseCase, container.GetArticleUseCase, container.ListArticlesUseCase, container.DeleteArticleUseCase, container.UpdateArticleUseCase, container.GetUserUseCase)
|
||||
|
||||
@@ -83,11 +99,18 @@ func NewAuthRouter(container *UseCases, isProduction bool, rateLimit config.Auth
|
||||
r.Post("/invite/accept", acceptInviteHandler.AcceptInvite)
|
||||
})
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(middleware.RequireSession)
|
||||
r.Use(jwtauth.Verifier(container.Token))
|
||||
r.Use(jwtauth.Authenticator(container.Token))
|
||||
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||
r.Post("/verify", verificationHandler.Verify)
|
||||
r.Delete("/register", verificationHandler.CancelRegistration)
|
||||
})
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(jwtauth.Verifier(container.Token))
|
||||
r.Use(container.apiKeyAuth())
|
||||
r.Use(jwtauth.Authenticator(container.Token))
|
||||
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||
r.Get("/me", meHandler.Me)
|
||||
})
|
||||
return r
|
||||
@@ -100,6 +123,7 @@ func NewUserRouter(container *UseCases, rateLimit config.AuthRateLimitSettings,
|
||||
inviteHandler := user.NewInviteHandler(container.CreateInviteUseCase, container.CancelInviteUseCase, container.RenewInviteUseCase, container.ListUsersAndInvitesUseCase)
|
||||
|
||||
r.Use(jwtauth.Verifier(container.Token))
|
||||
r.Use(container.apiKeyAuth())
|
||||
r.Use(jwtauth.Authenticator(container.Token))
|
||||
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||
@@ -122,6 +146,7 @@ func NewSettingsRouter(container *UseCases) http.Handler {
|
||||
settingsHandler := settings.NewHandler(container.GetSettingsUseCase)
|
||||
|
||||
r.Use(jwtauth.Verifier(container.Token))
|
||||
r.Use(container.apiKeyAuth())
|
||||
r.Use(jwtauth.Authenticator(container.Token))
|
||||
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||
@@ -129,12 +154,64 @@ func NewSettingsRouter(container *UseCases) http.Handler {
|
||||
return r
|
||||
}
|
||||
|
||||
const (
|
||||
updateCheckMaxAttempts = 5
|
||||
updateCheckWindow = time.Minute
|
||||
updateDownloadMaxAttempts = 5
|
||||
updateDownloadWindow = time.Minute
|
||||
)
|
||||
|
||||
func NewSystemRouter(container *UseCases) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
updateHandler := update.NewHandler(container.GetUpdateStatusUseCase, container.CheckForUpdateUseCase, container.StartUpdateDownloadUseCase, container.RequestRestartUseCase, container.GetUserUseCase)
|
||||
|
||||
r.Use(middleware.RequireSession)
|
||||
r.Use(jwtauth.Verifier(container.Token))
|
||||
r.Use(jwtauth.Authenticator(container.Token))
|
||||
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||
r.Get("/update", updateHandler.GetStatus)
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(middleware.RequireOwner(container.GetUserUseCase))
|
||||
r.Use(middleware.NewUserRateLimiter(updateCheckMaxAttempts, updateCheckWindow))
|
||||
r.Post("/update/check", updateHandler.Check)
|
||||
})
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(middleware.RequireOwner(container.GetUserUseCase))
|
||||
r.Use(middleware.NewUserRateLimiter(updateDownloadMaxAttempts, updateDownloadWindow))
|
||||
r.Post("/update/download", updateHandler.Download)
|
||||
})
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(middleware.RequireOwner(container.GetUserUseCase))
|
||||
r.Post("/update/restart", updateHandler.Restart)
|
||||
})
|
||||
return r
|
||||
}
|
||||
|
||||
func NewAPIKeyRouter(container *UseCases) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
apiKeyHandler := apikey.NewHandler(container.CreateAPIKeyUseCase, container.ListAPIKeysUseCase, container.RevokeAPIKeyUseCase)
|
||||
|
||||
r.Use(middleware.RequireSession)
|
||||
r.Use(jwtauth.Verifier(container.Token))
|
||||
r.Use(jwtauth.Authenticator(container.Token))
|
||||
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||
r.Post("/", apiKeyHandler.Create)
|
||||
r.Get("/", apiKeyHandler.List)
|
||||
r.Delete("/{id}", apiKeyHandler.Revoke)
|
||||
return r
|
||||
}
|
||||
|
||||
func NewMediaRouter(container *UseCases) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
mediaHandler := media.NewHandler(container.CreateImageUseCase, container.ListMediaUseCase, container.RenameMediaUseCase, container.DeleteMediaUseCase, container.MergeMediaUseCase, container.GetMediaUsageUseCase)
|
||||
|
||||
r.Use(jwtauth.Verifier(container.Token))
|
||||
r.Use(container.apiKeyAuth())
|
||||
r.Use(jwtauth.Authenticator(container.Token))
|
||||
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||
@@ -162,6 +239,8 @@ func InitBackendRoutes(container *UseCases, settings config.Settings) *chi.Mux {
|
||||
r.Mount("/user", NewUserRouter(container, settings.AuthRateLimit, settings.TrustedProxies))
|
||||
r.Mount("/settings", NewSettingsRouter(container))
|
||||
r.Mount("/media", NewMediaRouter(container))
|
||||
r.Mount("/api-key", NewAPIKeyRouter(container))
|
||||
r.Mount("/system", NewSystemRouter(container))
|
||||
r.Mount("/auth", NewAuthRouter(container, settings.IsProduction(), settings.AuthRateLimit, settings.TrustedProxies))
|
||||
|
||||
return r
|
||||
@@ -188,7 +267,7 @@ func enableCorsIfConfigured(r *chi.Mux, origins []string) {
|
||||
}
|
||||
r.Use(cors.Handler(cors.Options{
|
||||
AllowedOrigins: origins,
|
||||
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
|
||||
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
|
||||
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
|
||||
ExposedHeaders: []string{"Link"},
|
||||
AllowCredentials: false,
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/infrastructure/update/releasesign"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
os.Exit(releasesign.Run(os.Args[1:], os.Stdout, os.Stderr))
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"RenewCMS/api"
|
||||
"RenewCMS/internal/domain/update"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
)
|
||||
|
||||
const (
|
||||
enableCommand = "enable-browser-updates"
|
||||
disableCommand = "disable-browser-updates"
|
||||
applyCommand = "apply-update"
|
||||
|
||||
exitOK = 0
|
||||
exitError = 1
|
||||
exitUsage = 2
|
||||
|
||||
usageText = "usage: renewcms [--version]\n" +
|
||||
" renewcms enable-browser-updates [--service NAME] [--binary PATH] [--data-dir DIR] [--port PORT]\n" +
|
||||
" renewcms disable-browser-updates [--service NAME] [--data-dir DIR]\n" +
|
||||
" renewcms apply-update --binary PATH --data-dir DIR [--service NAME] [--port PORT]"
|
||||
|
||||
applyNeedsFlagsMessage = "apply-update needs --binary and --data-dir."
|
||||
)
|
||||
|
||||
func runCommand(args []string, stdout io.Writer, stderr io.Writer) int {
|
||||
name, rest := args[0], args[1:]
|
||||
switch name {
|
||||
case enableCommand:
|
||||
return withOptions(name, rest, stderr, func(options update.InstallOptions) int {
|
||||
message, err := api.InitBrowserUpdateCommands().Enable.Enable(options)
|
||||
return printOutcome(stdout, stderr, message, err)
|
||||
})
|
||||
case disableCommand:
|
||||
return withOptions(name, rest, stderr, func(options update.InstallOptions) int {
|
||||
message, err := api.InitBrowserUpdateCommands().Disable.Disable(options)
|
||||
return printOutcome(stdout, stderr, message, err)
|
||||
})
|
||||
case applyCommand:
|
||||
return withOptions(name, rest, stderr, func(options update.InstallOptions) int {
|
||||
return apply(options, stderr)
|
||||
})
|
||||
}
|
||||
fmt.Fprintln(stderr, usageText)
|
||||
return exitUsage
|
||||
}
|
||||
|
||||
func withOptions(name string, args []string, stderr io.Writer, run func(update.InstallOptions) int) int {
|
||||
flags := flag.NewFlagSet(name, flag.ContinueOnError)
|
||||
flags.SetOutput(stderr)
|
||||
var options update.InstallOptions
|
||||
flags.StringVar(&options.Service, "service", "", "systemd service name of RenewCMS")
|
||||
flags.StringVar(&options.Binary, "binary", "", "path of the RenewCMS binary")
|
||||
flags.StringVar(&options.DataDir, "data-dir", "", "directory that holds DB_FILE")
|
||||
flags.StringVar(&options.Port, "port", "", "port RenewCMS listens on")
|
||||
if err := flags.Parse(args); err != nil {
|
||||
return exitUsage
|
||||
}
|
||||
return run(options)
|
||||
}
|
||||
|
||||
func printOutcome(stdout io.Writer, stderr io.Writer, message string, err error) int {
|
||||
if err != nil {
|
||||
fmt.Fprintln(stderr, err)
|
||||
return exitError
|
||||
}
|
||||
fmt.Fprintln(stdout, message)
|
||||
return exitOK
|
||||
}
|
||||
|
||||
func apply(options update.InstallOptions, stderr io.Writer) int {
|
||||
if options.Binary == "" || options.DataDir == "" {
|
||||
fmt.Fprintln(stderr, applyNeedsFlagsMessage)
|
||||
return exitUsage
|
||||
}
|
||||
if options.Service == "" {
|
||||
options.Service = update.DefaultService
|
||||
}
|
||||
if options.Port == "" {
|
||||
options.Port = update.DefaultPort
|
||||
}
|
||||
if err := api.InitApplyUpdateCommand(options).Apply(); err != nil {
|
||||
log.Printf("apply-update failed: %v", err)
|
||||
return exitError
|
||||
}
|
||||
return exitOK
|
||||
}
|
||||
+24
-5
@@ -8,6 +8,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
@@ -47,9 +48,19 @@ var envDefaults = map[string]string{
|
||||
"AUTH_RATE_LIMIT_MAX_ATTEMPTS": "5",
|
||||
"AUTH_RATE_LIMIT_WINDOW_SECONDS": "60",
|
||||
"TRUSTED_PROXIES": "",
|
||||
"UPDATE_FEED_URL": "https://git.floriansylvain.fr",
|
||||
}
|
||||
|
||||
const versionFlag = "--version"
|
||||
|
||||
func main() {
|
||||
if len(os.Args) == 2 && os.Args[1] == versionFlag {
|
||||
fmt.Println(version)
|
||||
return
|
||||
}
|
||||
if len(os.Args) > 1 {
|
||||
os.Exit(runCommand(os.Args[1:], os.Stdout, os.Stderr))
|
||||
}
|
||||
if err := run(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
@@ -69,7 +80,7 @@ func run() error {
|
||||
validator.InitValidator()
|
||||
|
||||
server := newServer(api.InitRoutes(container, settings), settings)
|
||||
return serveUntilStopped(server, settings)
|
||||
return serveUntilStopped(server, settings, container.RecordRunningInfoUseCase.Record)
|
||||
}
|
||||
|
||||
func initEnvVariables() {
|
||||
@@ -120,12 +131,12 @@ func newServer(handler http.Handler, settings config.Settings) *http.Server {
|
||||
}
|
||||
}
|
||||
|
||||
func serveUntilStopped(server *http.Server, settings config.Settings) error {
|
||||
func serveUntilStopped(server *http.Server, settings config.Settings, recordRunning func() error) error {
|
||||
stopSignal, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
serverErr := make(chan error, 1)
|
||||
go listen(server, serverErr, settings)
|
||||
go listen(server, serverErr, settings, recordRunning)
|
||||
|
||||
select {
|
||||
case err := <-serverErr:
|
||||
@@ -135,9 +146,17 @@ func serveUntilStopped(server *http.Server, settings config.Settings) error {
|
||||
}
|
||||
}
|
||||
|
||||
func listen(server *http.Server, serverErr chan<- error, settings config.Settings) {
|
||||
func listen(server *http.Server, serverErr chan<- error, settings config.Settings, recordRunning func() error) {
|
||||
listener, err := net.Listen("tcp", server.Addr)
|
||||
if err != nil {
|
||||
serverErr <- err
|
||||
return
|
||||
}
|
||||
if err := recordRunning(); err != nil {
|
||||
log.Printf("WARNING: could not write the running-version file: %v", err)
|
||||
}
|
||||
log.Printf("RenewCMS %s (%s) listening on %s, public URL %s", version, settings.Environment, server.Addr, settings.PublicURL)
|
||||
err := server.ListenAndServe()
|
||||
err = server.Serve(listener)
|
||||
if errors.Is(err, http.ErrServerClosed) {
|
||||
err = nil
|
||||
}
|
||||
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
# API reference
|
||||
|
||||
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
|
||||
readers without the UI.
|
||||
|
||||
## Base URL
|
||||
The origin that serves the app, for example `https://cms.example`. Every path starts with `/v1`,
|
||||
for example `https://cms.example/v1/article/`.
|
||||
|
||||
## Authentication
|
||||
- Public routes need nothing: `GET /v1/article/` and `GET /v1/article/{id}`. They return online
|
||||
articles only.
|
||||
- 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
|
||||
creator, with that user's role, and shows in full once.
|
||||
- A key cannot call `POST /v1/auth/verify`, `DELETE /v1/auth/register`, `/v1/api-key/*` or
|
||||
`/v1/system/*`. Those answer 403 "This action needs a real session." An invalid, unknown, expired
|
||||
or revoked key answers 401, even on public routes.
|
||||
- Each key can make 120 requests per minute. Beyond that: 429 with a `Retry-After` header.
|
||||
|
||||
## Routes a key can call (20)
|
||||
| Group | Routes |
|
||||
| --- | --- |
|
||||
| Articles | GET /v1/article/, GET /v1/article/{id}, POST /v1/article/, PATCH /v1/article/{id}, PATCH /v1/article/{id}/publish, PATCH /v1/article/{id}/unpublish, DELETE /v1/article/{id} |
|
||||
| Media | GET /v1/media/, POST /v1/media/, PATCH /v1/media/{id}, DELETE /v1/media/{id}, POST /v1/media/merge, GET /v1/media/{id}/usage |
|
||||
| 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 |
|
||||
| Settings | GET /v1/settings |
|
||||
|
||||
Article routes accept `?format=markdown|html|json` (default `markdown`). `GET /v1/media/` accepts
|
||||
`q`, `hash`, `cursor`, `filter`, `sort` and `limit`.
|
||||
|
||||
## Errors
|
||||
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.
|
||||
|
||||
## Notes
|
||||
- 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.
|
||||
@@ -0,0 +1,23 @@
|
||||
# API keys
|
||||
|
||||
Developers can authenticate against `/v1` with a named API key sent as `Authorization: Bearer rcms_...` instead of the `jwt` cookie. A key acts with exactly the rights of the user who created it.
|
||||
|
||||
## Managing keys
|
||||
|
||||
Key management needs a real session (the `jwt` cookie from a verified user).
|
||||
|
||||
- `POST /v1/api-key` with `{"name": "ci", "expires_at": "<RFC3339, optional>"}` answers `201` with `id`, `name`, `prefix`, `key`, `created_at`, `expires_at`. The full `key` is shown once and never again.
|
||||
- `GET /v1/api-key` lists the caller's keys (all keys for the owner), newest first, with a `status` of `active`, `expired` or `revoked`.
|
||||
- `DELETE /v1/api-key/{id}` revokes a key and answers `204`. Revoking twice keeps the first `revoked_at`.
|
||||
|
||||
Only the SHA-256 hash and a 12 character prefix are stored.
|
||||
|
||||
## Where a key is accepted
|
||||
|
||||
`/v1/article` (public and protected routes), `/v1/user`, `/v1/media`, `/v1/settings` and `GET /v1/auth/me`. An invalid, expired or revoked `rcms_` key answers `401` and is never treated as anonymous. Each key is limited to 120 requests per minute (`429` with `Retry-After`). `last_used_at` is updated at most once per minute.
|
||||
|
||||
## Session-only routes
|
||||
|
||||
`/v1/api-key`, `POST /v1/auth/verify`, `DELETE /v1/auth/register` and every `/v1/system` route answer `403 This action needs a real session.` to any `rcms_` Bearer header. The public auth routes ignore the header.
|
||||
|
||||
A successful password reset revokes every key of that user.
|
||||
@@ -0,0 +1,97 @@
|
||||
# Reading articles
|
||||
|
||||
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.
|
||||
|
||||
## Routes that honour `format`
|
||||
|
||||
- `GET /v1/article/`
|
||||
- `GET /v1/article/{id}`
|
||||
- `POST /v1/article/`
|
||||
- `PATCH /v1/article/{id}`
|
||||
- `PATCH /v1/article/{id}/publish`
|
||||
- `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`.
|
||||
|
||||
## The `format` parameter
|
||||
|
||||
| Value | `body` | `body_format` |
|
||||
| --- | --- | --- |
|
||||
| empty or absent | markdown string | `markdown` |
|
||||
| `markdown` | markdown string | `markdown` |
|
||||
| `html` | the stored HTML string | `html` |
|
||||
| `json` | JSON array of blocks | `json` |
|
||||
|
||||
Values are case-insensitive. When `format` is repeated, the first value is used. Any other value answers `400` with the plain-text message `The format must be one of: markdown, html, json.` before any article is read or written. An invalid id is reported first, ahead of the format.
|
||||
|
||||
Breaking change: the default used to be HTML. Clients that need HTML must send `?format=html`. The web interface does so.
|
||||
|
||||
## Article object
|
||||
|
||||
```json
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Backyard Renovation Update",
|
||||
"body": "## Plan\n\nReplace the **old** deck.",
|
||||
"body_format": "markdown",
|
||||
"is_online": true,
|
||||
"created_at": "2026-03-12T09:14:00Z",
|
||||
"updated_at": "2026-09-10T07:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
## 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.
|
||||
|
||||
### Text alignment
|
||||
|
||||
Markdown has no syntax for alignment, so centered, right-aligned and justified paragraphs and headings are wrapped in a `div` with an inline style. The blank lines around the content make CommonMark parse the inside as markdown:
|
||||
|
||||
```markdown
|
||||
<div style="text-align: center">
|
||||
|
||||
A **centered** paragraph
|
||||
|
||||
</div>
|
||||
```
|
||||
|
||||
Left alignment is the default and produces no wrapper. Your markdown renderer must allow raw HTML for the alignment to show (`html: true` in markdown-it); otherwise the wrapper tags appear as text, and a client that does not want them can request `?format=json` instead, where the alignment is a field.
|
||||
|
||||
## JSON block schema
|
||||
|
||||
`body` is a native JSON array. Every block has a `type`.
|
||||
|
||||
| Block | Fields |
|
||||
| --- | --- |
|
||||
| `heading` | `level` (1 to 6), `align` (only when `center`, `right` or `justify`), `children` (text nodes) |
|
||||
| `paragraph` | `align` (only when `center`, `right` or `justify`), `children` (text nodes, empty array for an empty paragraph) |
|
||||
| `list` | `ordered` (boolean), `items` (array of items, each an array of blocks) |
|
||||
| `blockquote` | `children` (blocks) |
|
||||
| `code` | `language` (empty string when unknown), `text` |
|
||||
| `hr` | none |
|
||||
| `image` | `src`, `alt` (empty string when missing) |
|
||||
|
||||
Text node: `{"type":"text","text":"...","marks":[...]}`. `marks` is always an array, listed outermost first. A mark is `{"type":"bold"}`, `{"type":"italic"}` or `{"type":"link","href":"..."}`. A line break becomes a `"\n"` inside the text. Adjacent text with identical marks is merged. Inline code, underline, strike-through and other formatting degrade to plain text. An image inside a paragraph becomes its own block and splits the paragraph. An empty body is `[]`.
|
||||
|
||||
Example for `<h2>Plan</h2><p>Replace the <strong>old</strong> deck.</p>`:
|
||||
|
||||
```json
|
||||
[
|
||||
{"type":"heading","level":2,"children":[{"type":"text","text":"Plan","marks":[]}]},
|
||||
{"type":"paragraph","children":[
|
||||
{"type":"text","text":"Replace the ","marks":[]},
|
||||
{"type":"text","text":"old","marks":[{"type":"bold"}]},
|
||||
{"type":"text","text":" deck.","marks":[]}
|
||||
]}
|
||||
]
|
||||
```
|
||||
|
||||
## Errors
|
||||
|
||||
| Status | Body |
|
||||
| --- | --- |
|
||||
| `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 |
|
||||
| `404` | `Article not found` |
|
||||
| `500` | `Internal server error` when the body cannot be converted |
|
||||
@@ -30,9 +30,12 @@ Copy [`.env.example`](../.env.example) to `.env` to get started. When a required
|
||||
| `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. |
|
||||
| `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). |
|
||||
| `UPDATE_FEED_URL` | `https://git.floriansylvain.fr` | Base URL of the Gitea server that publishes RenewCMS releases. The Settings page asks `{UPDATE_FEED_URL}/api/v1/repos/fsylvain/RenewCMS/releases` when the owner checks for updates. The last result is kept in `update-status.json`, next to `DB_FILE`. |
|
||||
|
||||
Relative paths are resolved against the process's working directory. In production, use absolute paths (see [deployment.md](deployment.md)).
|
||||
|
||||
For example, `WorkingDirectory=/var/lib/renewcms` with `DB_FILE=./data/renewcms.db` puts the database in `/var/lib/renewcms/data`. Browser-update `--data-dir` must name that directory, because the app reads helper status and update records beside the database. It is not necessarily `WorkingDirectory` or `ReadWritePaths`. Do not change an existing `DB_FILE` merely to match the helper: that could open a different, empty database. See [browser-update setup](deployment.md#browser-updates).
|
||||
|
||||
## Adding a variable
|
||||
|
||||
1. Read it in the code where it is needed (infrastructure or `api/`, never `internal/domain`).
|
||||
|
||||
+139
-1
@@ -8,7 +8,7 @@ RenewCMS ships as **one self-contained executable**. It serves:
|
||||
| `/healthz` | Liveness check, returns `200 ok` |
|
||||
| `/*` | The Vue SPA (embedded), with fallback to `index.html` for client-side routes |
|
||||
|
||||
Its only runtime state is the SQLite database (`DB_FILE`) and the uploads directory (`UPLOAD_DIR`). Nothing else needs to be installed on the server.
|
||||
Runtime state includes the SQLite database (`DB_FILE`), uploads (`UPLOAD_DIR`), and update records, staged binaries and backups beside the database. Running a release binary needs no Go, Bun or Node installation. Browser updates additionally require Linux with systemd and the helper setup below.
|
||||
|
||||
## 1. Build
|
||||
|
||||
@@ -19,8 +19,146 @@ task build # this OS/arch → bin/renewcms[.exe]
|
||||
task release # all targets → bin/renewcms_<version>_<os>_<arch>[.exe]
|
||||
```
|
||||
|
||||
`task release` also signs the release: it writes `bin/checksums.txt` (SHA-256 of the six binaries) and signs it into `bin/checksums.txt.sig` with an Ed25519 key. It refuses to start, before building anything, unless `RELEASE_SIGNING_KEY` points to the private key file and that key matches the public key committed as `internal/infrastructure/update/release.pub`. The one-time setup is below.
|
||||
|
||||
The frontend is built once and embedded into every binary. The binaries are static (`CGO_ENABLED=0`), so a Linux build runs on any distribution. The version comes from `git describe`: tag a release (`git tag v1.2.0`) before building, and the binary logs its version at startup.
|
||||
|
||||
### Release signing key (maintainers, once)
|
||||
|
||||
1. Run `task release:keygen -- <path>` with a path outside the repository (for example `~/.renewcms/release.key`). The private key is written there and never leaves your machine; keygen refuses a path inside the work tree.
|
||||
2. Commit the printed public key as `internal/infrastructure/update/release.pub`. A placeholder key (32 zero bytes) prevents signing. Official releases already embed the project's public key; this setup is for release maintainers, not site operators. Never copy the private signing key to a CMS server.
|
||||
3. Export `RELEASE_SIGNING_KEY=<path to the private key>` before every `task release`.
|
||||
|
||||
To check a download by hand: `go run ./cmd/releasesign verify checksums.txt`, with `checksums.txt.sig` next to it, then compare the binary's hash with the matching line of `checksums.txt`.
|
||||
|
||||
### Update checks
|
||||
|
||||
The owner's Settings page asks the release feed for the newest release (see `UPDATE_FEED_URL` in [configuration.md](configuration.md)) and keeps the last result in `update-status.json`, next to `DB_FILE`. Back it up with the rest of the data directory if you like; it is rebuilt by the next check when missing. The Settings page reports a newer version. To install it from the browser, set up [Browser updates](#browser-updates) once on the server.
|
||||
|
||||
### Update downloads
|
||||
|
||||
Once the restart helper is installed (it writes `update-helper.json` next to `DB_FILE`), the owner's Update button downloads the new binary, `checksums.txt` and `checksums.txt.sig` from the release feed host over https only, checks the ed25519 signature and the SHA-256, runs the staged binary with `--version`, copies the database into `backups/` (the last 3 copies are kept) and stages everything under `updates/<tag>/`, all next to `DB_FILE`. The job record is `update-job.json`. Nothing running is replaced and the site is not restarted by the download: the owner's Restart button does that, as described in [Browser updates](#browser-updates). `renewcms --version` prints the build version and exits.
|
||||
|
||||
### Browser updates
|
||||
|
||||
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.
|
||||
|
||||
#### Find the actual database directory
|
||||
|
||||
The helper's `--data-dir` must be the directory containing `DB_FILE`. Inspect the relevant settings without printing the configuration's secrets:
|
||||
|
||||
```sh
|
||||
sudo systemctl show renewcms -p User -p WorkingDirectory
|
||||
sudo grep '^DB_FILE=' /etc/renewcms/renewcms.env
|
||||
```
|
||||
|
||||
| WorkingDirectory | DB_FILE | Correct --data-dir |
|
||||
| --- | --- | --- |
|
||||
| `/var/lib/renewcms` | `/var/lib/renewcms/renewcms.db` | `/var/lib/renewcms` |
|
||||
| `/var/lib/renewcms` | `./data/renewcms.db` | `/var/lib/renewcms/data` |
|
||||
|
||||
Leave an existing `DB_FILE` unchanged: changing it can open a different, empty database. Configure the helper to match the existing database instead.
|
||||
|
||||
#### Enable the helper
|
||||
|
||||
For this guide's absolute database path and port 8080, run:
|
||||
|
||||
```sh
|
||||
sudo /opt/renewcms/renewcms enable-browser-updates \
|
||||
--service renewcms \
|
||||
--binary /opt/renewcms/renewcms \
|
||||
--data-dir /var/lib/renewcms \
|
||||
--port 8080
|
||||
```
|
||||
|
||||
Replace these flags with your actual paths and port. For the relative database example above and port 8788, use `--data-dir /var/lib/renewcms/data --port 8788`. The absolute executable path works even when `/opt/renewcms` is absent from sudo's PATH.
|
||||
|
||||
Without explicit flags, discovery reads `/etc/systemd/system/renewcms.service` and takes its first `ReadWritePaths` entry as the data directory. It does not resolve `DB_FILE`, so explicit flags are necessary when these directories differ or the unit lives elsewhere. The port comes from `--port`, else `PORT` in the unit's `EnvironmentFile`, else 8080. The helper polls `/healthz` on `127.0.0.1` at that port. It then:
|
||||
|
||||
- writes `renewcms-update.path` and `renewcms-update.service` next to your other units in `/etc/systemd/system` (no secret and no environment value goes into them);
|
||||
- runs `systemctl daemon-reload` and enables and starts the path unit;
|
||||
- writes `update-helper.json` in the data directory last, so the Settings page only offers Update and Restart once everything else worked.
|
||||
|
||||
Running it again rewrites the units and the status file to the current values. If a step fails, the units it wrote are removed again and `update-helper.json` is not written.
|
||||
|
||||
#### Verify setup and test a plain restart
|
||||
|
||||
For the layout above, run these checks, substituting your service user and database directory if different:
|
||||
|
||||
```sh
|
||||
systemctl is-active renewcms-update.path
|
||||
systemctl is-enabled renewcms-update.path
|
||||
sudo systemctl cat renewcms-update.service
|
||||
sudo -u renewcms cat /var/lib/renewcms/update-helper.json
|
||||
```
|
||||
|
||||
Expect `active`, `enabled`, an `ExecStart` with the correct paths and port, and readable JSON. Reload Settings as owner. With no update waiting, Restart should appear. Press it, confirm the plain restart dialog, and expect the overlay followed by the site returning and a “Site restarted” message.
|
||||
|
||||
Then run:
|
||||
|
||||
```sh
|
||||
systemctl is-active renewcms
|
||||
sudo cat /var/lib/renewcms/update-result.json
|
||||
sudo cat /var/lib/renewcms/update-running.json
|
||||
sudo journalctl -u renewcms-update.service -n 30 --no-pager
|
||||
curl --retry 5 --retry-connrefused --retry-delay 2 -fsS http://127.0.0.1:8080/healthz
|
||||
```
|
||||
|
||||
Expect an active app service, result `kind: restart` with `outcome: succeeded`, the installed version and a new process in `update-running.json`, and health response `ok`. Check `/healthz` through your public HTTPS hostname too. A brief connection refusal during startup can be transient. The oneshot helper normally becomes inactive after success; the path unit stays active.
|
||||
|
||||
#### Install a future update
|
||||
|
||||
When a newer signed release exists, check for updates in Settings, read its notes and click Update. The site stays online while the files are downloaded, verified and backed up. Wait for Ready to install, then click Restart and confirm installation. Afterwards, check the version in Settings, public health, the helper journal and `update-result.json`: expect `kind: update` and `outcome: succeeded`.
|
||||
|
||||
On the latest release you can test only a plain restart. Test installation, forced rollback and hostile-file cases on an isolated Linux/systemd machine with its own data and service. The helper unit names are fixed, so setting up another instance on the same machine replaces that machine's existing helper configuration.
|
||||
|
||||
#### Troubleshooting
|
||||
|
||||
- **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.
|
||||
- **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.
|
||||
- **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.
|
||||
|
||||
#### Disable the helper
|
||||
|
||||
Use the same database directory you supplied when enabling it:
|
||||
|
||||
```sh
|
||||
sudo /opt/renewcms/renewcms disable-browser-updates \
|
||||
--service renewcms \
|
||||
--data-dir /var/lib/renewcms
|
||||
```
|
||||
|
||||
This stops and disables the path unit, removes both unit files and `update-helper.json`, and runs `systemctl daemon-reload`. The restart request, result, staged files and backups stay. `can_apply` becomes false: Settings shows “Not prepared” when an update is available, or “You're up to date” without Restart otherwise.
|
||||
|
||||
How it works: pressing Restart makes the app write `update-restart-request.json` in the data directory. The path unit notices it and starts the helper, which deletes the request, checks the staged files again, installs the update, restarts the service and waits up to 60 seconds for the site to answer `/healthz` and for the new process to write `update-running.json`. The helper writes its outcome to `update-result.json`; the Settings page reads it. The technical reason of a failure goes to the journal only (`journalctl -u renewcms-update`).
|
||||
|
||||
Files in the data directory:
|
||||
|
||||
| File | Written by | What |
|
||||
|------|------------|------|
|
||||
| `update-restart-request.json` | the app | The request: `kind` (`update` or `restart`), `tag` (updates only), `requested_at`, `requested_by`. The helper deletes it first. |
|
||||
| `update-result.json` | the helper | The outcome: `running`, `succeeded`, `rolled_back` or `failed`, with `kind`, `tag`, `from_version`, `started_at`, `finished_at`. It stays until the next download or restart. |
|
||||
| `update-helper.json` | `enable-browser-updates` | Marks browser updates as set up (`version`, `service`, `binary`, `data_dir`, `installed_at`). |
|
||||
| `update-running.json` | the server, at every start | `version`, `pid` and `started_at` of the running process. The helper uses it to tell a new process from an old one. |
|
||||
|
||||
What is supported and what is not:
|
||||
|
||||
- Linux with systemd only. Not Windows, macOS, Docker or other init systems: there the command refuses with a clear message and the Settings page keeps showing "Not prepared".
|
||||
- Before the swap the helper copies the staged files into a private temp directory, checks the signature and the SHA-256 on that copy and installs the copy. It refuses symbolic links under `updates/` and on the request file.
|
||||
- The previous binary is kept as `<name>.previous` next to the binary, and the update download keeps a database backup in `backups/`.
|
||||
- If the new version does not come up within 60 seconds, the helper puts `<name>.previous` back, restarts the service and records `rolled_back`. If even that fails the result is `failed` and the journal says so loudly.
|
||||
- A plain restart (no update waiting) restarts the service the same way and records `succeeded` or `failed`; no binary is replaced.
|
||||
- Only the owner can press Restart. The site is unavailable for about 10 seconds.
|
||||
|
||||
#### 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).
|
||||
|
||||
## 2. Lay out the server
|
||||
|
||||
The following is a suggested layout for Linux:
|
||||
|
||||
@@ -25,15 +25,16 @@ The visual spec of record for the back-office SPA and the transactional emails,
|
||||
| [Forgot password](screens/forgot-password.md) | `/register/reset/request` | 6 | `source/RenewCMS Screens Auth.dc.html` |
|
||||
| [Reset password](screens/reset-password.md) | `/register/reset/validate?c=CODE&email=EMAIL` | 7 | `source/RenewCMS Screens Auth.dc.html` |
|
||||
| [Boot](screens/boot.md) | `any route, first load` | 1 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [Home](screens/home.md) | `/home` | 4 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [Home](screens/home.md) | `/home` | 6 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [Articles](screens/articles.md) | `/article` | 14 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [New article](screens/new-article.md) | `modal from anywhere · /article/new` | 5 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [Editor](screens/editor.md) | `/article/:id/edit` | 22 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [Media](screens/media.md) | `/media` | 41 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [Media picker](screens/media-picker.md) | `/article/:id/edit` (dialog) | 13 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [Integration](screens/integration.md) | `/integration` | 2 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [Integration](screens/integration.md) | `/integration` | 8 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [API keys](screens/integration-api-keys.md) | `/integration/api-keys` | 12 | `source/RenewCMS Screens API keys.dc.html` |
|
||||
| [Users](screens/users.md) | `/users` | 17 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [Settings](screens/settings.md) | `/settings` | 1 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [Settings](screens/settings.md) | `/settings` | 25 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [Profile](screens/profile.md) | `/profile` | 13 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [Accept invite](screens/accept-invite.md) | `/invite/accept?c=CODE` | 9 | `source/RenewCMS Screens Auth.dc.html` |
|
||||
| [Global](screens/global.md) | `any route` | 4 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
@@ -41,6 +42,7 @@ The visual spec of record for the back-office SPA and the transactional emails,
|
||||
## Other boards
|
||||
|
||||
- `source/MediaFrame.dc.html`: the frame that draws the Media and Media picker states (the Back-office board imports it). Like `AppFrame.dc.html`, it holds the exact values.
|
||||
- `source/IntegrationPage.dc.html` and `source/ApiKeysPage.dc.html`: the page components for the Integration and API keys screens (imported by `AppFrame.dc.html`). They hold the exact values.
|
||||
- `source/RenewCMS Prototype.dc.html`: the clickable flows (first run, edit and publish, password reset, delete, session expiry mid-edit).
|
||||
- `source/RenewCMS Handoff.dc.html`: the handoff page the first markdown here was generated from. It predates the Users and Profile screens and the invitation email, so it does not list them. Those are written by hand from the Back-office board, `AppFrame.dc.html`, the Prototype and `emails/invitation.html`.
|
||||
- `source/RenewCMS Components Product.dc.html`: not regenerated for the new screens either. The matching component changes are in `components.md`, under "Added with the Users and Profile screens" and "Added with roles, invite actions and Settings".
|
||||
|
||||
@@ -30,7 +30,12 @@
|
||||
| PasswordStrengthHint | custom (in UFormField #help) | rules: { label, met }[], showErrors: boolean | none | none | Register, Reset, Accept invite |
|
||||
| ResultPanel | custom + UButton | tone: 'success'\|'error'\|'info', icon, title, description, actions: ButtonProps[] | none | default | Pending, Verify, Reset request, Reset, Accept invite, Register (403) |
|
||||
| CodeBlock | custom (shiki) + UButton | code: string, lang: string, label? | none | none | Integration |
|
||||
| EndpointCard | UCard, UBadge, UTabs | method: 'GET', path, description, examples: { fetch, curl, response } | none | none | Integration |
|
||||
| EndpointCard | UCollapsible, UBadge, UTable, UTabs | method: 'GET'\|'POST'\|'PATCH'\|'DELETE', path, description, access, keyAccess, body?, examples: { fetch, curl, response }, errors, sessionOnly? | none | none | Integration |
|
||||
| SectionIndex | custom nav (desktop), USelectMenu "Jump to" (mobile) | sections: { id, label }[], active: string | jump | none | Integration |
|
||||
| SessionOnlyGroup | UAlert-style note + list rows | routes: { method, path }[] | none | none | Integration |
|
||||
| ApiKeysTable | UTable, UBadge | keys: ApiKey[], showCreatedBy: boolean | revoke | none | API keys |
|
||||
| CreateApiKeyModal | UModal, UForm, UFormField, UInput | open: boolean | create | none | API keys |
|
||||
| ApiKeyReveal | UModal, UAlert, UButton | key: string | done | none | API keys |
|
||||
| ErrorView | custom + UButton | kind: 'not-found'\|'error' | retry | none | Not found, error boundary |
|
||||
| OfflineBanner | UBanner | none (reads useOnline) | none | none | DashboardShell |
|
||||
| AppBoot | USkeleton inside DashboardShell | none | none | none | First load of any verified route |
|
||||
@@ -47,7 +52,7 @@ These are the RenewCMS components, built from the primitives on the first page .
|
||||
|
||||
### AuthShell
|
||||
|
||||
One centered card for every public screen. The logo sits above the title, and the form or ResultPanel goes in the slot. Footer links and the theme select sit outside the card, so the card itself stays about one task.
|
||||
One centered card for every public screen. The logo sits above the title, and the form or ResultPanel goes in the slot. Footer links, the language chip and the theme select sit outside the card, so the card itself stays about one task.
|
||||
|
||||
Log in Welcome back. Log in to manage your articles.
|
||||
|
||||
@@ -55,7 +60,7 @@ default slot
|
||||
|
||||
Forgot password? System
|
||||
|
||||
Built from Custom layout component AuthShell.vue : a UPageCard variant="outline" inside a centered main , with AppLogo , and UColorModeSelect size="sm" in the footer. Forms inside it use UForm rather than UAuthForm , because every screen needs states (such as 403, 429 and an inline login during verification) that UAuthForm doesn't expose.
|
||||
Built from Custom layout component AuthShell.vue : a UPageCard variant="outline" inside a centered main , with AppLogo , and UColorModeSelect size="sm" in the footer, next to the language chip (see LanguageSwitcher). Forms inside it use UForm rather than UAuthForm , because every screen needs states (such as 403, 429 and an inline login during verification) that UAuthForm doesn't expose.
|
||||
|
||||
Props, slots Props title: string , description?: string . Slots default , notice (an alert above the title, for session expired or password changed), footer (links). No emits.
|
||||
|
||||
@@ -383,12 +388,13 @@ The Product components board was not regenerated for these. They are written fro
|
||||
|
||||
### UserMenu (changed)
|
||||
|
||||
The chip at the foot of the sidebar no longer logs out on click. It opens the account menu, which lists Profile, the theme choice and Log out.
|
||||
The chip at the foot of the sidebar no longer logs out on click. It opens the account menu, which lists Profile, the theme choice, the language choice and Log out.
|
||||
|
||||
- **Chip:** 40 px high, an initials avatar (26 px, sand `#d4c5b0` with ink text), the name, and a chevrons-up-down icon. `aria-haspopup="menu"`, `aria-expanded`, title "Account". While the menu is open, or while `/profile` is the current page, it takes `--rc-sand` with `#111111` text.
|
||||
- **Name:** the display name when there is one, otherwise the username. Initials come from the first letters of the first two words of the display name, uppercased. Without a display name they come from the username.
|
||||
- **Desktop menu:** a 224 px popover anchored above the chip on its left edge, with `--rc-shadow-pop`. Header: the name in semibold, the email below it in muted 12 px, a bottom border. Items are 32 px: Profile (circle-user), a separator, System, Light and Dark (14 px text, a check icon at the right edge on the current choice), a separator, Log out (log-out). The current page's item is highlighted with `--ui-bg-elevated`. The theme items are radio-style: choosing one applies at once and keeps the menu open. Nuxt UI: `type: 'checkbox'` items bound to `useColorMode().preference`.
|
||||
- **Mobile:** the account row in the navigation drawer opens a bottom sheet over an `--rc-overlay` scrim, with a grab handle. Header: 36 px avatar, name in 15 px semibold, email in muted text. Items are 48 px at 15 px text; the theme items keep the same order and separators.
|
||||
- **Desktop menu:** a 224 px popover anchored above the chip on its left edge, with `--rc-shadow-pop`. Header: the name in semibold, the email below it in muted 12 px, a bottom border. Items are 32 px: Profile (circle-user), a separator, a "Theme" section label, System, Light and Dark (14 px text, a check icon at the right edge on the current choice), a separator, a "Language" section label, English and Français (same row as the theme items, a check icon on the current one), a separator, Log out (log-out). Section labels are 11 px, weight 500, uppercase, letter-spacing .04em, `--ui-text-muted`, padded 6px 8px 2px. The current page's item is highlighted with `--ui-bg-elevated`. The theme items are radio-style: choosing one applies at once and keeps the menu open. Nuxt UI: `type: 'checkbox'` items bound to `useColorMode().preference`.
|
||||
- **Mobile:** the account row in the navigation drawer opens a bottom sheet over an `--rc-overlay` scrim, with a grab handle. Header: 36 px avatar, name in 15 px semibold, email in muted text. Items are 48 px at 15 px text; the theme and language items keep the same order, section labels (padded 8px 16px 2px) and separators.
|
||||
- **Language items:** a `menuitemradio` group named by the "Language" label. Each item is labelled with the language's own name (English, Français) and carries `lang="en"` / `lang="fr"`. Choosing one applies the language at once and keeps the menu open, like the theme items. See LanguageSwitcher.
|
||||
- **Keyboard:** Escape or a click outside closes it. Arrow keys move between items.
|
||||
- The board now draws the theme items, so the chip, menu and sheet need no visual exception. The board highlights Profile even on Home; the app highlights it only on `/profile`.
|
||||
|
||||
@@ -734,7 +740,16 @@ Three choices: System (the default), Light and Dark. The toggle at the top of th
|
||||
|
||||
Nuxt UI In the user menu: a UDropdownMenu group of three type: 'checkbox' items bound to useColorMode().preference . On auth screens: UColorModeSelect in the footer. Nuxt UI's UColorModeButton isn't used because it only toggles between light and dark and hides the system option. colorMode: true in the plugin handles storage and applying the .dark class before first paint.
|
||||
|
||||
ARIA Menu items use menuitemcheckbox , with aria-checked on the current choice. The segmented variant is a radiogroup named "Theme".
|
||||
ARIA Menu items use menuitemradio , with aria-checked on the current choice. The segmented variant is a radiogroup named "Theme".
|
||||
|
||||
### LanguageSwitcher
|
||||
|
||||
Two choices: English and Français. Each is always written in its own language, whatever the interface language. It appears in two places and never as a form select.
|
||||
|
||||
- **Account menu (signed in):** a "Language" section between the theme items and Log out. See UserMenu (changed).
|
||||
- **Auth footer (signed out):** a chip beside the System theme chip, in the footer outside the card. The chip is 28 px high on desktop and 44 px on mobile, 8 px side padding, 1 px `--ui-border-accented` border, `--ui-text-toned` text, a 14 px lucide `languages` icon, then the current language's own name. `aria-haspopup="menu"`, `aria-expanded`, `aria-label` "Language: English". While open it takes `--ui-bg-elevated`. The footer sits at the right with an 8 px gap between the two chips.
|
||||
- **Auth popover:** opens above the chip (bottom 36 px, right-aligned, 168 px wide), `--ui-bg`, 1 px `--ui-border`, `--rc-shadow-pop`, 4 px padding, `role="menu"` named "Language". Rows are 32 px (44 px on mobile), 14 px text, `menuitemradio` with `lang`, a 16 px check icon at the right edge on the current one. Choosing a row applies the language and closes the popover; Escape or an outside click closes it without changing anything.
|
||||
- The choice persists across reloads and applies to every screen at once.
|
||||
|
||||
## Added with roles, invite actions and Settings
|
||||
|
||||
@@ -784,3 +799,18 @@ Exact values live in `source/MediaFrame.dc.html`. Copy and states are in [media]
|
||||
| MediaPicker | UTabs inside ImageUploader | articleId | picked(item, alt) | Editor |
|
||||
|
||||
ImageUploader (changed): it gains the Upload and Library tabs and the "Already in your library" card. The remove-image confirm becomes neutral and only detaches the image from the article.
|
||||
|
||||
## Added with Updates
|
||||
|
||||
Exact values live in `source/AppFrame.dc.html` (the Settings and Home states). Copy and states are in [settings](screens/settings.md) and [home](screens/home.md).
|
||||
|
||||
| Component | Nuxt UI base | Props | Emits | Used in |
|
||||
|---|---|---|---|---|
|
||||
| UpdatesCard | custom card, UProgress, UButton, UCollapsible | status: UpdateStatus, role | check, update, restart, copy-command | Settings |
|
||||
| UpdateStatusBlock | custom (polite live region) | tone, icon, title, text, meta, pendingTag?, action? (in-block Restart, Ready only) | none | UpdatesCard |
|
||||
| UpdateProgress | UProgress | label, text, value or indeterminate | none | UpdatesCard |
|
||||
| ReleaseNotes | UCollapsible | version, date, items | none | UpdatesCard |
|
||||
| ServerCommand | UButton, code block | line | copy | UpdatesCard (Not prepared) |
|
||||
| RestartOverlay | custom full-page `role="status"` | title, text, startedAt, slow | reload | App shell |
|
||||
| UpdateBanner | UAlert | state: 'available'\|'ready' | go-to-settings, dismiss | Home (owner) |
|
||||
| UpdatePill | UBadge | none | none | DashboardShell Settings item (dot on mobile) |
|
||||
@@ -11,14 +11,15 @@ A global `router.beforeEach` guard reads `meta.auth`. On the first navigation it
|
||||
| `/register/validate` | AuthShell | public | VerifyPage | POST /v1/auth/verify (+ POST /login inline on 401) |
|
||||
| `/register/reset/request` | AuthShell | public | ResetRequestPage | POST /v1/auth/password-reset |
|
||||
| `/register/reset/validate` | AuthShell | public | ResetConfirmPage | POST /v1/auth/password-reset/confirm |
|
||||
| `/home` | DashboardShell | verified | HomePage | GET /v1/article/ |
|
||||
| `/home` | DashboardShell | verified | HomePage | GET /v1/article/ · GET /v1/system/update (owner, for the banner) |
|
||||
| `/article` | DashboardShell | verified | ArticlesPage | GET /v1/article/ · PATCH /{id}/publish\|unpublish · DELETE /{id} |
|
||||
| `/article/new` | DashboardShell | verified | ArticlesPage + NewArticleModal | POST /v1/article/ |
|
||||
| `/article/:id/edit` | DashboardShell | verified | EditorPage | GET /{id} · PATCH /{id} · PATCH /{id}/publish\|unpublish · GET /v1/media/ · POST /v1/media/ · DELETE /{id} |
|
||||
| `/media` | DashboardShell | verified | MediaPage | GET /v1/media/ · POST /v1/media/ · PATCH /v1/media/{id} · DELETE /v1/media/{id} · POST /v1/media/merge · GET /v1/media/{id}/usage |
|
||||
| `/integration` | DashboardShell | verified | IntegrationPage | none |
|
||||
| `/integration/api-keys` | DashboardShell | verified | ApiKeysPage + CreateApiKeyModal | GET /v1/api-key · POST /v1/api-key · DELETE /v1/api-key/{id} |
|
||||
| `/users` | DashboardShell | verified | UsersPage + InviteUserModal | GET /v1/user/ · POST /v1/user/invite · DELETE /v1/user/invite/:id · POST /v1/user/invite/:id/renew |
|
||||
| `/settings` | DashboardShell | verified | SettingsPage | GET /v1/settings |
|
||||
| `/settings` | DashboardShell | verified | SettingsPage | GET /v1/settings · GET /v1/system/update · POST /v1/system/update/check · POST /v1/system/update/download · POST /v1/system/update/restart |
|
||||
| `/profile` | DashboardShell | verified | ProfilePage | GET /v1/auth/me · PATCH /v1/user/me · POST /v1/auth/password-reset |
|
||||
| `/invite/accept` | AuthShell | public | AcceptInvitePage | GET /v1/auth/invite?c=* · POST /v1/auth/invite/accept* |
|
||||
| `/:pathMatch(.*)*` | either | any | NotFoundPage | none |
|
||||
|
||||
@@ -40,3 +40,17 @@ The greeting reads "Good morning, {name}", where the name is the display name wh
|
||||
- Breadcrumbs: Home (mobile title "Home")
|
||||
- Subtitle: "Here's where things stand on your site."
|
||||
- Error state for the list request
|
||||
|
||||
### Update available (owner)
|
||||
|
||||
**Trigger:** The owner only. A quiet banner above the content, and an "Update" pill on the Settings sidebar item (a dot on the menu icon on mobile, read as "Update available"). Dismissing hides the banner until the next version; the pill stays. Admins see neither.
|
||||
|
||||
- Breadcrumbs: Home (mobile title "Home")
|
||||
- Subtitle: "Here's where things stand on your site."
|
||||
- Banner: `role="region"` labelled "Update available", info tone, `circle-arrow-up` icon, title "Version 2.3.0 is available", text "Update it from Settings. It takes about 2 minutes and the site stays online.", button "Go to Settings", and a dismiss button
|
||||
|
||||
### Update ready to install (owner)
|
||||
|
||||
**Trigger:** The download is checked. The same banner changes its copy, and a dismiss comes back on the next visit because the update is waiting.
|
||||
|
||||
- Banner: success tone, `circle-check` icon, title "Version 2.3.0 is ready to install", text "Restart from Settings to finish. The site is unavailable for about 10 seconds.", button "Go to Settings"
|
||||
@@ -0,0 +1,58 @@
|
||||
# Integration: API keys
|
||||
|
||||
Route: `/integration/api-keys`. Component: `ApiKeysPage.dc.html`, mounted by `AppFrame`.
|
||||
|
||||
- **Visual reference:** `source/RenewCMS Screens API keys.dc.html`, group "API keys", drawn by `source/ApiKeysPage.dc.html` (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
|
||||
|
||||
## API
|
||||
`POST /v1/api-key` · `GET /v1/api-key` · `DELETE /v1/api-key/{id}`. Access: Session only. An API key cannot manage keys; with a key these routes answer 403 "This action needs a real session."
|
||||
- `POST /v1/api-key` body: `name` (string, required, max 60), `expires_at` (RFC3339 string, optional, in the future). A past date answers 400 "The expiry must be a date in the future."
|
||||
- `DELETE /v1/api-key/{id}`: unknown id answers 404 "API key not found".
|
||||
|
||||
## Placement
|
||||
Under Integration, as a sub-page linked from the Authentication section ("Manage API keys") and the sidebar item. Keys exist to call the API and admins can create them; Settings is owner-only today. The mobile top bar has a back arrow that returns to Integration.
|
||||
|
||||
## Content
|
||||
- Columns: Name, Key (prefix, mono), Status (active, expired, revoked), Created by (owners only), Created, Last used, Expires, Revoke. Owners see all keys; admins see their own.
|
||||
- Create key modal: Name (required, up to 60, counter), Expiry date (optional, must be in the future). Errors: "Enter a name." / "Use 60 characters or fewer." / "Choose a date in the future."
|
||||
- The Expiry field is a native date input. The displayed format follows the browser's locale, so there is no custom format. The board draws one example date only.
|
||||
- One-time reveal: warning "You won't be able to see this key again.", monospace key, Copy / Copied, "Closing this window discards the key from the screen. Copy it first." Button "Done".
|
||||
- Revoke: "Revoke this key?" / ""Nightly media import" (rcms_Mq7b…) will stop working right away. Requests that use it answer 401. This can't be undone." Buttons "Keep key", "Revoke key". Toast "Key revoked".
|
||||
- Empty: "No API keys yet" / "Create a key to call the API from a script or service." Error: "Couldn't load your API keys" / "Check your connection and try again."
|
||||
- Note: "Resetting a user's password revokes all of their keys."
|
||||
|
||||
## Mobile: pinned Create key
|
||||
On mobile the "Create key" button is pinned to the bottom of the viewport (44 px high, full width, on a bar with a top border). It shows in Owner list, Admin own keys only, Loading, Empty, Error and Revoked, and is hidden behind every modal state. In Empty it replaces the inline button. The content has bottom padding so nothing sits under the bar, and the toast sits above it. Desktop keeps "Create key" in the page header (and in the Empty card).
|
||||
|
||||
## States
|
||||
|
||||
Names are matched exactly by the visual-check script.
|
||||
|
||||
### Owner: list
|
||||
|
||||
### Admin: own keys only
|
||||
|
||||
### Loading
|
||||
the list request is in flight. Skeleton rows appear only after 150 ms.
|
||||
|
||||
### Empty
|
||||
|
||||
### Error
|
||||
a 500 or network failure on the list request. If a key is created while this state is showing, the list reloads, the new key appears and the error alert is cleared.
|
||||
|
||||
### Create key
|
||||
|
||||
### Create key: validation
|
||||
|
||||
### Create key: name too long
|
||||
|
||||
### One-time reveal
|
||||
|
||||
### One-time reveal: copied
|
||||
|
||||
### Revoke: confirm
|
||||
|
||||
### Revoked
|
||||
|
||||
## Component inventory (Nuxt UI v4)
|
||||
`UTable`, `UBadge`, `UModal` with `UForm`/`UFormField`/`UInput` (type date), `UAlert` color warning, `UButton`, `useClipboard`.
|
||||
@@ -1,22 +1,82 @@
|
||||
# Connect your website
|
||||
# Integration (API reference)
|
||||
|
||||
- **Route:** `/integration`
|
||||
- **API:** none (static)
|
||||
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Integration" (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
|
||||
Route: `/integration`. Component: `IntegrationPage.dc.html`, mounted by `AppFrame`. The API keys sub-page is in `screens/integration-api-keys.md`.
|
||||
|
||||
Written for a developer. The base URL is window.location.origin.
|
||||
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Integration", drawn by `source/IntegrationPage.dc.html` (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
|
||||
|
||||
## Navigation decision
|
||||
Sticky section index on the right (desktop), "Jump to" select (mobile). A reference is read in one scroll and searched with the browser, so tabs would hide content and break find-in-page and deep links; the index keeps one page with anchors and shows position.
|
||||
|
||||
## Page copy
|
||||
- Header: breadcrumb "Integration", title "API reference", description "Everything a developer needs to build on RenewCMS."
|
||||
- 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", 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}`.
|
||||
- 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." CodeBlock 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 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.""
|
||||
- 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. 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."
|
||||
|
||||
## EndpointCard states
|
||||
- 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 with one CodeBlock and 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.
|
||||
- Chips: access "Public", "Verified user", "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.
|
||||
|
||||
## States
|
||||
Desktop 1440×900, mobile 390×844, light and dark. Names are matched exactly by the visual-check script.
|
||||
|
||||
### Default
|
||||
### 1. Default
|
||||
|
||||
**Trigger:** Opened from the sidebar or the Home card.
|
||||
### 2. Group scrolled, one card expanded
|
||||
|
||||
- Breadcrumbs: Integration (mobile title "Integration")
|
||||
### 3a. Copied: base URL
|
||||
|
||||
### Copied
|
||||
### 3b. Copied: CodeBlock
|
||||
|
||||
**Trigger:** The base URL was copied. The button reads "Copied" for 2 s and this is announced.
|
||||
### 4. Authentication
|
||||
|
||||
- Breadcrumbs: Integration (mobile title "Integration")
|
||||
- copied: true
|
||||
### 5. Session only
|
||||
|
||||
### 6. Errors
|
||||
|
||||
### 7. Navigation
|
||||
|
||||
## Error messages
|
||||
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."
|
||||
- 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."
|
||||
- 404: "Article not found" / "Image not found" / "Invite not found" / "API key not found"
|
||||
- 429: "Too many requests. Please try again later." A per-key limit also sends `Retry-After`.
|
||||
- 500: "Internal server error"
|
||||
- 409, only as examples under their endpoints: `POST /v1/user/invite` "This address already has an account."; `POST /v1/media/merge` "Some of the images to merge changed. Refresh and try again." There is no 409 or 422 row in the table.
|
||||
- 413 and 415 on `POST /v1/media/` keep their earlier plain captions; no real message is known.
|
||||
|
||||
## Request bodies
|
||||
- `POST /v1/article/`: `title` (string, required, 3 to 200 characters), `body` (string, required, max 10000).
|
||||
- `PATCH /v1/article/{id}`: `body` (string, required, max 10000).
|
||||
- `PATCH /v1/media/{id}` (rename): `filename` (string, required).
|
||||
- `POST /v1/media/merge`: `keep_id` (number, required, > 0), `merge_ids` (number[], required, at least 1, each > 0).
|
||||
- `POST /v1/media/`: multipart/form-data, 1 file field (shown as "multipart/form-data, 1 file field").
|
||||
- `PATCH /v1/user/me`: `display_name` (string, required, max 60 characters).
|
||||
- `POST /v1/user/invite`: `email` (string, required, valid email).
|
||||
- `POST /v1/system/update/restart`: optional body `{ "kind": "update" | "restart" }`.
|
||||
|
||||
## Component inventory and Nuxt UI v4
|
||||
- EndpointCard (extended): `UCollapsible` (trigger is a button with aria-expanded), `UBadge` (method, chips, status), `UTable` (body fields), `UTabs` (fetch, curl, Response), CodeBlock.
|
||||
- SectionIndex (new): custom `<nav>` of anchor buttons with `aria-current`; sticky, scroll-spy. Mobile: `USelectMenu` labelled "Jump to".
|
||||
- SessionOnlyGroup (new): `UAlert`-style info note plus list rows; no new colour.
|
||||
- ErrorTable: `UTable`. Info notes: existing note style (or `UAlert` variant `naked`).
|
||||
|
||||
## Assumptions to confirm
|
||||
- Paths not in the brief: `/v1/settings`, `/v1/system/update/*`, `POST /v1/auth/register|verify|logout`.
|
||||
- [to confirm] The multipart field name on `POST /v1/media/` is written as `file` as a placeholder.
|
||||
- Response field names in the samples (for example `articlesUpdated`, `display_name` in the profile response) are illustrative.
|
||||
- Code samples use a simple keyword and string colouring.
|
||||
|
||||
## Tokens
|
||||
No new tokens. Foundations check: colours, radius (0) and spacing come from existing `--ui-*` and `--rc-*` values; every control has a 2 px primary focus ring; index, select and cards are keyboard operable. Open question: the board hard-codes a few pixel sizes, as the other screens do.
|
||||
@@ -48,8 +48,12 @@ Desktop: a 224 px popover above the chip, aligned to its left. Mobile: the accou
|
||||
| Header | The name in semibold (display name, or the username), and the email in muted 12 px (14 px on mobile, with a 36 px initials avatar beside them) |
|
||||
| Item | Profile (circle-user icon), highlighted while on `/profile` |
|
||||
| Separator | |
|
||||
| Label | "Theme": 11 px, weight 500, uppercase, letter-spacing .04em, muted |
|
||||
| Items | System, Light, Dark: a radio-style group, the current choice carries a check icon at the right edge; choosing one applies the theme at once and keeps the menu open |
|
||||
| Separator | |
|
||||
| Label | "Language", styled like "Theme" |
|
||||
| Items | English, Français (each in its own language, with `lang`): a radio-style group with a check on the current one; choosing one applies the language at once and keeps the menu open |
|
||||
| Separator | |
|
||||
| Item | Log out (log-out icon) |
|
||||
|
||||
Avatar initials come from the first letters of the first two words of the display name, uppercased ("Marta Alves" gives MA). Without a display name they come from the username.
|
||||
@@ -64,7 +68,7 @@ The board's menu now carries System, Light and Dark, matching the shipped UserMe
|
||||
|
||||
- Breadcrumbs: Home (mobile title "Home")
|
||||
- Page behind the menu: Home, default
|
||||
- Menu open, as described above, with the System, Light and Dark group between Profile and Log out. The board shows Light checked
|
||||
- Menu open, as described above, with the Theme group (System, Light, Dark) and the Language group (English, Français) between Profile and Log out. The board shows Light and English checked
|
||||
|
||||
### Loading
|
||||
|
||||
|
||||
+113
-21
@@ -1,35 +1,127 @@
|
||||
# Settings
|
||||
|
||||
- **Route:** `/settings`
|
||||
- **API:** GET /v1/settings (not drawn, see the notes)
|
||||
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Settings" (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
|
||||
- **API:** GET /v1/settings (version) · GET /v1/system/update · POST /v1/system/update/check · POST /v1/system/update/download · POST /v1/system/update/restart
|
||||
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Settings", drawn by `source/AppFrame.dc.html` (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
|
||||
|
||||
Opened from the sidebar (Settings, settings icon, after Integration) and from the mobile drawer. Every verified user sees it, owner and admins alike. For now it holds a single section, Version. Nothing on it can be edited.
|
||||
Opened from the sidebar (Settings, settings icon, after Integration) and from the mobile drawer. Every verified user sees it. It holds two sections: Version (everyone) and Updates (the owner has the buttons, admins read the status).
|
||||
|
||||
The Updates card lets a non-technical owner update the site without a terminal. **Update** downloads the new version and checks it, and changes nothing. **Restart** installs it and restarts the site (about 10 seconds). "Restart later" is simply closing the dialog or leaving the page; the update waits. A plain **Restart** appears only when no update is waiting. The state lives on the server, so any owner on any device sees the same card, and the buttons are disabled while any step runs.
|
||||
|
||||
Out of scope: choosing versions, downgrades, automatic updates, update history.
|
||||
|
||||
## The page
|
||||
|
||||
Title "Settings" and the subtitle "Workspace information.", 720 px wide at most. Page padding 32 px on desktop and `20px 16px 88px` on mobile, 20 px between the header and the card.
|
||||
Title "Settings", subtitle "Workspace information.", 720 px at most, 20 px between sections. Page padding 32 px on desktop and `20px 16px 88px` on mobile.
|
||||
|
||||
One card (`--ui-bg`, 1 px `--ui-border`, 20 px padding on desktop and 16 px on mobile), a single row with the label on the left and the value on the right, 16 px apart:
|
||||
**Version card** (unchanged): label "Version" and the running build's version in IBM Plex Mono 14 px, shown exactly as the server reports it (for example `v2.2.0-beta`).
|
||||
|
||||
**Updates card**, under it: `--ui-bg`, 1 px `--ui-border`, 20 px padding (16 px on mobile), 16 px gap. A region labelled by its heading "Updates" (`id="updates-h"`, `tabindex="-1"`, focus ring `2px solid var(--ui-primary)` with 4 px offset when focus is moved there). Inside:
|
||||
|
||||
| Part | Content |
|
||||
|---|---|
|
||||
| Label | "Version", 15 px semibold, `--ui-text-highlighted` |
|
||||
| Value | The running build's version in IBM Plex Mono 14 px, `--ui-text-toned`. The board shows `v2.2.0-beta`. Shown exactly as the server reports it, so the SPA adds no `v` prefix. |
|
||||
| Status block | A polite live region (`aria-live="polite"`): 14 px padding, 12 px gap, an 18 px icon, a semibold title, the text, and a muted `meta` line. Background and icon color follow the tone: neutral `--ui-bg-muted`, success, info, warning, error (`--rc-<tone>-soft` fill, `--ui-<tone>` icon). The title row is a flex row with an 8 px gap that wraps. In "Ready to install" it carries a **Pending tag** after the title and the block holds the **Restart** button (see below). |
|
||||
| Pending tag | Only in "Ready to install", right after the title: 20 px high, 0 6 px padding, IBM Plex Mono 11 px medium, `--ui-bg` fill, `--ui-warning` text and 1 px `--ui-warning` border, square corners, text "Pending". |
|
||||
| In-block button | Only in "Ready to install", "Restart: confirm" and "Restart: request failed": the primary Restart button sits inside the status block, under the `meta` line, after 8 px of extra top padding, left-aligned (content width, 14 px side padding, 32 px high, 44 px on mobile, not stretched). The buttons row under the block is not drawn in these states. The hint stays under the card. |
|
||||
| Progress | A `progressbar` with a value (`aria-valuenow`) while downloading, labelled for example "Downloading version 2.3.0", with the text `42% · 11 of 26 MB`. Indeterminate while verifying (35 % wide moving bar), labelled "Checking the download", text "Almost there". Announced at 25 % steps and when the step changes, never on every tick. |
|
||||
| Release notes | A button "What's new in 2.3.0" with `aria-expanded` and a chevron, collapsed by default. Open: "Released 24 Sep 2026" and a plain-text list. |
|
||||
| Server command | Only in the "Not prepared" state: "For whoever manages the server", a one-line `code` block, a Copy button (reads "Copied" with a check for 2 s, announced), and the note "They run this once on the server. After that, Update and Restart appear here." The command shown is `renewcms enable-browser-updates` and is subject to the real one. |
|
||||
| Buttons | 32 px high (44 px on mobile, stacked full width), 14 px side padding. One primary at most. Disabled buttons use 40 % opacity. |
|
||||
| Hint | 12 px muted line under the buttons. |
|
||||
| Link | Underlined, with an `arrow-up-right`: "How to update" or "Read the release notes". |
|
||||
|
||||
Buttons used: **Check for updates** (`refresh-cw`, secondary), **Update** (`download`, primary), **Restart** (`power`, primary and inside the status block when an update is ready, otherwise secondary in the buttons row), **Try again** (`rotate-cw`, primary), and the disabled "Checking…" and "Updating…" (`loader-circle`). Copy such as "Version 2.3.0" names the newer release. Decision for the spec: show the release tag without its leading `v` ("Version 2.3.0-beta" for tag `v2.3.0-beta`), while the Version card keeps the running build exactly as the server reports it.
|
||||
|
||||
## Copy
|
||||
|
||||
| Where | Copy |
|
||||
|---|---|
|
||||
| Up to date | `circle-check`, success: "You're up to date" / "You have the latest version of RenewCMS." / "Last checked today at 09:41"; buttons "Check for updates" and "Restart"; hint "Restart takes about 10 seconds. Your site is unavailable while it restarts." |
|
||||
| Checking | `loader-circle`: "Checking for updates…" / "This usually takes a few seconds."; "Checking…" disabled |
|
||||
| Check failed | `wifi-off`, warning: "Couldn't check for updates" / "RenewCMS couldn't reach the update server. Check your connection and try again. Your site isn't affected." / "Last checked yesterday at 18:12"; "Try again" (primary) and "Restart" |
|
||||
| Available | `circle-arrow-up`, info: "Version 2.3.0 is available" / "You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart."; "Update"; hint "Takes about 2 minutes. Your site stays online." |
|
||||
| Downloading | `download`, info: "Downloading version 2.3.0…" / "You can leave this page. The download continues and your site stays online."; "Updating…" disabled |
|
||||
| Verifying | `shield-check`, info: "Checking the download…" / "Making sure the file is complete and safe to install. This takes a few seconds." |
|
||||
| Ready | `clock`, warning, with the "Pending" tag after the title: "Version 2.3.0 is ready to install" / "The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds." / "Nothing has changed yet."; "Restart" (primary, inside the block); hint "Not now? Leave this page. The update waits here, and the banner on Home reminds you." |
|
||||
| Done | "You're on version 2.3.0" / "The update is installed and your site is running again." / "Updated today at 09:52"; link "Read the release notes"; toast `circle-check` "Update installed" / "RenewCMS is now on version 2.3.0." |
|
||||
| Rolled back | `triangle-alert`, warning: "The update didn't install" / "RenewCMS put the previous version back, so your site is running as before. Nothing was lost." / "What to do next: try again in a few minutes. If it fails again, ask whoever manages your server to check the update."; "Try again"; toast (error, stays) `circle-x` "The update didn't install" / "Your site is back on v2.2.0-beta." |
|
||||
| Download failed | `circle-x`, error: "The download didn't finish" / "The connection dropped before the file was complete. Nothing was changed and your site is running as before."; "Try again" |
|
||||
| Not trusted | `triangle-alert`, warning: "We didn't use this update" / "The file didn't pass our safety check, so it was not installed. Nothing was changed. Try downloading it again. If this keeps happening, contact RenewCMS support." Technical detail goes to the server log. |
|
||||
| Rate limited | `info`: "Too many tries" / "Wait a moment before trying again."; button "Try again in 0:42" counting down Retry-After |
|
||||
| Not prepared | `info`: "Version 2.3.0 is available" / "This site can't update itself from the browser yet. Whoever manages your server can set it up once, or update RenewCMS for you." and a link "How to update". No buttons, not even Restart. |
|
||||
| Admin | "Version 2.3.0 is available" / "You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site." No buttons. Up to date reads "You're up to date" and "Only the owner can update or restart the site." |
|
||||
|
||||
## Dialogs and overlays
|
||||
|
||||
Both dialogs use the ConfirmDialog behaviour: focus moves to the first button, Escape and the cancel button close it, and focus returns to the button that opened it. The confirm button is neutral, not red, because nothing is lost.
|
||||
|
||||
| Dialog | Title | Description | Cancel / Confirm |
|
||||
|---|---|---|---|
|
||||
| Install | "Restart to finish the update?" | "RenewCMS will install version 2.3.0 and restart. Your site will be unavailable for about 10 seconds. This page reloads on its own when the site is back. Save anything you're editing first." | "Restart later" / "Restart now" |
|
||||
| Plain restart | "Restart the site?" | "Your site will be unavailable for about 10 seconds. This page reloads on its own when the site is back. Save anything you're editing first." | "Cancel" / "Restart site" |
|
||||
|
||||
Failure inside the install dialog: "Couldn't start the restart. Nothing was changed and your site is still running. Try again in a moment."
|
||||
|
||||
Restart overlay: a full-page `role="status"` live region (`--ui-bg-muted`, 440 px card) that survives the server going away, with a moving bar. Copy: "Installing version 2.3.0" / "Your site is restarting with the new version. This takes about 10 seconds. This page reloads on its own when the site is back." / "Started at 09:51". Announced once as "Installing version 2.3.0. Your site is restarting." After 60 seconds with no answer: "Still restarting" / "This is taking longer than usual. Keep this page open. It reloads on its own when the site is back, or you can reload it now." / "Started at 09:51 · 1 minute ago" and a "Reload page" button. Plain restart: "Restarting your site" / "This takes about 10 seconds. This page reloads on its own when the site is back." After the reload: focus lands on the "Updates" heading and a toast `circle-check` "Site restarted" / "Your site is running again."
|
||||
|
||||
## Elsewhere
|
||||
|
||||
For the owner only: an **Update** pill on the Settings sidebar item, and a dot on the menu icon on mobile (read as "Update available"). Admins see neither. The Home banner is described in [home](home.md).
|
||||
|
||||
## Status to copy
|
||||
|
||||
| Status | Where | Copy |
|
||||
|---|---|---|
|
||||
| 200 | Check, up to date | "You're up to date" and the last-checked line |
|
||||
| 200 | Check, newer version | "Version 2.3.0 is available" and its text |
|
||||
| 202 | Update, Restart | Accepted. The card switches to progress, announced as "Downloading version 2.3.0, 25 percent". |
|
||||
| 200 | Update finished | "Version 2.3.0 is ready to install" |
|
||||
| 200 | After restart | Toast "Update installed" or "Site restarted" |
|
||||
| 400 | Update, nothing to install | Info toast "Nothing to update" / "You already have the latest version." The card refreshes. |
|
||||
| 401 | any | Global: /login?redirect=/settings&reason=expired. No local copy. |
|
||||
| 403 | any button, not the owner | Error toast "Only the owner can do this" / "Ask the owner of this site to update RenewCMS." The card reloads as the admin view. An unverified account is handled globally. |
|
||||
| 409 | Update, Restart | Already running: info toast "An update is already running" / "Another owner started it. Progress shows here." Not prepared: the card shows the "Not prepared" state. |
|
||||
| 422 | Update, file not trusted | The "Not trusted" card above |
|
||||
| 429 | Check, Update | The rate-limited card above |
|
||||
| 500 / network | Check | "Couldn't check for updates" with "Try again" |
|
||||
| 500 / network | Update | "The download didn't finish" with "Try again" |
|
||||
| 500 / network | Restart dialog | "Couldn't start the restart. Nothing was changed and your site is still running. Try again in a moment." |
|
||||
| Site back, old version | after restart | The rolled-back card above |
|
||||
| No answer, 60 s | restart overlay | "Still restarting" |
|
||||
| Offline | whole page | Existing banner. Check, Update and Restart are disabled. During a restart the overlay keeps polling and ignores the offline state. |
|
||||
|
||||
## Behaviour notes
|
||||
|
||||
- The page asks for `GET /v1/system/update` on open and, when a step is running, polls it every second. The server holds the state (idle, downloading, verifying, ready, restarting, succeeded, failed), so another device or owner sees the same card.
|
||||
- A check runs on the first open after 24 hours and when "Check for updates" is pressed.
|
||||
- Update takes no confirmation because it changes nothing. Restart always asks.
|
||||
|
||||
## States
|
||||
|
||||
### Default
|
||||
|
||||
**Trigger:** Opened from the sidebar.
|
||||
|
||||
- Breadcrumbs: Settings (mobile title "Settings")
|
||||
- Section: Version, `v2.2.0-beta`
|
||||
|
||||
The board draws no loading or error state. Decide them in the spec (see the notes).
|
||||
|
||||
## Notes for implementation
|
||||
|
||||
- The board's API line says "none (static)", but the version lives in the Go binary (`main.version`, set with `-ldflags -X`, `dev` when unset), so the SPA has to ask for it. The recommendation is `GET /v1/settings` returning `{ "version": "..." }` inside the verified group, so later settings have a home. It is read once at startup and never from the environment at request time.
|
||||
- Not drawn: loading (the recommendation is a skeleton for the value only, after 150 ms, like the other pages), and a failed request (an inline error in the card with "Try again", using the global copy "Couldn't reach RenewCMS. Check your connection and try again.").
|
||||
- Keep the page free of actions, toggles and links until a later slice adds a real setting.
|
||||
| State | Trigger and behaviour |
|
||||
|---|---|
|
||||
| Up to date | Opened with no newer version. Restart is available but not emphasised. |
|
||||
| Checking | Check for updates pressed, or the first open after 24 hours. Announced as "Checking for updates". Buttons are disabled. |
|
||||
| Check failed | Offline, or the update server didn't answer (500, network). The last known result is kept. |
|
||||
| Update available | A newer version exists. Release notes are collapsed. Update is the one primary button. |
|
||||
| Update available, notes open | "What's new in 2.3.0" expanded. It is a button with aria-expanded, and the list is plain text. |
|
||||
| Downloading | Update pressed (202). Progress polls every second. Announced as "Downloading, 25 percent" and so on, never every tick. |
|
||||
| Verifying | The download finished. No percentage, so the bar is indeterminate. Announced as "Checking the download". |
|
||||
| Ready to install | The file passed its checks. The card turns warning (orange) with a "Pending" tag and a `clock` icon, and Restart, the primary action, sits inside it. "Restart later" is closing the dialog or leaving the page. |
|
||||
| Restart: confirm | Restart pressed. The card behind the dialog keeps the Ready look. Same dialog behaviour as the delete confirm: focus moves to the first button, Escape and "Restart later" close it, and focus returns to Restart. The confirm button is neutral, not red, because nothing is lost. |
|
||||
| Restart: request failed | 500 or network failure before the restart began. The site is still running. The card behind the dialog keeps the Ready look. |
|
||||
| Restarting to install | Full-page overlay, so it survives the server going away. The page polls until the site answers, then reloads. It is a live region announced once as "Installing version 2.3.0. Your site is restarting." |
|
||||
| Restarting, taking longer | No answer after 60 seconds. The copy changes and a manual reload appears. The overlay stays until the site is back. |
|
||||
| Update done | The page reloaded on the new version. Focus lands on the "Updates" heading (ring shown), the toast is announced, and the version updates. |
|
||||
| Update failed, rolled back | The site came back on v2.2.0-beta. The error toast stays until dismissed and the card keeps the explanation. |
|
||||
| Download failed | A 500, or the connection dropped. Focus moves to the card heading. Try again restarts the download. |
|
||||
| Verification failed | The downloaded file isn't trusted. The tone is a warning, and the file is thrown away. Technical detail goes to the server log, not the screen. |
|
||||
| Too many requests (429) | Retry-After counted down in the button. It re-enables at zero. |
|
||||
| Not prepared | The server can't update from the browser. No buttons, not even Restart. The command is for the person who runs the server and is a single line. The placeholder command is subject to the real one. |
|
||||
| Not prepared: command copied | Copy pressed. The button reads "Copied" for 2 s and it is announced. |
|
||||
| Plain restart: confirm | Restart with no update waiting. Nothing is installed. |
|
||||
| Plain restart: restarting | Same overlay as the update restart with shorter copy. |
|
||||
| Plain restart: done | The page reloaded. Focus lands on the "Updates" heading. |
|
||||
| Admin view | Admins see the version and the note, with no buttons. Up to date: "You're up to date" and "Only the owner can update or restart the site." No Home banner or Settings pill. |
|
||||
| Role changed (403) | An owner was changed to admin while the page was open and pressed a button. The card reloads in the admin view. |
|
||||
| Update already running (409) | Another owner started it. The card switches to that run's progress. |
|
||||
@@ -0,0 +1,94 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<script src="./support.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<x-dc>
|
||||
<div style="flex:1;min-height:0;overflow:hidden;background:var(--ui-bg-muted);color:var(--ui-text);font-family:'IBM Plex Sans',sans-serif;font-size:13px;line-height:20px;padding:{{ pad }};position:relative;display:flex;flex-direction:column;gap:16px">
|
||||
<div style="display:flex;align-items:flex-end;gap:16px;flex-wrap:wrap">
|
||||
<div style="flex:1;min-width:200px;display:flex;flex-direction:column;gap:4px"><span style="color:var(--ui-text-muted)">Integration › API keys</span><span style="font:600 {{ h1 }} 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">API keys</span><span style="color:var(--ui-text-muted);text-wrap:pretty">{{ sub }}</span></div>
|
||||
<sc-if value="{{ desk }}"><span style="height:36px;padding:0 14px;display:flex;align-items:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500">Create key</span></sc-if>
|
||||
</div>
|
||||
<sc-if value="{{ err }}"><div role="alert" style="display:flex;gap:10px;padding:12px 14px;background:var(--rc-error-soft);color:var(--ui-error)"><span style="flex:1"><strong>Couldn't load your API keys</strong><br>Check your connection and try again.</span><span style="font-weight:500;color:var(--ui-text-highlighted)">Try again</span></div></sc-if>
|
||||
<sc-if value="{{ empty }}"><div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:48px 24px;display:flex;flex-direction:column;align-items:center;gap:10px;text-align:center"><span style="font:600 16px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">No API keys yet</span><span style="color:var(--ui-text-toned);max-width:360px;text-wrap:pretty">Create a key to call the API from a script or service.</span><sc-if value="{{ desk }}"><span style="height:36px;padding:0 14px;display:flex;align-items:center;background:var(--ui-primary);color:var(--ui-bg);font-weight:500">Create key</span></sc-if></div></sc-if>
|
||||
<sc-if value="{{ showList }}">
|
||||
<sc-if value="{{ desk }}"><div style="background:var(--ui-bg);border:1px solid var(--ui-border)">
|
||||
<div style="display:grid;grid-template-columns:{{ cols }};gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500"><span>Name</span><span>Key</span><span>Status</span><sc-if value="{{ owner }}"><span>Created by</span></sc-if><span>Created</span><span>Last used</span><span>Expires</span><span></span></div>
|
||||
<sc-for list="{{ rows }}" as="r" hint-placeholder-count="4"><div style="display:grid;grid-template-columns:{{ cols }};gap:12px;height:48px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border);background:{{ r.bg }}">
|
||||
<sc-if value="{{ r.skel }}"><span style="height:12px;width:60%;background:var(--ui-bg-accented)"></span><span style="height:12px;width:70%;background:var(--ui-bg-accented)"></span><span style="height:20px;width:56px;background:var(--ui-bg-accented)"></span><span style="height:12px;width:60%;background:var(--ui-bg-accented)"></span><span></span><span></span><span></span></sc-if>
|
||||
<sc-if value="{{ r.name }}"><span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;color:{{ r.fg }}">{{ r.name }}</span><span style="font:400 12px 'IBM Plex Mono',monospace;color:{{ r.fg2 }}">{{ r.prefix }}</span><span><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;background:{{ r.sbg }};color:{{ r.sfg }};font-size:12px;font-weight:500">{{ r.status }}</span></span>
|
||||
<sc-if value="{{ owner }}"><span style="color:{{ r.fg2 }};overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ r.by }}</span></sc-if><span style="color:{{ r.fg2 }}">{{ r.created }}</span><span style="color:{{ r.fg2 }}">{{ r.used }}</span><span style="color:{{ r.fg2 }}">{{ r.exp }}</span>
|
||||
<span style="display:flex;justify-content:flex-end"><sc-if value="{{ r.canRevoke }}"><span style="height:28px;padding:0 10px;display:flex;align-items:center;border:1px solid var(--ui-border-accented);color:var(--ui-text-highlighted);font-weight:500">Revoke</span></sc-if></span></sc-if>
|
||||
</div></sc-for></div></sc-if>
|
||||
<sc-if value="{{ mob }}"><div style="background:var(--ui-bg);border:1px solid var(--ui-border);margin:0 -16px;border-left:0;border-right:0">
|
||||
<sc-for list="{{ rows }}" as="r" hint-placeholder-count="4"><div style="display:flex;flex-direction:column;gap:6px;padding:12px 16px;border-bottom:1px solid var(--ui-border);background:{{ r.bg }}">
|
||||
<sc-if value="{{ r.skel }}"><span style="height:14px;width:55%;background:var(--ui-bg-accented)"></span><span style="height:12px;width:40%;background:var(--ui-bg-accented)"></span></sc-if>
|
||||
<sc-if value="{{ r.name }}"><div style="display:flex;align-items:center;gap:8px"><span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;font-size:15px;color:{{ r.fg }}">{{ r.name }}</span><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;background:{{ r.sbg }};color:{{ r.sfg }};font-size:12px;font-weight:500">{{ r.status }}</span></div>
|
||||
<span style="font:400 12px 'IBM Plex Mono',monospace;color:{{ r.fg2 }}">{{ r.prefix }}</span>
|
||||
<span style="color:{{ r.fg2 }}">Created {{ r.created }}<sc-if value="{{ owner }}"> by {{ r.by }}</sc-if> · Last used {{ r.used }} · Expires {{ r.exp }}</span>
|
||||
<sc-if value="{{ r.canRevoke }}"><span style="align-self:flex-start;height:44px;padding:0 14px;display:flex;align-items:center;border:1px solid var(--ui-border-accented);color:var(--ui-text-highlighted);font-weight:500">Revoke</span></sc-if></sc-if>
|
||||
</div></sc-for></div></sc-if>
|
||||
</sc-if>
|
||||
<div style="display:flex;flex-direction:column;gap:8px;font-size:14px;line-height:22px;color:var(--ui-text-toned)">
|
||||
<div style="display:flex;gap:10px"><span style="display:flex;padding-top:3px;color:var(--ui-info)"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat"></span></span><span style="text-wrap:pretty">Resetting a user's password revokes all of their keys.</span></div>
|
||||
</div>
|
||||
<sc-if value="{{ pinned }}"><div style="position:absolute;left:0;right:0;bottom:0;z-index:40;padding:12px 16px;background:var(--ui-bg);border-top:1px solid var(--ui-border)"><span style="height:44px;display:flex;align-items:center;justify-content:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500">Create key</span></div></sc-if>
|
||||
<sc-if value="{{ toast }}"><div role="status" style="position:absolute;{{ toastPos }};z-index:60;display:flex;gap:10px;padding:12px 14px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);color:var(--ui-success)"><span style="display:flex;flex-direction:column"><strong>Key revoked</strong><span style="color:var(--ui-text-toned)">"Nightly media import" can no longer be used.</span></span></div></sc-if>
|
||||
</div>
|
||||
<sc-if value="{{ modal }}"><div style="position:absolute;inset:0;z-index:50;background:var(--rc-overlay);display:flex;align-items:{{ mAlign }};justify-content:center;padding:{{ mPad }}">
|
||||
<div role="dialog" aria-modal="true" style="width:{{ mW }};max-width:100%;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-modal);padding:20px;display:flex;flex-direction:column;gap:14px;color:var(--ui-text)">
|
||||
<div style="display:flex;flex-direction:column;gap:4px"><span style="font:600 18px/26px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ m.title }}</span><span style="color:var(--ui-text-toned);font-size:14px;line-height:22px;text-wrap:pretty">{{ m.desc }}</span></div>
|
||||
<sc-if value="{{ m.form }}">
|
||||
<div style="display:flex;flex-direction:column;gap:6px"><div style="display:flex;justify-content:space-between"><span style="font-weight:500;color:var(--ui-text-highlighted)">Name</span><span style="font:400 12px 'IBM Plex Mono',monospace;color:{{ m.cntFg }}">{{ m.count }}</span></div><span style="height:40px;padding:0 12px;display:flex;align-items:center;border:1px solid {{ m.nameBd }};background:var(--ui-bg);color:var(--ui-text-highlighted)">{{ m.name }}</span><span style="color:{{ m.nameFg }}">{{ m.nameHelp }}</span></div>
|
||||
<div style="display:flex;flex-direction:column;gap:6px"><span style="font-weight:500;color:var(--ui-text-highlighted)">Expiry date <span style="font-weight:400;color:var(--ui-text-muted)">(optional)</span></span><span style="height:40px;padding:0 12px;display:flex;align-items:center;border:1px solid {{ m.expBd }};background:var(--ui-bg);color:{{ m.expTx }}">{{ m.exp }}</span><span style="color:{{ m.expFg }}">{{ m.expHelp }}</span></div>
|
||||
</sc-if>
|
||||
<sc-if value="{{ m.reveal }}">
|
||||
<div style="display:flex;gap:10px;padding:10px 12px;background:var(--rc-warning-soft);color:var(--ui-warning)"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/triangle-alert.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/triangle-alert.svg') center / contain no-repeat"></span></span><span style="font-weight:500">You won't be able to see this key again.</span></div>
|
||||
<div style="display:flex;flex-direction:{{ keyDir }};border:1px solid var(--ui-border-accented);background:var(--ui-bg-elevated)"><span style="flex:1;min-width:0;padding:10px 12px;font:400 12px/20px 'IBM Plex Mono',monospace;word-break:break-all;color:var(--ui-text-highlighted)">rcms_Kf3x9QwL0aBcT7nV2uYdE5sHjR8mPz4WqXg6C1oIyNe</span><span style="height:44px;padding:0 14px;display:flex;align-items:center;justify-content:center;gap:6px;border-left:1px solid var(--ui-border-accented);font-weight:500;color:{{ m.cpFg }}"><span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ m.cpIcon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ m.cpIcon }}.svg') center / contain no-repeat"></span>{{ m.cpT }}</span></div>
|
||||
<span style="color:var(--ui-text-muted)">Closing this window discards the key from the screen. Copy it first.</span>
|
||||
</sc-if>
|
||||
<div style="display:flex;flex-direction:{{ btnDir }};justify-content:flex-end;gap:8px"><sc-if value="{{ m.cancel }}"><span style="height:44px;padding:0 14px;display:flex;align-items:center;justify-content:center;border:1px solid var(--ui-border-accented);color:var(--ui-text-highlighted);font-weight:500">{{ m.cancel }}</span></sc-if><span style="height:44px;padding:0 14px;display:flex;align-items:center;justify-content:center;font-weight:500;background:{{ m.cbg }};color:{{ m.cfg }};opacity:{{ m.cop }}">{{ m.confirm }}</span></div>
|
||||
</div></div></sc-if>
|
||||
</x-dc>
|
||||
<script type="text/x-dc" data-dc-script>
|
||||
class Component extends DCLogic {
|
||||
renderVals() {
|
||||
const mob = !!this.props.mobile, k = (this.props.s && this.props.s.ak) || {}
|
||||
const owner = k.view !== 'admin'
|
||||
const R = (name, prefix, status, by, created, used, exp) => {
|
||||
const rv = status === 'revoked', tone = { active: ['var(--rc-success-soft)', 'var(--ui-success)'], expired: ['var(--rc-warning-soft)', 'var(--ui-warning)'], revoked: ['var(--ui-bg-elevated)', 'var(--ui-text-muted)'] }[status]
|
||||
return { name, prefix, status, by, created, used, exp, sbg: tone[0], sfg: tone[1], bg: rv ? 'var(--ui-bg-muted)' : 'var(--ui-bg)', fg: rv ? 'var(--ui-text-muted)' : 'var(--ui-text-highlighted)', fg2: rv ? 'var(--ui-text-muted)' : 'var(--ui-text-toned)', canRevoke: !rv }
|
||||
}
|
||||
let all = owner
|
||||
? [R('Website build', 'rcms_Kf3x…', 'active', 'Marta Alves', '12 Mar 2026', '3 Oct 2026', 'None'), R('Nightly media import', 'rcms_Mq7b…', k.revoked ? 'revoked' : 'active', 'Jonas', '2 Apr 2026', '3 Oct 2026', '31 Dec 2026'), R('Staging preview', 'rcms_Zt2d…', 'expired', 'Marta Alves', '14 Jun 2026', '20 Aug 2026', '30 Aug 2026'), R('Old migration script', 'rcms_Hn5w…', 'revoked', 'Inès Duarte', '3 Apr 2026', '9 May 2026', 'None')]
|
||||
: [R('Nightly media import', 'rcms_Mq7b…', 'active', 'Jonas', '2 Apr 2026', '3 Oct 2026', '31 Dec 2026'), R('Old CI token', 'rcms_Lp9c…', 'revoked', 'Jonas', '18 Jan 2026', '2 Feb 2026', 'None')]
|
||||
const st = k.state || 'list'
|
||||
const rows = st === 'loading' ? Array.from({ length: 4 }, () => ({ skel: true, bg: 'var(--ui-bg)' })) : all
|
||||
const cp = { reveal: true }
|
||||
const b = (o) => ({ cancel: 'Cancel', cbg: 'var(--ui-primary)', cfg: 'var(--ui-bg)', cop: '1', ...o })
|
||||
const form = (o) => b({ form: true, title: 'Create API key', desc: 'The key acts as you, with your role. It is shown in full once.', confirm: 'Create key', name: 'Nightly media import', count: '20 / 60', cntFg: 'var(--ui-text-muted)', nameBd: 'var(--ui-border-accented)', nameFg: 'var(--ui-text-muted)', nameHelp: 'Required. Up to 60 characters.', exp: '31 Dec 2026', expTx: 'var(--ui-text-highlighted)', expBd: 'var(--ui-border-accented)', expFg: 'var(--ui-text-muted)', expHelp: 'Optional. Must be in the future. Leave it empty for a key that does not expire.', ...o })
|
||||
const M = {
|
||||
create: form({}),
|
||||
invalid: form({ name: '', count: '0 / 60', nameBd: 'var(--ui-error)', nameFg: 'var(--ui-error)', nameHelp: 'Enter a name.', exp: '12 Mar 2026', expBd: 'var(--ui-error)', expFg: 'var(--ui-error)', expHelp: 'Choose a date in the future.' }),
|
||||
toolong: form({ name: 'Nightly import of the new media library from the Brussels office file server', count: '75 / 60', cntFg: 'var(--ui-error)', nameBd: 'var(--ui-error)', nameFg: 'var(--ui-error)', nameHelp: 'Use 60 characters or fewer.' }),
|
||||
reveal: b({ reveal: true, title: 'Your new API key', desc: '"Nightly media import" is ready. Copy the key and store it somewhere safe.', cancel: '', confirm: 'Done', cpT: 'Copy', cpIcon: 'copy', cpFg: 'var(--ui-text-highlighted)' }),
|
||||
copied: b({ reveal: true, title: 'Your new API key', desc: '"Nightly media import" is ready. Copy the key and store it somewhere safe.', cancel: '', confirm: 'Done', cpT: 'Copied', cpIcon: 'check', cpFg: 'var(--ui-success)' }),
|
||||
revoke: b({ title: 'Revoke this key?', desc: '"Nightly media import" (rcms_Mq7b…) will stop working right away. Requests that use it answer 401. This can\'t be undone.', cancel: 'Keep key', confirm: 'Revoke key', cbg: 'var(--ui-error)', cfg: 'var(--ui-bg)' })
|
||||
}
|
||||
const m = k.modal ? M[k.modal] : null
|
||||
return {
|
||||
mob, desk: !mob, owner, rows, pad: mob ? '20px 16px 84px' : '32px', pinned: mob && !m, h1: mob ? '20px/28px' : '28px/36px',
|
||||
sub: owner ? 'Keys act as the user who created them. As an owner you see everyone\'s keys.' : 'Keys act as you, with your role. You only see your own keys.',
|
||||
err: st === 'error', empty: st === 'empty', showList: st === 'list' || st === 'loading',
|
||||
cols: owner ? 'minmax(0,1.3fr) 110px 76px minmax(0,1fr) 100px 100px 100px 80px' : 'minmax(0,1.3fr) 110px 76px 100px 100px 100px 80px',
|
||||
toast: !!k.toast, toastPos: mob ? 'left:16px;right:16px;bottom:84px' : 'right:24px;bottom:24px;width:320px',
|
||||
modal: !!m, m: m || {}, mAlign: mob ? 'flex-end' : 'flex-start', mPad: mob ? '16px' : '120px 16px 16px', mW: mob ? '100%' : '480px', btnDir: mob ? 'column-reverse' : 'row', keyDir: mob ? 'column' : 'row'
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -12,20 +12,20 @@
|
||||
<div style="width:224px;flex-shrink:0;background:var(--ui-bg);border-right:1px solid var(--ui-border);display:flex;flex-direction:column;padding:12px;gap:2px">
|
||||
<div style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px;margin-bottom:10px"><svg width="26" height="26" viewBox="0 0 16 16" shape-rendering="crispEdges"><rect width="16" height="16" fill="#111"></rect><path fill="#fff" fill-rule="evenodd" d="M4 3h6v1h1v1h1v3h-1v1h-1v1h1v1h1v2h-2v-2h-1v-1H6v3H4zm2 2v3h4V5z"></path></svg><span style="font-weight:600;font-size:14px;color:var(--ui-text-highlighted)">RenewCMS</span></div>
|
||||
<sc-for list="{{ nav }}" as="n" hint-placeholder-count="3">
|
||||
<div data-act="nav-{{ n.key }}" style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px;background:{{ n.bg }};color:{{ n.fg }};font-weight:{{ n.fw }}"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat"></span>{{ n.t }}</div>
|
||||
<div data-act="nav-{{ n.key }}" style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px;background:{{ n.bg }};color:{{ n.fg }};font-weight:{{ n.fw }}"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat"></span>{{ n.t }}<sc-if value="{{ n.badge }}"><span style="margin-left:auto;height:18px;padding:0 6px;display:inline-flex;align-items:center;background:var(--ui-info);color:var(--ui-bg);font:500 11px 'IBM Plex Sans',sans-serif">Update</span></sc-if></div>
|
||||
</sc-for>
|
||||
<div style="flex:1"></div>
|
||||
<sc-if value="{{ s.boot }}"><div style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px"><span style="width:26px;height:26px;background:var(--ui-bg-accented)"></span><span style="width:80px;height:12px;background:var(--ui-bg-accented)"></span></div></sc-if>
|
||||
<sc-if value="{{ notBoot }}"><div data-act="usermenu" role="button" aria-haspopup="menu" aria-expanded="{{ menuOpen }}" title="Account" style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px;background:{{ chipBg }};color:{{ chipFg }}"><span style="width:26px;height:26px;flex-shrink:0;background:#d4c5b0;color:#111;display:flex;align-items:center;justify-content:center;font:600 11px 'IBM Plex Sans',sans-serif">{{ ini }}</span><span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500">{{ who }}</span><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevrons-up-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevrons-up-down.svg') center / contain no-repeat"></span></div></sc-if>
|
||||
</div>
|
||||
<sc-if value="{{ deskMenu }}"><div role="menu" aria-label="Account" style="position:absolute;left:12px;bottom:56px;z-index:40;width:224px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:4px"><div style="padding:8px 8px 10px;display:flex;flex-direction:column;gap:2px;border-bottom:1px solid var(--ui-border);margin-bottom:4px"><span style="font-weight:600;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ who }}</span><span style="font-size:12px;color:var(--ui-text-muted)">marta@renew.example</span></div><div data-act="nav-profile" role="menuitem" style="height:32px;padding:0 8px;display:flex;align-items:center;gap:10px;background:{{ pfItemBg }};color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat"></span>Profile</div><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><sc-for list="{{ themeSeg }}" as="m" hint-placeholder-count="3"><div data-act="{{ m.act }}" role="menuitemradio" aria-checked="{{ m.on }}" style="height:32px;padding:0 8px;display:flex;align-items:center;justify-content:space-between;font-size:14px;color:var(--ui-text-highlighted)">{{ m.t }}<span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;opacity:{{ m.op }};-webkit-mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat"></span></div></sc-for><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><div data-act="logout" role="menuitem" style="height:32px;padding:0 8px;display:flex;align-items:center;gap:10px;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat"></span>Log out</div></div></sc-if>
|
||||
<sc-if value="{{ deskMenu }}"><div role="menu" aria-label="Account" style="position:absolute;left:12px;bottom:56px;z-index:40;width:224px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:4px"><div style="padding:8px 8px 10px;display:flex;flex-direction:column;gap:2px;border-bottom:1px solid var(--ui-border);margin-bottom:4px"><span style="font-weight:600;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ who }}</span><span style="font-size:12px;color:var(--ui-text-muted)">marta@renew.example</span></div><div data-act="nav-profile" role="menuitem" style="height:32px;padding:0 8px;display:flex;align-items:center;gap:10px;background:{{ pfItemBg }};color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat"></span>Profile</div><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><div style="padding:6px 8px 2px;font-size:11px;font-weight:500;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Theme</div><sc-for list="{{ themeSeg }}" as="m" hint-placeholder-count="3"><div data-act="{{ m.act }}" role="menuitemradio" aria-checked="{{ m.on }}" style="height:32px;padding:0 8px;display:flex;align-items:center;justify-content:space-between;font-size:14px;color:var(--ui-text-highlighted)">{{ m.t }}<span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;opacity:{{ m.op }};-webkit-mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat"></span></div></sc-for><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><div style="padding:6px 8px 2px;font-size:11px;font-weight:500;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Language</div><sc-for list="{{ langSeg }}" as="m" hint-placeholder-count="2"><div data-act="{{ m.act }}" lang="{{ m.code }}" role="menuitemradio" aria-checked="{{ m.on }}" style="height:32px;padding:0 8px;display:flex;align-items:center;justify-content:space-between;font-size:14px;color:var(--ui-text-highlighted)">{{ m.t }}<span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;opacity:{{ m.op }};-webkit-mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat"></span></div></sc-for><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><div data-act="logout" role="menuitem" style="height:32px;padding:0 8px;display:flex;align-items:center;gap:10px;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat"></span>Log out</div></div></sc-if>
|
||||
</sc-if>
|
||||
<div style="flex:1;min-width:0;min-height:0;display:flex;flex-direction:column">
|
||||
<sc-if value="{{ desk }}" hint-placeholder-val="{{ true }}">
|
||||
<div style="height:48px;flex-shrink:0;border-bottom:1px solid var(--ui-border);background:var(--ui-bg);display:flex;align-items:center;padding:0 24px;gap:8px;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/panel-left-close.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/panel-left-close.svg') center / contain no-repeat"></span><span style="width:1px;height:16px;background:var(--ui-border);margin:0 6px"></span><sc-for list="{{ crumbs }}" as="c" hint-placeholder-count="1"><sc-if value="{{ c.sep }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevron-right.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-right.svg') center / contain no-repeat"></span></sc-if><span style="color:{{ c.fg }};font-weight:{{ c.fw }}">{{ c.t }}</span></sc-for></div>
|
||||
</sc-if>
|
||||
<sc-if value="{{ mob }}">
|
||||
<div style="height:56px;flex-shrink:0;border-bottom:1px solid var(--ui-border);background:var(--ui-bg);display:flex;align-items:center;padding:0 6px;gap:4px;color:var(--ui-text-highlighted)"><span data-act="m-lead" style="width:44px;height:44px;display:flex;align-items:center;justify-content:center"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:20px;height:20px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ mLead }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ mLead }}.svg') center / contain no-repeat"></span></span><span style="flex:1;min-width:0;font-weight:600;font-size:16px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ s.mTitle }}</span><sc-if value="{{ s.mAction }}"><span data-act="m-action" style="width:44px;height:44px;display:flex;align-items:center;justify-content:center"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:20px;height:20px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ s.mAction }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.mAction }}.svg') center / contain no-repeat"></span></span></sc-if></div>
|
||||
<div style="height:56px;flex-shrink:0;border-bottom:1px solid var(--ui-border);background:var(--ui-bg);display:flex;align-items:center;padding:0 6px;gap:4px;color:var(--ui-text-highlighted)"><span data-act="m-lead" style="position:relative;width:44px;height:44px;display:flex;align-items:center;justify-content:center"><sc-if value="{{ s.navBadge }}"><span aria-label="Update available" style="position:absolute;top:9px;right:9px;width:10px;height:10px;background:var(--ui-info);border:2px solid var(--ui-bg)"></span></sc-if><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:20px;height:20px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ mLead }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ mLead }}.svg') center / contain no-repeat"></span></span><span style="flex:1;min-width:0;font-weight:600;font-size:16px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ s.mTitle }}</span><sc-if value="{{ s.mAction }}"><span data-act="m-action" style="width:44px;height:44px;display:flex;align-items:center;justify-content:center"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:20px;height:20px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ s.mAction }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.mAction }}.svg') center / contain no-repeat"></span></span></sc-if></div>
|
||||
</sc-if>
|
||||
<sc-if value="{{ s.offline }}"><div role="status" style="flex-shrink:0;display:flex;align-items:center;gap:10px;padding:10px 16px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/wifi-off.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/wifi-off.svg') center / contain no-repeat"></span><span style="flex:1">You're offline. You can keep writing, but saving and publishing will wait until you're back online.</span></div></sc-if>
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
<sc-if value="{{ isHome }}">
|
||||
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:{{ gap }};max-width:1040px">
|
||||
<div style="display:flex;align-items:flex-end;gap:16px;flex-wrap:wrap"><div style="flex:1;min-width:200px;display:flex;flex-direction:column;gap:4px"><span style="font:600 28px/36px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Good morning, {{ who }}</span><span style="color:var(--ui-text-muted);font-size:14px">{{ s.home.sub }}</span></div><sc-if value="{{ desk }}"><span data-act="new" style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/plus.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/plus.svg') center / contain no-repeat"></span>New article</span></sc-if></div>
|
||||
<sc-if value="{{ s.home.banner }}"><div role="region" aria-label="Update available" style="display:flex;flex-direction:{{ upBtnDir }};align-items:{{ upBannerAlign }};gap:12px;padding:12px 14px;background:{{ s.home.banner.bg }};border:1px solid var(--ui-border)"><div style="flex:1;display:flex;gap:10px;min-width:0"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:{{ s.home.banner.fg }};-webkit-mask:url('https://api.iconify.design/lucide/{{ s.home.banner.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.home.banner.icon }}.svg') center / contain no-repeat"></span></span><div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600;color:var(--ui-text-highlighted)">{{ s.home.banner.title }}</span><span style="color:var(--ui-text-toned);text-wrap:pretty">{{ s.home.banner.text }}</span></div></div><div style="display:flex;align-items:center;gap:8px"><span style="flex:1;height:{{ btnH }};padding:0 12px;display:flex;align-items:center;justify-content:center;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500">{{ s.home.banner.btn }}</span><span role="button" aria-label="Dismiss" style="width:{{ btnH }};height:{{ btnH }};display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/x.svg') center / contain no-repeat"></span></span></div></div></sc-if>
|
||||
<sc-if value="{{ s.home.error }}"><div role="alert" style="display:flex;gap:10px;padding:12px 14px;background:var(--rc-error-soft);color:var(--ui-error)"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat"></span></span><div style="flex:1;display:flex;flex-direction:column;gap:8px"><div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600">Couldn't load your articles</span><span style="color:var(--ui-text-toned)">Check your connection and try again.</span></div><span style="align-self:flex-start;height:28px;padding:0 10px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500;font-size:12px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/rotate-cw.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/rotate-cw.svg') center / contain no-repeat"></span>Try again</span></div></div></sc-if>
|
||||
<sc-if value="{{ s.home.stats }}">
|
||||
<div style="display:grid;grid-template-columns:{{ cols3 }};gap:12px">
|
||||
@@ -176,25 +177,8 @@
|
||||
</sc-if>
|
||||
</sc-if>
|
||||
|
||||
<sc-if value="{{ isInteg }}">
|
||||
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:24px;max-width:860px;overflow:hidden">
|
||||
<div style="display:flex;flex-direction:column;gap:4px"><span style="font:600 20px/28px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Connect your website</span><span style="color:var(--ui-text-muted)">A guide for the developer who builds your public site.</span></div>
|
||||
<p style="margin:0;font-size:14px;line-height:22px;color:var(--ui-text-toned);text-wrap:pretty">RenewCMS is headless: it stores and publishes your articles but doesn't show them to visitors. Your website fetches published articles from the two addresses below and displays them in its own design.</p>
|
||||
<div style="display:flex;flex-direction:column;gap:6px"><span style="font-weight:500;color:var(--ui-text-highlighted)">Base URL</span><div style="display:flex;border:1px solid var(--ui-border-accented);background:var(--ui-bg)"><span style="flex:1;min-width:0;height:40px;padding:0 12px;display:flex;align-items:center;font:400 13px 'IBM Plex Mono',monospace;overflow:hidden;white-space:nowrap">https://cms.renew.example</span><span data-act="copy" style="height:40px;padding:0 12px;display:flex;align-items:center;gap:6px;border-left:1px solid var(--ui-border-accented);font-weight:500;color:{{ copyFg }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ copyIcon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ copyIcon }}.svg') center / contain no-repeat"></span>{{ copyText }}</span></div></div>
|
||||
<sc-for list="{{ endpoints }}" as="e" hint-placeholder-count="2">
|
||||
<div style="background:var(--ui-bg);border:1px solid var(--ui-border)">
|
||||
<div style="padding:16px;display:flex;flex-direction:column;gap:8px;border-bottom:1px solid var(--ui-border)"><div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap"><span style="height:22px;padding:0 7px;display:inline-flex;align-items:center;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font:500 12px 'IBM Plex Mono',monospace">GET</span><span style="font:500 14px 'IBM Plex Mono',monospace;color:var(--ui-text-highlighted)">{{ e.path }}</span></div><span style="color:var(--ui-text-toned)">{{ e.desc }}</span></div>
|
||||
<div style="display:flex;gap:20px;padding:0 16px;border-bottom:1px solid var(--ui-border)"><span style="height:36px;display:flex;align-items:center;border-bottom:2px solid {{ e.l1 }};margin-bottom:-1px;font-weight:500;color:var(--ui-text-highlighted)">fetch</span><span style="height:36px;display:flex;align-items:center;color:var(--ui-text-toned)">curl</span><span style="height:36px;display:flex;align-items:center;color:var(--ui-text-toned)">Response</span></div>
|
||||
<div style="background:var(--ui-bg-elevated)"><div style="height:32px;padding:0 8px 0 16px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--ui-border)"><span style="font:500 12px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">JavaScript</span><span style="display:flex;align-items:center;gap:6px;color:var(--ui-text-toned);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/copy.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/copy.svg') center / contain no-repeat"></span>Copy</span></div><pre style="margin:0;padding:14px 16px;overflow:hidden;font:400 12px/19px 'IBM Plex Mono',monospace;color:var(--ui-text);white-space:pre">{{ e.code }}</pre></div>
|
||||
</div>
|
||||
</sc-for>
|
||||
<div style="display:flex;flex-direction:column;gap:10px;font-size:14px;line-height:22px;color:var(--ui-text-toned)">
|
||||
<div style="display:flex;gap:10px"><span style="display:flex;padding-top:3px;color:var(--ui-info)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat"></span></span><span style="text-wrap:pretty">Anonymous callers only ever get online articles. Drafts stay private until you publish them.</span></div>
|
||||
<div style="display:flex;gap:10px"><span style="display:flex;padding-top:3px;color:var(--ui-info)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat"></span></span><span style="text-wrap:pretty">Images in <code>body</code> use paths like <code>/static/uploadedImages/<uuid>.png</code>. Prefix them with the base URL before rendering.</span></div>
|
||||
<div style="display:flex;gap:10px"><span style="display:flex;padding-top:3px;color:var(--ui-info)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat"></span></span><span style="text-wrap:pretty">Browsers can only call the API from origins listed in the server's CORS setting. Ask whoever runs the server to add your site's address.</span></div>
|
||||
</div>
|
||||
</div>
|
||||
</sc-if>
|
||||
<sc-if value="{{ isInteg }}"><div style="position:relative;flex:1;min-height:0;overflow:hidden"><dc-import name="IntegrationPage" s="{{ s }}" mobile="{{ mob }}" style="display:flex;flex-direction:column;flex:1;min-height:0;overflow:hidden" hint-size="100%,100%"></dc-import></div></sc-if>
|
||||
<sc-if value="{{ isKeys }}"><div style="display:flex;flex-direction:column;flex:1;min-height:0;overflow:hidden"><dc-import name="ApiKeysPage" s="{{ s }}" mobile="{{ mob }}" style="display:flex;flex-direction:column;flex:1;min-height:0;overflow:hidden" hint-size="100%,100%"></dc-import></div></sc-if>
|
||||
|
||||
<sc-if value="{{ isUsers }}">
|
||||
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:16px;flex:1;min-height:0">
|
||||
@@ -229,7 +213,16 @@
|
||||
<sc-if value="{{ isSettings }}">
|
||||
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:20px;max-width:720px;overflow:hidden">
|
||||
<div style="display:flex;flex-direction:column;gap:2px"><span style="font:600 20px/28px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Settings</span><span style="color:var(--ui-text-muted)">Workspace information.</span></div>
|
||||
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;align-items:center;justify-content:space-between;gap:16px"><span style="font:600 15px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Version</span><span style="font:400 14px/22px 'IBM Plex Mono',monospace;color:var(--ui-text-toned)">v2.2.0-beta</span></div>
|
||||
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;align-items:center;justify-content:space-between;gap:16px"><span style="font:600 15px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Version</span><span style="font:400 14px/22px 'IBM Plex Mono',monospace;color:var(--ui-text-toned)">{{ s.upd.v }}</span></div>
|
||||
<div role="region" aria-labelledby="updates-h" style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;flex-direction:column;gap:16px">
|
||||
<span id="updates-h" tabindex="-1" style="align-self:flex-start;font:600 15px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted);outline:{{ s.upd.focus }};outline-offset:4px">Updates</span>
|
||||
<div aria-live="polite" style="display:flex;gap:12px;padding:14px;background:{{ s.upd.bg }}"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:{{ s.upd.fg }};-webkit-mask:url('https://api.iconify.design/lucide/{{ s.upd.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.upd.icon }}.svg') center / contain no-repeat"></span></span><div style="flex:1;min-width:0;display:flex;flex-direction:column;gap:4px"><div style="display:flex;align-items:center;flex-wrap:wrap;gap:8px"><span style="font:600 14px/22px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ s.upd.title }}</span><sc-if value="{{ s.upd.pendingTag }}"><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;background:var(--ui-bg);color:var(--ui-warning);border:1px solid var(--ui-warning);font:500 11px 'IBM Plex Mono',monospace">Pending</span></sc-if></div><span style="color:var(--ui-text-toned);text-wrap:pretty">{{ s.upd.text }}</span><sc-if value="{{ s.upd.bar }}"><div style="display:flex;flex-direction:column;gap:6px;padding-top:8px"><div role="progressbar" aria-label="{{ s.upd.barLabel }}" aria-valuemin="0" aria-valuemax="100" aria-valuenow="{{ s.upd.pct }}" style="height:6px;background:var(--ui-bg-accented)"><div style="height:6px;width:{{ s.upd.barW }};margin-left:{{ s.upd.barL }};background:var(--ui-primary)"></div></div><span style="font:400 12px/16px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">{{ s.upd.barText }}</span></div></sc-if><sc-if value="{{ s.upd.meta }}"><span style="font-size:12px;color:var(--ui-text-muted)">{{ s.upd.meta }}</span></sc-if><sc-if value="{{ s.upd.inBtn }}"><div style="display:flex;padding-top:8px"><span role="button" style="height:{{ btnH }};padding:0 14px;display:flex;align-items:center;justify-content:center;gap:6px;background:{{ s.upd.inBtn.bg }};color:{{ s.upd.inBtn.fg }};border:1px solid {{ s.upd.inBtn.bd }};font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ s.upd.inBtn.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.upd.inBtn.icon }}.svg') center / contain no-repeat"></span>{{ s.upd.inBtn.t }}</span></div></sc-if></div></div>
|
||||
<sc-if value="{{ s.upd.notes }}"><div style="display:flex;flex-direction:column;gap:10px"><span role="button" aria-expanded="{{ s.upd.notes.open }}" style="align-self:flex-start;display:flex;align-items:center;gap:6px;min-height:{{ btnH }};font-weight:500;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ s.upd.notes.chev }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.upd.notes.chev }}.svg') center / contain no-repeat"></span>What's new in {{ s.upd.notes.ver }}</span><sc-if value="{{ s.upd.notes.open }}"><div style="display:flex;flex-direction:column;gap:8px;padding:0 0 0 20px"><span style="font-size:12px;color:var(--ui-text-muted)">{{ s.upd.notes.date }}</span><sc-for list="{{ s.upd.notes.items }}" as="it" hint-placeholder-count="3"><div style="display:flex;gap:8px"><span aria-hidden="true" style="flex-shrink:0;width:4px;height:4px;margin-top:8px;background:var(--ui-text-muted)"></span><span style="color:var(--ui-text-toned);text-wrap:pretty">{{ it.t }}</span></div></sc-for><span style="align-self:flex-start;color:var(--ui-text-highlighted);text-decoration:underline;text-underline-offset:3px;font-weight:500">Read the full release notes</span></div></sc-if></div></sc-if>
|
||||
<sc-if value="{{ s.upd.cmd }}"><div style="display:flex;flex-direction:column;gap:8px"><span style="font-weight:500;color:var(--ui-text-highlighted)">For whoever manages the server</span><div style="display:flex;flex-direction:{{ upCmdDir }};align-items:{{ upBtnAlign }};gap:8px"><code style="flex:1;min-width:0;padding:8px 12px;background:var(--ui-bg-elevated);color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;line-height:22px">{{ s.upd.cmd.line }}</code><span role="button" style="height:{{ btnH }};padding:0 12px;display:flex;align-items:center;justify-content:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:{{ s.upd.cmd.fg }};font-weight:500"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ s.upd.cmd.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.upd.cmd.icon }}.svg') center / contain no-repeat"></span>{{ s.upd.cmd.t }}</span></div><span style="font-size:12px;color:var(--ui-text-muted)">{{ s.upd.cmd.note }}</span></div></sc-if>
|
||||
<sc-if value="{{ s.upd.btns }}"><div style="display:flex;flex-direction:{{ upBtnDir }};align-items:{{ upBtnAlign }};gap:8px"><sc-for list="{{ s.upd.btns }}" as="b" hint-placeholder-count="1"><span role="button" style="height:{{ btnH }};padding:0 14px;display:flex;align-items:center;justify-content:center;gap:6px;background:{{ b.bg }};color:{{ b.fg }};border:1px solid {{ b.bd }};opacity:{{ b.op }};font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ b.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ b.icon }}.svg') center / contain no-repeat"></span>{{ b.t }}</span></sc-for></div></sc-if>
|
||||
<sc-if value="{{ s.upd.hint }}"><span style="font-size:12px;color:var(--ui-text-muted);text-wrap:pretty">{{ s.upd.hint }}</span></sc-if>
|
||||
<sc-if value="{{ s.upd.link }}"><span style="align-self:flex-start;display:flex;align-items:center;gap:6px;color:var(--ui-text-highlighted);text-decoration:underline;text-underline-offset:3px;font-weight:500">{{ s.upd.link }}<span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/external-link.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/external-link.svg') center / contain no-repeat"></span></span></sc-if>
|
||||
</div>
|
||||
</div>
|
||||
</sc-if>
|
||||
|
||||
@@ -270,7 +263,9 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<sc-if value="{{ mobMenu }}"><div style="position:absolute;inset:0;z-index:50;background:var(--rc-overlay);display:flex;align-items:flex-end"><div role="menu" aria-label="Account" style="width:100%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);padding:8px 0 24px"><div style="margin:0 auto 8px;width:36px;height:4px;background:var(--ui-bg-accented)"></div><div style="padding:8px 16px 14px;display:flex;align-items:center;gap:12px;border-bottom:1px solid var(--ui-border);margin-bottom:4px"><span style="width:36px;height:36px;flex-shrink:0;background:#d4c5b0;color:#111;display:flex;align-items:center;justify-content:center;font:600 13px 'IBM Plex Sans',sans-serif">{{ ini }}</span><div style="display:flex;flex-direction:column;min-width:0"><span style="font-weight:600;font-size:15px;color:var(--ui-text-highlighted)">{{ who }}</span><span style="color:var(--ui-text-muted)">marta@renew.example</span></div></div><div data-act="nav-profile" role="menuitem" style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;font-size:15px;background:{{ pfItemBg }};color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat"></span>Profile</div><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><sc-for list="{{ themeSeg }}" as="m" hint-placeholder-count="3"><div data-act="{{ m.act }}" role="menuitemradio" aria-checked="{{ m.on }}" style="height:48px;padding:0 16px;display:flex;align-items:center;justify-content:space-between;font-size:15px;color:var(--ui-text-highlighted)">{{ m.t }}<span aria-hidden="true" style="display:inline-block;width:18px;height:18px;background-color:currentColor;opacity:{{ m.op }};-webkit-mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat"></span></div></sc-for><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><div data-act="logout" role="menuitem" style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;font-size:15px;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat"></span>Log out</div></div></div></sc-if>
|
||||
<sc-if value="{{ mobMenu }}"><div style="position:absolute;inset:0;z-index:50;background:var(--rc-overlay);display:flex;align-items:flex-end"><div role="menu" aria-label="Account" style="width:100%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);padding:8px 0 24px"><div style="margin:0 auto 8px;width:36px;height:4px;background:var(--ui-bg-accented)"></div><div style="padding:8px 16px 14px;display:flex;align-items:center;gap:12px;border-bottom:1px solid var(--ui-border);margin-bottom:4px"><span style="width:36px;height:36px;flex-shrink:0;background:#d4c5b0;color:#111;display:flex;align-items:center;justify-content:center;font:600 13px 'IBM Plex Sans',sans-serif">{{ ini }}</span><div style="display:flex;flex-direction:column;min-width:0"><span style="font-weight:600;font-size:15px;color:var(--ui-text-highlighted)">{{ who }}</span><span style="color:var(--ui-text-muted)">marta@renew.example</span></div></div><div data-act="nav-profile" role="menuitem" style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;font-size:15px;background:{{ pfItemBg }};color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat"></span>Profile</div><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><div style="padding:8px 16px 2px;font-size:11px;font-weight:500;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Theme</div><sc-for list="{{ themeSeg }}" as="m" hint-placeholder-count="3"><div data-act="{{ m.act }}" role="menuitemradio" aria-checked="{{ m.on }}" style="height:48px;padding:0 16px;display:flex;align-items:center;justify-content:space-between;font-size:15px;color:var(--ui-text-highlighted)">{{ m.t }}<span aria-hidden="true" style="display:inline-block;width:18px;height:18px;background-color:currentColor;opacity:{{ m.op }};-webkit-mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat"></span></div></sc-for><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><div style="padding:8px 16px 2px;font-size:11px;font-weight:500;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Language</div><sc-for list="{{ langSeg }}" as="m" hint-placeholder-count="2"><div data-act="{{ m.act }}" lang="{{ m.code }}" role="menuitemradio" aria-checked="{{ m.on }}" style="height:48px;padding:0 16px;display:flex;align-items:center;justify-content:space-between;font-size:15px;color:var(--ui-text-highlighted)">{{ m.t }}<span aria-hidden="true" style="display:inline-block;width:18px;height:18px;background-color:currentColor;opacity:{{ m.op }};-webkit-mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat"></span></div></sc-for><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><div data-act="logout" role="menuitem" style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;font-size:15px;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat"></span>Log out</div></div></div></sc-if>
|
||||
|
||||
<sc-if value="{{ s.overlay }}"><div role="status" aria-live="polite" style="position:absolute;inset:0;z-index:70;background:var(--ui-bg-muted);display:flex;align-items:center;justify-content:center;padding:24px"><div style="width:100%;max-width:440px;display:flex;flex-direction:column;gap:16px;align-items:flex-start"><svg width="26" height="26" viewBox="0 0 16 16" shape-rendering="crispEdges" aria-hidden="true"><rect width="16" height="16" fill="#111"></rect><path fill="#fff" fill-rule="evenodd" d="M4 3h6v1h1v1h1v3h-1v1h-1v1h1v1h1v2h-2v-2h-1v-1H6v3H4zm2 2v3h4V5z"></path></svg><div style="display:flex;flex-direction:column;gap:6px"><span style="font:600 22px/30px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ s.overlay.title }}</span><span style="font-size:14px;line-height:22px;color:var(--ui-text-toned);text-wrap:pretty">{{ s.overlay.text }}</span></div><div role="progressbar" aria-label="Restarting" style="width:100%;height:4px;background:var(--ui-bg-accented)"><div style="width:35%;height:4px;margin-left:{{ s.overlay.barL }};background:var(--ui-primary)"></div></div><span style="font-size:12px;color:var(--ui-text-muted)">{{ s.overlay.meta }}</span><sc-if value="{{ s.overlay.btn }}"><span role="button" style="height:{{ btnH }};padding:0 14px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500">{{ s.overlay.btn }}</span></sc-if></div></div></sc-if>
|
||||
|
||||
<sc-if value="{{ s.modal }}">
|
||||
<div style="position:absolute;inset:0;z-index:50;background:var(--rc-overlay);display:flex;align-items:{{ modalAlign }};justify-content:center;padding:{{ modalPad }}">
|
||||
@@ -344,7 +339,7 @@ class Component extends DCLogic {
|
||||
const m = !!this.props.mobile
|
||||
const k = s.kind || 'home'
|
||||
const navItems = [['home', 'house', 'Home'], ['articles', 'file-text', 'Articles'], ['media', 'images', 'Media'], ['users', 'users', 'Users'], ['integration', 'plug', 'Integration'], ['settings', 'settings', 'Settings']]
|
||||
const nav = navItems.map(([key, icon, t]) => ({ key, icon, t, bg: s.nav === key ? 'var(--rc-sand)' : 'transparent', fg: s.nav === key ? '#111111' : 'var(--ui-text-toned)', fw: s.nav === key ? 500 : 400 }))
|
||||
const nav = navItems.map(([key, icon, t]) => ({ key, icon, t, bg: s.nav === key ? 'var(--rc-sand)' : 'transparent', badge: key === 'settings' && !!s.navBadge, fg: s.nav === key ? '#111111' : 'var(--ui-text-toned)', fw: s.nav === key ? 500 : 400 }))
|
||||
const crumbs = (s.crumbs || []).map((t, i, a) => ({ t, sep: i > 0, fg: i === a.length - 1 ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)', fw: i === a.length - 1 ? 500 : 400 }))
|
||||
const L = s.list || {}
|
||||
const counts = L.counts || [6, 4, 2]
|
||||
@@ -423,17 +418,17 @@ class Component extends DCLogic {
|
||||
const edTitle = e.title || 'How we price a bathroom renovation'
|
||||
return {
|
||||
cr, s, nav, crumbs, who, ini, pf, dn, dnSave, rsNote, rsBtn,
|
||||
themeSeg: [['system','monitor','System'],['light','sun','Light'],['dark','moon','Dark']].map(([k,icon,tt])=>{const on=(s.mode||'light')===k;return {act:'theme-'+k,icon,t:tt,on,op:on?1:0}}), menuOpen: !!s.userMenu, deskMenu: !m && !!s.userMenu, mobMenu: m && !!s.userMenu, pfItemBg: 'var(--ui-bg-elevated)',
|
||||
langSeg: [['en','English'],['fr','Français']].map(([k,tt])=>{const on=(s.lang||'en')===k;return {act:'lang-'+k,code:k,t:tt,on,op:on?1:0}}), themeSeg: [['system','monitor','System'],['light','sun','Light'],['dark','moon','Dark']].map(([k,icon,tt])=>{const on=(s.mode||'light')===k;return {act:'theme-'+k,icon,t:tt,on,op:on?1:0}}), menuOpen: !!s.userMenu, deskMenu: !m && !!s.userMenu, mobMenu: m && !!s.userMenu, pfItemBg: 'var(--ui-bg-elevated)',
|
||||
chipBg: s.userMenu || s.nav === 'profile' ? 'var(--rc-sand)' : 'transparent', chipFg: s.userMenu || s.nav === 'profile' ? '#111111' : 'var(--ui-text-highlighted)',
|
||||
isSettings: k === 'settings', isProfile: k === 'profile', pfLoading: k === 'profile' && !!pf.loading, pfReady: k === 'profile' && !pf.loading,
|
||||
cardPad: m ? '16px' : '20px', cardPadX: m ? '16px' : '20px', inH: m ? '44px' : '40px', pfCols: m ? 'minmax(0,1fr)' : 'minmax(0,1fr) minmax(0,1.4fr)', pwDir: m ? 'column' : 'row', pwAlign: m ? 'stretch' : 'flex-end', edTitle, edBody: e.body || '', sampleBody: !e.body, tabs, rows, save, counter, pub, mFields, up, toasts, endpoints, toolbar,
|
||||
upBtnDir: m ? 'column' : 'row', upBtnAlign: m ? 'stretch' : 'flex-start', cardPad: m ? '16px' : '20px', cardPadX: m ? '16px' : '20px', inH: m ? '44px' : '40px', pfCols: m ? 'minmax(0,1fr)' : 'minmax(0,1fr) minmax(0,1.4fr)', pwDir: m ? 'column' : 'row', pwAlign: m ? 'stretch' : 'flex-end', edTitle, edBody: e.body || '', sampleBody: !e.body, tabs, rows, save, counter, pub, mFields, up, toasts, endpoints, toolbar,
|
||||
desk: !m, mob: m, notBoot: !s.boot,
|
||||
fw: m ? '390px' : '1440px', fh: m ? '844px' : '900px', dir: m ? 'column' : 'row',
|
||||
mLead: s.mLead || 'menu',
|
||||
isBoot: !!s.boot, isHome: k === 'home' && !s.boot, isList: k === 'articles', isEditor: k === 'editor', isInteg: k === 'integration', isError: k === 'error', isUsers: k === 'users',
|
||||
isBoot: !!s.boot, isHome: k === 'home' && !s.boot, isList: k === 'articles', isEditor: k === 'editor', isInteg: k === 'integration', isKeys: k === 'apikeys', isError: k === 'error', isUsers: k === 'users',
|
||||
usRows, usError: !!US.error, usOnly: !!US.only && !US.error, usTable: !m && !US.error, usCards: m && !US.error,
|
||||
pad: m ? '20px 16px 88px' : '32px', gap: m ? '20px' : '28px', cols3: m ? 'repeat(3,minmax(0,1fr))' : 'repeat(3,minmax(0,1fr))',
|
||||
btnH: m ? '44px' : '32px', rowH: m ? '52px' : '44px', inF: m ? '16px' : '14px',
|
||||
upBannerAlign: m ? 'stretch' : 'center', upCmdDir: m ? 'column' : 'row', btnH: m ? '44px' : '32px', rowH: m ? '52px' : '44px', inF: m ? '16px' : '14px',
|
||||
tbDir: m ? 'column' : 'row', tbGap: m ? '12px' : '16px', tbBorder: m ? '0' : '1px solid var(--ui-border)', tabBorder: m ? '1px solid var(--ui-border)' : '0', tabH: m ? '44px' : '36px', tabF: m ? '14px' : '13px',
|
||||
qText: L.q ? L.q : 'Search by title', qFg: L.q ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)',
|
||||
showTable: !m && !L.empty, showCards: m && !L.empty, listFab: !s.modal,
|
||||
|
||||
@@ -54,16 +54,17 @@
|
||||
<sc-if value="{{ hasFooter }}">
|
||||
<div style="width:{{ w }};max-width:100%;padding:{{ footPad }};display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;font-size:13px;color:var(--ui-text-muted)">
|
||||
<span style="display:flex;gap:6px;flex-wrap:wrap;align-items:center"><sc-if value="{{ s.footer }}"><span>{{ s.footer.pre }}</span><span data-act="footer" style="color:var(--ui-text-highlighted);font-weight:500;text-decoration:underline;text-underline-offset:3px">{{ s.footer.link }}</span></sc-if><sc-if value="{{ s.pending }}"><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;border:1px dashed var(--ui-border-accented);color:var(--ui-text-toned);font:500 11px 'IBM Plex Mono',monospace">API pending</span></sc-if></span>
|
||||
<span style="height:28px;padding:0 8px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned)"><span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/monitor.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/monitor.svg') center / contain no-repeat"></span>System</span>
|
||||
<span style="position:relative;display:flex;align-items:center;gap:8px"><sc-if value="{{ langOpen }}"><div role="menu" aria-label="Language" style="position:absolute;right:0;bottom:36px;z-index:10;width:168px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:4px"><sc-for list="{{ langSeg }}" as="m" hint-placeholder-count="2"><div data-act="{{ m.act }}" lang="{{ m.code }}" role="menuitemradio" aria-checked="{{ m.on }}" style="height:{{ optH }};padding:0 8px;display:flex;align-items:center;justify-content:space-between;font-size:14px;color:var(--ui-text-highlighted)">{{ m.t }}<span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;opacity:{{ m.op }};-webkit-mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat"></span></div></sc-for></div></sc-if><span data-act="langmenu" role="button" aria-haspopup="menu" aria-expanded="{{ langOpen }}" aria-label="Language: {{ langName }}" style="height:{{ chipH }};padding:0 8px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned);background:{{ langBg }}"><span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/languages.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/languages.svg') center / contain no-repeat"></span>{{ langName }}</span><span style="height:{{ chipH }};padding:0 8px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned)"><span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/monitor.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/monitor.svg') center / contain no-repeat"></span>System</span></span>
|
||||
</div>
|
||||
</sc-if>
|
||||
</div>
|
||||
</x-dc>
|
||||
<script type="text/x-dc" data-dc-script data-props="{"$preview":{"width":480,"height":620},"s":{"editor":null,"tsType":"object"},"mobile":{"editor":"boolean","default":false,"tsType":"boolean"}}">
|
||||
<script type="text/x-dc" data-dc-script data-props="{"$preview":{"width":480,"height":620},"s":{"editor":null,"tsType":"object"},"lang":{"editor":"enum","options":["en","fr"],"default":"en","tsType":"string"},"langOpen":{"editor":"boolean","default":false,"tsType":"boolean"},"mobile":{"editor":"boolean","default":false,"tsType":"boolean"}}">
|
||||
class Component extends DCLogic {
|
||||
renderVals() {
|
||||
const s = this.props.s || {}
|
||||
const m = !!this.props.mobile
|
||||
const lang = this.props.lang || s.lang || 'en'
|
||||
const tone = t => ({ bg: 'var(--rc-' + t + '-soft)', fg: 'var(--ui-' + t + ')' })
|
||||
const notice = s.notice ? { ...s.notice, ...tone(s.notice.tone) } : null
|
||||
const result = s.result ? { ...s.result, ...tone(s.result.tone), actions: (s.result.actions || []).map((a, i) => i === 0 && !a.secondary ? { act: 'result-' + i, t: a.t, bg: 'var(--ui-primary)', fg: 'var(--ui-bg)', bd: '1px solid var(--ui-primary)' } : { act: 'result-' + i, t: a.t, bg: 'var(--ui-bg)', fg: 'var(--ui-text-highlighted)', bd: '1px solid var(--ui-border-accented)' }) } : null
|
||||
@@ -87,7 +88,9 @@ class Component extends DCLogic {
|
||||
return {
|
||||
s, notice, result, fields,
|
||||
hasForm: fields.length > 0 && !!s.submit,
|
||||
hasFooter: !!(s.footer || s.pending || !m),
|
||||
hasFooter: true,
|
||||
langOpen: !!(this.props.langOpen ?? s.langOpen), langName: lang === 'fr' ? 'Français' : 'English', langBg: this.props.langOpen ?? s.langOpen ? 'var(--ui-bg-elevated)' : 'transparent', chipH: m ? '44px' : '28px', optH: m ? '44px' : '32px',
|
||||
langSeg: [['en','English'],['fr','Français']].map(([k,t]) => ({ act: 'lang-' + k, code: k, t, on: lang === k, op: lang === k ? 1 : 0 })),
|
||||
submitOpacity: s.submit && s.submit.disabled && !s.submit.loading ? '0.4' : '1',
|
||||
w: m ? '100%' : '400px',
|
||||
border: m ? '0' : '1px solid var(--ui-border)',
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<script src="./support.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<x-dc>
|
||||
<div ref="{{ rootRef }}" onScroll="{{ onScroll }}" style="position:absolute;inset:0;overflow-y:auto;overflow-x:hidden;scrollbar-width:thin;background:var(--ui-bg-muted);color:var(--ui-text);font-family:'IBM Plex Sans',sans-serif;font-size:13px;line-height:20px">
|
||||
<sc-if value="{{ mob }}">
|
||||
<div style="position:sticky;top:0;z-index:5;background:var(--ui-bg);border-bottom:1px solid var(--ui-border);padding:8px 16px;display:flex;flex-direction:column;gap:4px">
|
||||
<button aria-haspopup="listbox" aria-expanded="{{ jumpOpen }}" aria-label="Jump to section" onClick="{{ toggleJump }}" style="all:unset;box-sizing:border-box;cursor:pointer;height:44px;padding:0 12px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);font-size:14px" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:2px"><span style="color:var(--ui-text-muted)">Jump to</span><span style="flex:1;font-weight:500;color:var(--ui-text-highlighted)">{{ activeLabel }}</span><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:var(--ui-text-muted);-webkit-mask:url('https://api.iconify.design/lucide/chevrons-up-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevrons-up-down.svg') center / contain no-repeat"></span></button>
|
||||
<sc-if value="{{ jumpOpen }}"><div role="listbox" aria-label="Sections" style="position:absolute;left:16px;right:16px;top:56px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:4px">
|
||||
<sc-for list="{{ index }}" as="i" hint-placeholder-count="8"><button role="option" aria-selected="{{ i.on }}" onClick="{{ i.go }}" style="all:unset;box-sizing:border-box;cursor:pointer;width:100%;height:44px;padding:0 10px;display:flex;align-items:center;justify-content:space-between;font-size:14px;background:{{ i.bg }};color:var(--ui-text-highlighted);font-weight:{{ i.fw }}" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:-2px">{{ i.t }}<span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;opacity:{{ i.op }};-webkit-mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat"></span></button></sc-for>
|
||||
</div></sc-if>
|
||||
</div>
|
||||
</sc-if>
|
||||
<div style="position:relative;padding:{{ pad }};display:flex;gap:40px;align-items:flex-start">
|
||||
<div style="flex:1;min-width:0;display:flex;flex-direction:column;gap:{{ secGap }}">
|
||||
|
||||
<div style="display:flex;flex-direction:column;gap:6px">
|
||||
<span style="color:var(--ui-text-muted)">Integration</span>
|
||||
<span style="font:600 {{ h1 }} 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">API reference</span>
|
||||
<span style="color:var(--ui-text-muted);font-size:14px;line-height:22px">Everything a developer needs to build on RenewCMS.</span>
|
||||
</div>
|
||||
<p style="margin:0;font-size:14px;line-height:22px;color:var(--ui-text-toned);text-wrap:pretty;max-width:720px">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.</p>
|
||||
|
||||
<div style="display:flex;flex-direction:column;gap:6px">
|
||||
<span style="font-weight:500;color:var(--ui-text-highlighted)">Base URL</span>
|
||||
<div style="display:flex;border:1px solid var(--ui-border-accented);background:var(--ui-bg)"><span style="flex:1;min-width:0;height:40px;padding:0 12px;display:flex;align-items:center;font:400 13px 'IBM Plex Mono',monospace;overflow:hidden;white-space:nowrap">https://cms.renew.example</span>
|
||||
<button aria-label="Copy base URL" onClick="{{ copyBase }}" style="all:unset;box-sizing:border-box;cursor:pointer;height:40px;padding:0 12px;display:flex;align-items:center;gap:6px;border-left:1px solid var(--ui-border-accented);font-weight:500;color:{{ baseCopy.fg }}" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:-2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ baseCopy.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ baseCopy.icon }}.svg') center / contain no-repeat"></span><span aria-live="polite">{{ baseCopy.t }}</span></button></div>
|
||||
</div>
|
||||
|
||||
<section data-anchor="auth" aria-labelledby="h-auth" style="display:flex;flex-direction:column;gap:14px">
|
||||
<h2 id="h-auth" style="margin:0;font:600 18px/26px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Authentication</h2>
|
||||
<div style="display:grid;grid-template-columns:{{ authCols }};gap:12px;align-items:start">
|
||||
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:16px;display:flex;flex-direction:column;gap:10px">
|
||||
<div style="display:flex;align-items:center;gap:8px"><span style="font:600 15px/22px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Public</span><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned);font-size:12px">No key</span></div>
|
||||
<span style="color:var(--ui-text-toned);text-wrap:pretty">No key needed. Two read-only routes, and only online articles are returned.</span>
|
||||
<div style="display:flex;flex-direction:column;gap:6px;font:500 12px 'IBM Plex Mono',monospace;color:var(--ui-text-highlighted)"><span>GET /v1/article/</span><span>GET /v1/article/{id}</span></div>
|
||||
</div>
|
||||
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:16px;display:flex;flex-direction:column;gap:10px;min-width:0">
|
||||
<div style="display:flex;align-items:center;gap:8px"><span style="font:600 15px/22px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">API key</span><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;background:var(--rc-success-soft);color:var(--ui-success);font-size:12px;font-weight:500">Full access</span></div>
|
||||
<span style="color:var(--ui-text-toned);text-wrap:pretty">Send <code>Authorization: Bearer rcms_…</code>. 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.</span>
|
||||
<div style="border:1px solid var(--ui-border);min-width:0">
|
||||
<div role="tablist" aria-label="Example language" style="display:flex;gap:16px;padding:0 12px;border-bottom:1px solid var(--ui-border)"><sc-for list="{{ authTabs }}" as="t" hint-placeholder-count="2"><button role="tab" aria-selected="{{ t.on }}" onClick="{{ t.pick }}" style="all:unset;box-sizing:border-box;cursor:pointer;height:36px;display:flex;align-items:center;border-bottom:2px solid {{ t.bd }};margin-bottom:-1px;font-weight:500;color:{{ t.fg }}" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:-2px">{{ t.t }}</button></sc-for></div>
|
||||
<div style="background:var(--ui-bg-elevated)"><div style="height:32px;padding:0 4px 0 12px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--ui-border)"><span style="font:500 12px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">{{ authLang }}</span><button aria-label="Copy example" onClick="{{ copyAuth }}" style="all:unset;box-sizing:border-box;cursor:pointer;height:28px;padding:0 8px;display:flex;align-items:center;gap:6px;font-weight:500;color:{{ authCopy.fg }}" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:-2px"><span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ authCopy.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ authCopy.icon }}.svg') center / contain no-repeat"></span><span aria-live="polite">{{ authCopy.t }}</span></button></div>
|
||||
<pre tabindex="0" style="margin:0;padding:12px;overflow-x:auto;font:400 12px/19px 'IBM Plex Mono',monospace;color:var(--ui-text)">{{ authCode }}</pre></div>
|
||||
</div>
|
||||
<span style="color:var(--ui-text-muted);text-wrap:pretty">Keys start with <code>rcms_</code> and are shown in full once, when you create them.</span>
|
||||
<a href="#" style="align-self:flex-start;display:inline-flex;align-items:center;gap:6px;min-height:{{ linkH }};font-weight:500;color:var(--ui-text-highlighted)" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:2px">Manage API keys<span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/arrow-right.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/arrow-right.svg') center / contain no-repeat"></span></a>
|
||||
</div>
|
||||
</div>
|
||||
<div style="display:flex;flex-direction:column;gap:10px;font-size:14px;line-height:22px;color:var(--ui-text-toned)">
|
||||
<div style="display:flex;gap:10px"><span style="display:flex;padding-top:3px;color:var(--ui-info)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat"></span></span><span style="text-wrap:pretty">A key can't create, list or revoke API keys, log in, register, verify or reset a password, or call anything under <code>/v1/system</code>. 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.</span></div>
|
||||
<div style="display:flex;gap:10px"><span style="display:flex;padding-top:3px;color:var(--ui-info)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat"></span></span><span style="text-wrap:pretty">Each key can make 120 requests per minute. Beyond that the API answers 429 with a <code>Retry-After</code> header.</span></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<sc-for list="{{ groups }}" as="g" hint-placeholder-count="4">
|
||||
<section data-anchor="{{ g.key }}" style="display:flex;flex-direction:column;gap:10px">
|
||||
<div style="display:flex;align-items:baseline;gap:10px;flex-wrap:wrap"><h2 style="margin:0;font:600 18px/26px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ g.title }}</h2><span style="color:var(--ui-text-muted)">{{ g.count }}</span></div>
|
||||
<span style="color:var(--ui-text-toned);text-wrap:pretty">{{ g.desc }}</span>
|
||||
<div style="border:1px solid var(--ui-border);border-top:0;background:var(--ui-bg)">
|
||||
<sc-for list="{{ g.eps }}" as="ep" hint-placeholder-count="6">
|
||||
<div data-anchor="{{ ep.anchor }}" style="border-top:1px solid var(--ui-border)">
|
||||
<button aria-expanded="{{ ep.open }}" aria-label="{{ ep.label }}" onClick="{{ ep.toggle }}" style="all:unset;box-sizing:border-box;cursor:pointer;width:100%;display:{{ rowDisplay }};grid-template-columns:{{ rowCols }};flex-direction:column;align-items:{{ rowAlign }};gap:{{ rowGap }};padding:{{ rowPad }};min-height:44px;background:{{ ep.rowBg }}" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:-2px">
|
||||
<span style="display:flex;align-items:center;gap:10px;min-width:0"><span style="width:56px;height:22px;flex-shrink:0;display:inline-flex;align-items:center;justify-content:center;background:{{ ep.mBg }};color:{{ ep.mFg }};border:1px solid {{ ep.mBd }};font:500 11px 'IBM Plex Mono',monospace">{{ ep.m }}</span><span style="min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font:500 13px 'IBM Plex Mono',monospace;color:var(--ui-text-highlighted)">{{ ep.p }}</span><sc-if value="{{ mob }}"><span style="flex:1"></span><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;color:var(--ui-text-muted);background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ ep.chev }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ ep.chev }}.svg') center / contain no-repeat"></span></sc-if></span>
|
||||
<span style="min-width:0;color:var(--ui-text-toned);overflow:hidden;text-overflow:ellipsis;white-space:{{ descWrap }}">{{ ep.d }}</span>
|
||||
<span style="display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-start"><sc-for list="{{ ep.chips }}" as="c" hint-placeholder-count="2"><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;white-space:nowrap;background:{{ c.bg }};color:{{ c.fg }};border:1px {{ c.bs }} {{ c.bd }};font-size:12px;font-weight:{{ c.fw }}"><sc-if value="{{ c.icon }}"><span aria-hidden="true" style="display:inline-block;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ c.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ c.icon }}.svg') center / contain no-repeat"></span></sc-if>{{ c.t }}</span></sc-for></span>
|
||||
<sc-if value="{{ desk }}"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;color:var(--ui-text-muted);background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ ep.chev }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ ep.chev }}.svg') center / contain no-repeat"></span></sc-if>
|
||||
</button>
|
||||
<sc-if value="{{ ep.open }}">
|
||||
<div style="padding:4px {{ detX }} 16px;display:flex;flex-direction:column;gap:14px;border-top:1px solid var(--ui-border-muted)">
|
||||
<div style="padding-top:10px;display:flex;flex-direction:column;gap:6px"><span style="font-weight:600;color:var(--ui-text-highlighted)">{{ ep.bodyTitle }}</span>
|
||||
<sc-if value="{{ ep.hasFields }}"><div style="border:1px solid var(--ui-border)">
|
||||
<div style="display:grid;grid-template-columns:{{ fCols }};gap:4px 12px;padding:6px 10px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500"><span>Name</span><span>Type</span><span>Required</span><sc-if value="{{ desk }}"><span>Rule</span></sc-if></div>
|
||||
<sc-for list="{{ ep.fields }}" as="f" hint-placeholder-count="2"><div style="display:grid;grid-template-columns:{{ fCols }};gap:2px 12px;padding:8px 10px;border-top:1px solid var(--ui-border)"><span style="font:500 12px 'IBM Plex Mono',monospace;color:var(--ui-text-highlighted)">{{ f.n }}</span><span style="font:400 12px 'IBM Plex Mono',monospace;color:var(--ui-text-toned)">{{ f.t }}</span><span style="color:var(--ui-text-toned)">{{ f.req }}</span><span style="grid-column:{{ ruleCol }};color:var(--ui-text-toned);text-wrap:pretty">{{ f.rule }}</span></div></sc-for></div></sc-if>
|
||||
<sc-if value="{{ ep.noFields }}"><span style="color:var(--ui-text-muted)">No request body.</span></sc-if></div>
|
||||
<div style="border:1px solid var(--ui-border);min-width:0">
|
||||
<div role="tablist" aria-label="Example" style="display:flex;gap:16px;padding:0 12px;border-bottom:1px solid var(--ui-border)"><sc-for list="{{ ep.tabs }}" as="t" hint-placeholder-count="3"><button role="tab" aria-selected="{{ t.on }}" onClick="{{ t.pick }}" style="all:unset;box-sizing:border-box;cursor:pointer;height:{{ tabH }};display:flex;align-items:center;border-bottom:2px solid {{ t.bd }};margin-bottom:-1px;font-weight:500;color:{{ t.fg }}" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:-2px">{{ t.t }}</button></sc-for></div>
|
||||
<div style="background:var(--ui-bg-elevated)"><div style="height:32px;padding:0 4px 0 12px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--ui-border)"><span style="font:500 12px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">{{ ep.lang }}</span><button aria-label="{{ ep.copyLabel }}" onClick="{{ ep.copy }}" style="all:unset;box-sizing:border-box;cursor:pointer;height:28px;padding:0 8px;display:flex;align-items:center;gap:6px;font-weight:500;color:{{ ep.cFg }}" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:-2px"><span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ ep.cIcon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ ep.cIcon }}.svg') center / contain no-repeat"></span><span aria-live="polite">{{ ep.cT }}</span></button></div>
|
||||
<pre tabindex="0" style="margin:0;padding:12px;overflow-x:auto;font:400 12px/19px 'IBM Plex Mono',monospace;color:var(--ui-text)">{{ ep.code }}</pre></div>
|
||||
</div>
|
||||
<div style="display:flex;flex-direction:column;gap:6px"><span style="font-weight:600;color:var(--ui-text-highlighted)">Errors</span>
|
||||
<sc-for list="{{ ep.errs }}" as="e" hint-placeholder-count="2"><div title="{{ e.cap }}" style="display:flex;align-items:baseline;gap:10px"><span style="width:36px;height:20px;flex-shrink:0;display:inline-flex;align-items:center;justify-content:center;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned);font:500 11px 'IBM Plex Mono',monospace">{{ e.c }}</span><span style="min-width:0;color:var(--ui-text-toned);text-wrap:pretty">{{ e.cap }}</span></div></sc-for></div>
|
||||
</div>
|
||||
</sc-if>
|
||||
</div>
|
||||
</sc-for>
|
||||
</div>
|
||||
</section>
|
||||
</sc-for>
|
||||
|
||||
<section data-anchor="session" aria-labelledby="h-sess" style="display:flex;flex-direction:column;gap:10px">
|
||||
<div style="display:flex;align-items:baseline;gap:10px;flex-wrap:wrap"><h2 id="h-sess" style="margin:0;font:600 18px/26px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Session only</h2><span style="color:var(--ui-text-muted)">12 routes, not available to API keys</span></div>
|
||||
<div style="background:var(--ui-bg-muted);border:1px dashed var(--ui-border-accented)">
|
||||
<div style="display:flex;gap:10px;padding:12px 14px;color:var(--ui-text-toned);text-wrap:pretty"><span style="display:flex;padding-top:2px;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat"></span></span><span>These routes need a signed-in browser session. With an API key they answer 403 "This action needs a real session."</span></div>
|
||||
<sc-for list="{{ sessGroups }}" as="sg" hint-placeholder-count="3">
|
||||
<div style="border-top:1px dashed var(--ui-border-accented)">
|
||||
<div style="padding:8px 14px 4px;font-size:11px;font-weight:500;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">{{ sg.t }}</div>
|
||||
<sc-for list="{{ sg.rows }}" as="r" hint-placeholder-count="4"><div style="display:{{ rowDisplay }};grid-template-columns:{{ sessCols }};flex-direction:column;align-items:{{ rowAlign }};gap:{{ sessGap }};padding:{{ sessPad }};min-height:36px"><span style="display:flex;align-items:center;gap:10px;min-width:0"><span style="width:56px;flex-shrink:0;font:500 11px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">{{ r.m }}</span><span style="min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font:400 13px 'IBM Plex Mono',monospace;color:var(--ui-text-toned)">{{ r.p }}</span></span><span style="color:var(--ui-text-muted)">{{ r.d }}</span><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;align-self:{{ chipSelf }};border:1px dashed var(--ui-border-accented);color:var(--ui-text-muted);font-size:12px;white-space:nowrap"><span aria-hidden="true" style="display:inline-block;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat"></span>Session only</span></div></sc-for>
|
||||
</div>
|
||||
</sc-for>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section data-anchor="errors" aria-labelledby="h-err" style="display:flex;flex-direction:column;gap:10px">
|
||||
<h2 id="h-err" style="margin:0;font:600 18px/26px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Errors</h2>
|
||||
<span style="color:var(--ui-text-toned);text-wrap:pretty">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.</span>
|
||||
<div style="border:1px solid var(--ui-border);background:var(--ui-bg);overflow:hidden">
|
||||
<div style="display:grid;grid-template-columns:{{ errCols }};gap:12px;padding:8px 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500"><span>Status</span><span>Meaning</span><sc-if value="{{ desk }}"><span>Typical cause</span></sc-if></div>
|
||||
<sc-for list="{{ errRows }}" as="r" hint-placeholder-count="8"><div style="display:grid;grid-template-columns:{{ errCols }};gap:2px 12px;padding:10px 12px;border-top:1px solid var(--ui-border)"><span style="font:500 13px 'IBM Plex Mono',monospace;color:var(--ui-text-highlighted)">{{ r.c }}</span><span style="font-weight:500;color:var(--ui-text-highlighted)">{{ r.m }}</span><span style="grid-column:{{ errCause }};color:var(--ui-text-toned);text-wrap:pretty">{{ r.w }}</span></div></sc-for>
|
||||
</div>
|
||||
<div style="border:1px solid var(--ui-border);min-width:0"><div style="background:var(--ui-bg-elevated)"><div style="height:32px;padding:0 12px;display:flex;align-items:center;border-bottom:1px solid var(--ui-border);font:500 12px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">Error response · text/plain</div>
|
||||
<pre tabindex="0" style="margin:0;padding:12px;overflow-x:auto;font:400 12px/19px 'IBM Plex Mono',monospace;color:var(--ui-text)">{{ errBody }}</pre></div></div>
|
||||
</section>
|
||||
|
||||
<section data-anchor="notes" aria-labelledby="h-notes" style="display:flex;flex-direction:column;gap:10px">
|
||||
<h2 id="h-notes" style="margin:0;font:600 18px/26px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Notes</h2>
|
||||
<div style="display:flex;flex-direction:column;gap:10px;font-size:14px;line-height:22px;color:var(--ui-text-toned)">
|
||||
<div style="display:flex;gap:10px"><span style="display:flex;padding-top:3px;color:var(--ui-info)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat"></span></span><span style="text-wrap:pretty">Images in <code>body</code> use paths like <code>/static/uploadedImages/<uuid>.png</code>. Prefix them with the base URL before rendering.</span></div>
|
||||
<div style="display:flex;gap:10px"><span style="display:flex;padding-top:3px;color:var(--ui-info)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat"></span></span><span style="text-wrap:pretty">Browsers can only call the API from origins listed in the server's CORS setting. Ask whoever runs the server to add your site's address.</span></div>
|
||||
<div style="display:flex;gap:10px"><span style="display:flex;padding-top:3px;color:var(--ui-info)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat"></span></span><span style="text-wrap:pretty">Article routes accept <code>?format=markdown</code>, <code>?format=html</code> or <code>?format=json</code> to choose how <code>body</code> is returned. With <code>json</code>, <code>body</code> is the stored JSON structure. Articles have <code>body_format: markdown</code> by default.</span></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
</div>
|
||||
<sc-if value="{{ desk }}">
|
||||
<nav aria-label="On this page" style="position:sticky;top:32px;width:168px;flex-shrink:0;display:flex;flex-direction:column;gap:2px;border-left:1px solid var(--ui-border)">
|
||||
<span style="padding:0 12px 6px;font-size:11px;font-weight:500;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">On this page</span>
|
||||
<sc-for list="{{ index }}" as="i" hint-placeholder-count="8"><button aria-current="{{ i.cur }}" onClick="{{ i.go }}" style="all:unset;box-sizing:border-box;cursor:pointer;height:28px;padding:0 12px;margin-left:-1px;display:flex;align-items:center;border-left:2px solid {{ i.bd }};color:{{ i.fg }};font-weight:{{ i.fw }}" style-hover="color:var(--ui-text-highlighted)" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:-2px">{{ i.t }}</button></sc-for>
|
||||
</nav>
|
||||
</sc-if>
|
||||
</div>
|
||||
</div>
|
||||
</x-dc>
|
||||
<script type="text/x-dc" data-dc-script>
|
||||
class Component extends DCLogic {
|
||||
state = (() => { const i = (this.props.s && this.props.s.int) || {}; return { open: i.open ? { [i.open]: true } : {}, tab: i.open ? { [i.open]: i.tab || 'fetch' } : {}, copied: i.copied || null, jump: !!i.jump, active: i.scroll === 'ep-' + i.open ? 'media' : (i.scroll || 'auth'), authTab: i.authTab || 'curl' } })()
|
||||
rootRef = React.createRef()
|
||||
BASE = 'https://cms.renew.example'
|
||||
KEY = 'rcms_Kf3x9QwL0aBc…'
|
||||
IDX = [['auth', 'Authentication'], ['articles', 'Articles'], ['media', 'Media'], ['users', 'Users and invites'], ['settings', 'Settings'], ['session', 'Session only'], ['errors', 'Errors'], ['notes', 'Notes']]
|
||||
componentDidMount() {
|
||||
const i = (this.props.s && this.props.s.int) || {}
|
||||
const go = () => { if (i.scroll) this.scrollTo(i.scroll, !!this.props.mobile) }
|
||||
go(); setTimeout(go, 250); setTimeout(go, 900)
|
||||
if (document.fonts && document.fonts.ready) document.fonts.ready.then(go)
|
||||
}
|
||||
scrollTo(a, mob) {
|
||||
const r = this.rootRef.current; if (!r) return
|
||||
const el = r.querySelector('[data-anchor="' + a + '"]'); if (!el) return
|
||||
const off = a.indexOf('ep-') === 0 ? 24 : 0
|
||||
r.scrollTop = Math.max(0, this.yOf(el, r) - (mob ? 64 : 32) - off)
|
||||
}
|
||||
yOf(el, r) { const w = el.offsetParent; return el.offsetTop + (w && w !== r ? w.offsetTop : 0) }
|
||||
onScroll = () => {
|
||||
const r = this.rootRef.current; if (!r) return
|
||||
let cur = this.IDX[0][0]
|
||||
for (const [k] of this.IDX) { const el = r.querySelector('[data-anchor="' + k + '"]'); if (el && this.yOf(el, r) <= r.scrollTop + 120) cur = k }
|
||||
if (cur !== this.state.active) this.setState({ active: cur })
|
||||
}
|
||||
flash(k) {
|
||||
this.setState({ copied: k }); clearTimeout(this._t); this._t = setTimeout(() => this.setState({ copied: null }), 2000)
|
||||
}
|
||||
hl(code) {
|
||||
const re = /("[^"\n]*"|'[^'\n]*')|\b(const|await|fetch|curl|new)\b|\b(\d+)\b/g
|
||||
const out = []; let last = 0, m, k = 0
|
||||
while ((m = re.exec(code))) {
|
||||
if (m.index > last) out.push(code.slice(last, m.index))
|
||||
const c = m[1] ? 'var(--ui-success)' : m[2] ? 'var(--ui-info)' : 'var(--ui-warning)'
|
||||
out.push(React.createElement('span', { key: k++, style: { color: c } }, m[0])); last = m.index + m[0].length
|
||||
}
|
||||
out.push(code.slice(last)); return out
|
||||
}
|
||||
eps() {
|
||||
const A = (id, m, p, d, acc, key, errs, fields, x = {}) => ({ id, m, p, d, acc, key, errs: acc === 'Verified user' ? errs.flatMap(e => e[0] === 401 ? [e, e403] : [e]) : errs, fields, ...x })
|
||||
const S = (n, t, req, rule) => ({ n, t, req, rule })
|
||||
const e401 = [401, 'You must be logged in to access this resource.']
|
||||
const e403 = [403, 'You must verify your account to access this resource.']
|
||||
const e404 = [404, 'Article not found']
|
||||
const m404 = [404, 'Image not found']
|
||||
const i404 = [404, 'Invite not found']
|
||||
const mm = 'The request cannot be processed due to a mismatch in the format of the body.'
|
||||
const j = o => JSON.stringify(o, null, 2)
|
||||
const G = {
|
||||
articles: { title: 'Articles', desc: 'Read, write and publish articles. Titles can\'t be changed after creation.', eps: [
|
||||
A('art-list', 'GET', '/v1/article/', 'List articles. Anonymous callers get online articles only.', 'Public', 1, [e401], [], { pub: 1, r: j([{ id: 12, title: 'How we price a bathroom renovation', status: 'online' }]) }),
|
||||
A('art-get', 'GET', '/v1/article/{id}', 'Get one article. Drafts answer 404 to anonymous callers.', 'Public', 1, [e401, e404], [], { pub: 1, r: j({ id: 12, title: 'How we price a bathroom renovation', status: 'online', body: 'A bathroom renovation is priced by room size, plumbing changes and finish level.', body_format: 'markdown' }) }),
|
||||
A('art-create', 'POST', '/v1/article/', 'Create a draft article.', 'Verified user', 1, [[400, mm], e401], [S('title', 'string', 'Yes', '3 to 200 characters. Can\'t be changed later.'), S('body', 'string', 'Yes', 'Up to 10 000 characters.')], { body: { title: 'Choosing tiles for a small bathroom', body: 'Small rooms show every grout line.' }, r: j({ id: 13, status: 'draft' }) }),
|
||||
A('art-update', 'PATCH', '/v1/article/{id}', 'Update the body of an article.', 'Verified user', 1, [[400, mm], e401, e404], [S('body', 'string', 'Yes', 'Up to 10 000 characters.')], { body: { body: 'Updated text.' }, r: j({ id: 12, status: 'draft' }) }),
|
||||
A('art-pub', 'PATCH', '/v1/article/{id}/publish', 'Publish an article.', 'Verified user', 1, [e401, e404], [], { r: j({ id: 12, status: 'online' }) }),
|
||||
A('art-unpub', 'PATCH', '/v1/article/{id}/unpublish', 'Unpublish an article.', 'Verified user', 1, [e401, e404], [], { r: j({ id: 12, status: 'draft' }) }),
|
||||
A('art-del', 'DELETE', '/v1/article/{id}', 'Delete an article and its images.', 'Verified user', 1, [e401, e404], [], { r: '204 No Content' })
|
||||
] },
|
||||
media: { title: 'Media', desc: 'The image library. One image can be used in many articles.', eps: [
|
||||
A('med-list', 'GET', '/v1/media/', 'List images.', 'Verified user', 1, [e401], [], { r: j([{ id: 4, filename: 'north-wall.jpg', size: 3900000 }]) }),
|
||||
A('med-up', 'POST', '/v1/media/', 'Upload an image (multipart).', 'Verified user', 1, [[400, mm], e401, [413, 'The file is over 10 MB.'], [415, 'Not a PNG, JPEG, WEBP or SVG image.']], [S('file', 'file', 'Yes', 'PNG, JPEG, WEBP or SVG, up to 10 MB.')], { multi: true, form: [['file', '@north-wall.jpg']], r: j({ id: 4, filename: 'north-wall.jpg', url: '/static/uploadedImages/3f9c.jpg' }) }),
|
||||
A('med-ren', 'PATCH', '/v1/media/{id}', 'Rename an image. The URL stays the same.', 'Verified user', 1, [[400, mm], e401, m404], [S('filename', 'string', 'Yes', 'The new filename.')], { body: { filename: 'north-wall-01.jpg' }, r: j({ id: 4, filename: 'north-wall-01.jpg' }) }),
|
||||
A('med-del', 'DELETE', '/v1/media/{id}', 'Delete an image. Articles that use it show a broken image.', 'Verified user', 1, [e401, m404], [], { r: '204 No Content' }),
|
||||
A('med-merge', 'POST', '/v1/media/merge', 'Merge identical copies into one image.', 'Verified user', 1, [[400, mm], e401, [409, 'Some of the images to merge changed. Refresh and try again.']], [S('keep_id', 'number', 'Yes', 'Greater than 0. The image to keep.'), S('merge_ids', 'number[]', 'Yes', 'At least 1, each greater than 0. Identical copies to delete. Articles switch to the kept image.')], { body: { keep_id: 4, merge_ids: [9, 11] }, r: j({ merged: 2, articlesUpdated: 5 }) }),
|
||||
A('med-use', 'GET', '/v1/media/{id}/usage', 'List the articles that use an image.', 'Verified user', 1, [e401, m404], [], { r: j([{ id: 12, title: 'How we price a bathroom renovation', status: 'online' }]) })
|
||||
] },
|
||||
users: { title: 'Users and invites', desc: 'People who can sign in, and pending invitations.', eps: [
|
||||
A('usr-list', 'GET', '/v1/user/', 'List users and invites.', 'Verified user', 1, [e401], [], { r: j([{ email: 'marta@renew.example', role: 'owner', status: 'accepted' }]) }),
|
||||
A('usr-me', 'PATCH', '/v1/user/me', 'Update my profile.', 'Verified user', 1, [[400, mm], e401], [S('display_name', 'string', 'Yes', 'Up to 60 characters.')], { body: { display_name: 'Marta Alves' }, r: j({ display_name: 'Marta Alves' }) }),
|
||||
A('usr-inv', 'POST', '/v1/user/invite', 'Invite a user by email.', 'Verified user', 1, [[400, mm], e401, [409, 'This address already has an account.']], [S('email', 'string', 'Yes', 'A valid email address. The link expires after 3 days.')], { body: { email: 'lea.martin@renew.example' }, r: j({ id: 7, status: 'pending' }) }),
|
||||
A('usr-cancel', 'DELETE', '/v1/user/invite/{id}', 'Cancel a pending invite.', 'Verified user', 1, [e401, i404], [], { r: '204 No Content' }),
|
||||
A('usr-renew', 'POST', '/v1/user/invite/{id}/renew', 'Renew an expired invite.', 'Verified user', 1, [e401, i404], [], { r: j({ id: 7, status: 'pending' }) }),
|
||||
A('auth-me', 'GET', '/v1/auth/me', 'Get the current user. With a key, the key\'s owner.', 'Verified user', 1, [e401], [], { r: j({ username: 'marta', email: 'marta@renew.example', role: 'owner' }) })
|
||||
] },
|
||||
settings: { title: 'Settings', desc: 'Read the site settings.', eps: [
|
||||
A('set-get', 'GET', '/v1/settings', 'Get settings.', 'Verified user', 1, [e401], [], { r: j({ version: 'v2.2.0-beta' }) })
|
||||
] }
|
||||
}
|
||||
const MB = { GET: ['var(--ui-bg-inverted)', 'var(--ui-text-inverted)', 'var(--ui-bg-inverted)'], POST: ['var(--rc-success-soft)', 'var(--ui-success)', 'var(--ui-success)'], PATCH: ['var(--rc-warning-soft)', 'var(--ui-warning)', 'var(--ui-warning)'], DELETE: ['var(--rc-error-soft)', 'var(--ui-error)', 'var(--ui-error)'] }
|
||||
const mob = !!this.props.mobile
|
||||
return Object.keys(G).map(key => {
|
||||
const g = G[key]
|
||||
return { key, title: g.title, desc: g.desc, count: g.eps.length + (g.eps.length === 1 ? ' route' : ' routes'), eps: g.eps.map(e => {
|
||||
const open = !!this.state.open[e.id], tab = this.state.tab[e.id] || 'fetch', url = this.BASE + e.p.replace('{id}', '12')
|
||||
const hdr = e.pub ? [] : ['Authorization: Bearer ' + this.KEY]
|
||||
let curl = 'curl ' + (e.m === 'GET' ? '' : '-X ' + e.m + ' ') + '"' + url + '"'
|
||||
hdr.forEach(h => curl += ' \\\n -H "' + h + '"')
|
||||
if (e.body) curl += ' \\\n -H "Content-Type: application/json" \\\n -d \'' + JSON.stringify(e.body) + '\''
|
||||
if (e.form) e.form.forEach(f => curl += ' \\\n -F "' + f[0] + '=' + f[1] + '"')
|
||||
let fe = (e.form ? 'const form = new FormData()\n' + e.form.map(f => f[1][0] === '@' ? "form.append('file', file)" : "form.append('" + f[0] + "', '" + f[1] + "')").join('\n') + '\n\n' : '') + "const res = await fetch('" + url + "'"
|
||||
const opts = []
|
||||
if (e.m !== 'GET') opts.push("method: '" + e.m + "'")
|
||||
if (hdr.length || e.body) opts.push('headers: { ' + [hdr.length ? "Authorization: 'Bearer " + this.KEY + "'" : null, e.body ? "'Content-Type': 'application/json'" : null].filter(Boolean).join(', ') + ' }')
|
||||
if (e.body) opts.push('body: JSON.stringify(' + JSON.stringify(e.body) + ')')
|
||||
if (e.form) opts.push('body: form')
|
||||
fe += opts.length ? ', {\n ' + opts.join(',\n ') + '\n})' : ')'
|
||||
const code = tab === 'curl' ? curl : tab === 'fetch' ? fe : e.r
|
||||
const lang = tab === 'curl' ? 'Shell' : tab === 'fetch' ? 'JavaScript' : 'JSON'
|
||||
const cp = this.state.copied === e.id
|
||||
const chip = (t, o) => ({ t, bg: 'transparent', fg: 'var(--ui-text-toned)', bd: 'var(--ui-border-accented)', bs: 'solid', fw: 400, ...o })
|
||||
const chips = [chip(e.acc, e.acc === 'Owner only' ? { bg: 'var(--ui-bg-elevated)', fg: 'var(--ui-text-highlighted)', fw: 500 } : {}), chip('API key OK', { icon: 'check', bg: 'var(--rc-success-soft)', fg: 'var(--ui-success)', bd: 'transparent', fw: 500 })]
|
||||
return { anchor: 'ep-' + e.id, open, m: e.m, p: e.p, d: e.d, mBg: MB[e.m][0], mFg: MB[e.m][1], mBd: MB[e.m][2], chev: open ? 'chevron-up' : 'chevron-down', rowBg: open ? 'var(--ui-bg-muted)' : 'transparent', label: e.m + ' ' + e.p + '. ' + e.d, chips,
|
||||
toggle: () => this.setState(s => ({ open: { ...s.open, [e.id]: !s.open[e.id] } })),
|
||||
bodyTitle: e.multi ? 'Request body · multipart/form-data, 1 file field' : e.body ? 'Request body · JSON' : 'Request body', hasFields: e.fields.length > 0, noFields: e.fields.length === 0, fields: e.fields,
|
||||
tabs: ['fetch', 'curl', 'Response'].map(t => { const k = t === 'Response' ? 'response' : t, on = (k === tab) || (t === tab); return { t, on, bd: on ? 'var(--ui-primary)' : 'transparent', fg: on ? 'var(--ui-text-highlighted)' : 'var(--ui-text-toned)', pick: () => this.setState(s => ({ tab: { ...s.tab, [e.id]: k } })) } }),
|
||||
lang, code: this.hl(code), copyLabel: 'Copy ' + lang + ' example', cT: cp ? 'Copied' : 'Copy', cIcon: cp ? 'check' : 'copy', cFg: cp ? 'var(--ui-success)' : 'var(--ui-text-toned)',
|
||||
copy: () => { try { navigator.clipboard && navigator.clipboard.writeText(code) } catch (x) { } this.flash(e.id) },
|
||||
errs: e.errs.map(([c, cap]) => ({ c, cap })) }
|
||||
}) }
|
||||
})
|
||||
}
|
||||
renderVals() {
|
||||
const mob = !!this.props.mobile, st = this.state
|
||||
const code = {
|
||||
curl: 'curl "' + this.BASE + '/v1/auth/me" \\\n -H "Authorization: Bearer ' + this.KEY + '"',
|
||||
fetch: "const res = await fetch('" + this.BASE + "/v1/auth/me', {\n headers: { Authorization: 'Bearer " + this.KEY + "' }\n})\nconst me = await res.json()"
|
||||
}[st.authTab]
|
||||
const cp = k => ({ t: st.copied === k ? 'Copied' : 'Copy', icon: st.copied === k ? 'check' : 'copy', fg: st.copied === k ? 'var(--ui-success)' : 'var(--ui-text-toned)' })
|
||||
const bc = cp('base'); if (st.copied !== 'base') bc.fg = 'var(--ui-text-highlighted)'
|
||||
const index = this.IDX.map(([k, t]) => { const on = st.active === k; return { t, on, cur: on ? 'true' : undefined, bd: on ? 'var(--ui-primary)' : 'transparent', fg: on ? 'var(--ui-text-highlighted)' : 'var(--ui-text-toned)', fw: on ? 500 : 400, bg: on ? 'var(--ui-bg-elevated)' : 'transparent', op: on ? 1 : 0, go: () => { this.setState({ jump: false, active: k }); this.scrollTo(k, mob) } } })
|
||||
const sg = (t, rows) => ({ t, rows: rows.map(([m, p, d]) => ({ m, p, d })) })
|
||||
const D = (a) => 'rowDisplay'
|
||||
return {
|
||||
rootRef: this.rootRef, onScroll: this.onScroll, mob, desk: !mob, jumpOpen: st.jump, toggleJump: () => this.setState(s => ({ jump: !s.jump })),
|
||||
activeLabel: (this.IDX.find(x => x[0] === st.active) || this.IDX[0])[1], index,
|
||||
pad: mob ? '20px 16px 96px' : '32px', secGap: mob ? '28px' : '32px', h1: mob ? '20px/28px' : '28px/36px', detX: mob ? '12px' : '16px', linkH: mob ? '44px' : '28px', tabH: mob ? '44px' : '36px',
|
||||
authCols: mob ? 'minmax(0,1fr)' : 'minmax(0,5fr) minmax(0,7fr)',
|
||||
baseCopy: bc, copyBase: () => { try { navigator.clipboard && navigator.clipboard.writeText(this.BASE) } catch (x) { } this.flash('base') },
|
||||
authTabs: ['curl', 'fetch'].map(t => { const on = st.authTab === t; return { t, on, bd: on ? 'var(--ui-primary)' : 'transparent', fg: on ? 'var(--ui-text-highlighted)' : 'var(--ui-text-toned)', pick: () => this.setState({ authTab: t }) } }),
|
||||
authLang: st.authTab === 'curl' ? 'Shell' : 'JavaScript', authCode: this.hl(code), authCopy: cp('auth'), copyAuth: () => { try { navigator.clipboard && navigator.clipboard.writeText(code) } catch (x) { } this.flash('auth') },
|
||||
groups: this.eps(),
|
||||
rowDisplay: mob ? 'flex' : 'grid', rowCols: mob ? 'none' : '300px minmax(0,1fr) auto 16px', rowAlign: mob ? 'stretch' : 'center', rowGap: mob ? '6px' : '16px', rowPad: mob ? '12px 12px' : '0 16px', descWrap: mob ? 'normal' : 'nowrap',
|
||||
fCols: mob ? 'minmax(0,1fr) auto auto' : '120px 72px 72px minmax(0,1fr)', ruleCol: mob ? '1 / -1' : 'auto',
|
||||
sessGroups: [sg('System · owner only', [['GET', '/v1/system/update', 'Update status'], ['POST', '/v1/system/update/check', 'Check for update'], ['POST', '/v1/system/update/download', 'Download update'], ['POST', '/v1/system/update/restart', 'Restart']]), sg('Sign in and account', [['POST', '/v1/auth/login', 'Log in'], ['POST', '/v1/auth/logout', 'Log out'], ['POST', '/v1/auth/register', 'Register'], ['POST', '/v1/auth/verify', 'Verify email'], ['POST', '/v1/auth/password-reset', 'Reset password']]), sg('API key management', [['GET', '/v1/api-key', 'List keys'], ['POST', '/v1/api-key', 'Create a key'], ['DELETE', '/v1/api-key/{id}', 'Revoke a key']])],
|
||||
sessCols: mob ? 'none' : '280px minmax(0,1fr) auto', sessGap: mob ? '2px' : '16px', sessPad: mob ? '8px 14px' : '0 14px', chipSelf: mob ? 'flex-start' : 'center',
|
||||
errCols: mob ? '56px minmax(0,1fr)' : '64px 200px minmax(0,1fr)', errCause: mob ? '2' : 'auto',
|
||||
errRows: [
|
||||
{ c: 400, m: 'Bad request', w: '"The request cannot be processed due to a mismatch in the format of the body." or "The expiry must be a date in the future."' },
|
||||
{ c: 401, m: 'Unauthorized', w: '"You must be logged in to access this resource." Sent for an invalid, unknown, expired or revoked key, even on public routes, and for a key whose user was deleted or unverified.' },
|
||||
{ c: 403, m: 'Forbidden', w: '"This action needs a real session." (a session-only route called with a key), "Only the owner can do this." or "You must verify your account to access this resource."' },
|
||||
{ c: 404, m: 'Not found', w: '"Article not found", "Image not found", "Invite not found" or "API key not found". Drafts answer 404 to anonymous callers.' },
|
||||
{ c: 429, m: 'Too many requests', w: '"Too many requests. Please try again later." A per-key limit of 120 requests per minute also sends a Retry-After header.' },
|
||||
{ c: 500, m: 'Server error', w: '"Internal server error"' }
|
||||
],
|
||||
errBody: 'HTTP/1.1 403 Forbidden\nContent-Type: text/plain\n\nThis action needs a real session.'
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -46,7 +46,7 @@
|
||||
<main ref="{{ stageRef }}" style="flex:1;min-width:0;height:100vh;overflow:auto;display:flex;align-items:center;justify-content:center;padding:24px">
|
||||
<div style="flex-shrink:0;width:{{ boxW }};height:{{ boxH }};box-shadow:0 8px 40px rgb(0 0 0 / 0.15);overflow:hidden">
|
||||
<div onClick="{{ onStage }}" class="{{ hsClass }}" style="width:{{ devW }};height:{{ devH }};zoom:{{ zoom }};position:relative;overflow:hidden;background:var(--ui-bg-muted)">
|
||||
<sc-if value="{{ isAuth }}"><div style="width:100%;height:100%;overflow:hidden;background:{{ authBg }};padding-top:{{ authTop }};display:flex;flex-direction:column;align-items:center"><dc-import name="AuthCard" s="{{ authS }}" mobile="{{ mobile }}" hint-size="400px,520px"></dc-import></div></sc-if>
|
||||
<sc-if value="{{ isAuth }}"><div style="width:100%;height:100%;overflow:hidden;background:{{ authBg }};padding-top:{{ authTop }};display:flex;flex-direction:column;align-items:center"><dc-import name="AuthCard" lang="{{ lang }}" lang-open="{{ langOpen }}" s="{{ authS }}" mobile="{{ mobile }}" hint-size="400px,520px"></dc-import></div></sc-if>
|
||||
<sc-if value="{{ isApp }}"><dc-import name="AppFrame" s="{{ appS }}" mobile="{{ mobile }}" hint-size="100%,100%"></dc-import></sc-if>
|
||||
<sc-if value="{{ isEmail }}"><div style="width:100%;height:100%;display:flex;flex-direction:column;background:var(--ui-bg)"><div style="flex-shrink:0;padding:14px 20px;border-bottom:1px solid var(--ui-border);display:flex;flex-direction:column;gap:2px"><span style="font-weight:600;font-size:15px;color:var(--ui-text-highlighted)">{{ emailSubject }}</span><span style="color:var(--ui-text-muted)">From RenewCMS · to marta@renew.example</span></div><iframe title="Email" srcDoc="{{ emailHtml }}" style="flex:1;width:100%;border:0"></iframe></div></sc-if>
|
||||
<sc-if value="{{ mnav }}">
|
||||
@@ -187,6 +187,9 @@ class Component extends DCLogic {
|
||||
act(a) {
|
||||
const s = this.state
|
||||
if (a === 'usermenu') return this.setState({ userMenu: !s.userMenu })
|
||||
if (a === 'langmenu') return this.setState({ langOpen: !s.langOpen })
|
||||
if (a && a.startsWith('lang-')) return this.setState({ lang: a.slice(5), langOpen: false })
|
||||
if (s.langOpen) this.setState({ langOpen: false })
|
||||
if (a && a.startsWith('theme-')) return this.setState({ mode: a.slice(6) })
|
||||
if (s.userMenu) this.setState({ userMenu: false })
|
||||
if (a === 'pf-reset') return this.setState({ pfReset: 'sent' })
|
||||
@@ -428,8 +431,8 @@ class Component extends DCLogic {
|
||||
rootRef: this.rootRef, stageRef: this.stageRef,
|
||||
devices: devs, modes, flows, hint, tools,
|
||||
hs: s.hs, hsClass: s.hs ? 'hs' : '', hsJust: s.hs ? 'flex-end' : 'flex-start', hsBg: s.hs ? 'var(--ui-primary)' : 'var(--ui-bg-accented)', toggleHs: () => this.setState({ hs: !s.hs }),
|
||||
mobile, isAuth, isApp, isEmail,
|
||||
authS: isAuth ? this.authS() : {}, appS: isApp ? { ...this.appS(), userMenu: s.userMenu, mode: s.mode } : {},
|
||||
mobile, isAuth, isApp, isEmail, lang: s.lang || 'en', langOpen: !!s.langOpen,
|
||||
authS: isAuth ? this.authS() : {}, appS: isApp ? { ...this.appS(), userMenu: s.userMenu, mode: s.mode, lang: s.lang || 'en' } : {},
|
||||
authBg: mobile ? 'var(--ui-bg)' : 'var(--ui-bg-muted)', authTop: mobile ? '40px' : '108px',
|
||||
emailHtml: isEmail ? this.emailHtml() : '', emailSubject: s.email === 'reset' ? 'Reset your RenewCMS password' : 'Verify your RenewCMS account',
|
||||
devW: dw + 'px', devH: dh + 'px', zoom: s.zoom, boxW: Math.round(dw * s.zoom) + 'px', boxH: Math.round(dh * s.zoom) + 'px',
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<script src="./support.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<x-dc>
|
||||
<helmet>
|
||||
<meta name="design_doc_mode" content="canvas">
|
||||
<link rel="icon" href="brand/favicon.svg">
|
||||
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@400;500&family=Source+Serif+4:ital,opsz,wght@0,8..60,400;0,8..60,600;1,8..60,400&display=swap" rel="stylesheet">
|
||||
<style>body{margin:0;font-family:'IBM Plex Sans',sans-serif;font-size:13px;line-height:20px}*{box-sizing:border-box}a{color:inherit;text-underline-offset:3px}a:hover{opacity:.8}code{font-family:'IBM Plex Mono',monospace;font-size:12px}</style>
|
||||
</helmet>
|
||||
<div ref="{{ rootRef }}" data-screen-label="Back-office screens" style="--ui-bg:#ffffff;--ui-bg-muted:#fafafa;--ui-bg-elevated:#f3f2f0;--ui-bg-accented:#e6e4e0;--ui-bg-inverted:#111111;--ui-text-dimmed:#999999;--ui-text-muted:#666666;--ui-text-toned:#444444;--ui-text:#222222;--ui-text-highlighted:#111111;--ui-text-inverted:#ffffff;--ui-border:#e6e4e0;--ui-border-muted:#f3f2f0;--ui-border-accented:#8a8783;--ui-primary:#111111;--ui-secondary:#635643;--ui-success:#315b33;--ui-info:#34536d;--ui-warning:#6c4700;--ui-error:#882c21;--rc-sand:#e8dfd1;--rc-success-soft:#eaefea;--rc-info-soft:#ebeef0;--rc-warning-soft:#f0ede6;--rc-error-soft:#f3eae9;--rc-overlay:rgb(10 10 10 / 0.4);--rc-shadow-pop:0 4px 16px rgb(17 17 17 / 0.08), 0 1px 2px rgb(17 17 17 / 0.06);--rc-shadow-modal:0 16px 48px rgb(17 17 17 / 0.18);--rc-canvas:#ecebe8;background:var(--rc-canvas);color:var(--ui-text);padding:64px;display:flex;flex-direction:column;gap:72px;width:max-content;min-width:100%">
|
||||
|
||||
<div style="display:flex;align-items:flex-end;gap:32px;max-width:1400px">
|
||||
<div style="flex:1;display:flex;flex-direction:column;gap:10px">
|
||||
<h1 style="margin:0;font:600 36px/44px 'IBM Plex Sans',sans-serif;letter-spacing:-0.02em;color:var(--ui-text-highlighted)">Screen: API keys</h1>
|
||||
<p style="margin:0;max-width:880px;font-size:16px;line-height:26px;color:var(--ui-text-toned);text-wrap:pretty">The screen the Authentication section of <a href="RenewCMS Screens Back-office.dc.html">the Integration screen</a> links to. 1440 px at 50%, 390 px at 75%. The theme switch shows every state in dark mode.</p>
|
||||
</div>
|
||||
<div role="radiogroup" aria-label="Theme" style="display:flex;border:1px solid var(--ui-border-accented);background:var(--ui-bg)">
|
||||
<sc-for list="{{ modes }}" as="m" hint-placeholder-count="3">
|
||||
<button role="radio" aria-checked="{{ m.on }}" onClick="{{ m.pick }}" style="all:unset;cursor:pointer;height:36px;padding:0 14px;display:flex;align-items:center;font-weight:500;font-size:14px;background:{{ m.bg }};color:{{ m.fg }}" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:2px">{{ m.label }}</button>
|
||||
</sc-for>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<sc-for list="{{ groups }}" as="g" hint-placeholder-count="7">
|
||||
<section data-screen-label="{{ g.label }}" style="display:flex;flex-direction:column;gap:28px">
|
||||
<div style="display:flex;flex-direction:column;gap:6px;max-width:1100px">
|
||||
<h2 style="margin:0;font:600 28px/36px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ g.title }}</h2>
|
||||
<div style="display:flex;gap:16px;flex-wrap:wrap;font:400 14px/22px 'IBM Plex Mono',monospace;color:var(--ui-text-toned)"><span>{{ g.route }}</span><span style="color:var(--ui-text-muted)">{{ g.api }}</span></div>
|
||||
<sc-if value="{{ g.note }}"><p style="margin:4px 0 0;font-size:15px;line-height:24px;color:var(--ui-text-toned);text-wrap:pretty">{{ g.note }}</p></sc-if>
|
||||
</div>
|
||||
<div style="display:flex;flex-wrap:wrap;gap:40px;align-items:flex-start">
|
||||
<sc-for list="{{ g.states }}" as="st" hint-placeholder-count="4">
|
||||
<div style="display:flex;flex-direction:column;gap:12px">
|
||||
<div style="display:flex;flex-direction:column;gap:2px;max-width:1040px"><span style="font:600 16px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ st.name }}</span><span style="font-size:13px;color:var(--ui-text-muted)">{{ st.trigger }}</span></div>
|
||||
<div style="display:flex;gap:24px;align-items:flex-start">
|
||||
<div style="width:720px;height:450px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:1440px;height:900px;zoom:0.5"><sc-if value="{{ st.notMedia }}"><dc-import name="AppFrame" s="{{ st }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></sc-if><sc-if value="{{ st.isMedia }}"><dc-import name="MediaFrame" s="{{ st }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></sc-if></div></div>
|
||||
<div style="width:293px;height:633px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:390px;height:844px;zoom:0.75"><sc-if value="{{ st.notMedia }}"><dc-import name="AppFrame" s="{{ st.m }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></sc-if><sc-if value="{{ st.isMedia }}"><dc-import name="MediaFrame" s="{{ st.m }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></sc-if></div></div>
|
||||
</div>
|
||||
</div>
|
||||
</sc-for>
|
||||
</div>
|
||||
<sc-if value="{{ g.table }}"><div style="display:flex;flex-direction:column;gap:8px;max-width:1240px"><span style="font:600 16px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ g.tableTitle }}</span><div style="background:var(--ui-bg);border:1px solid var(--ui-border)"><div style="display:grid;grid-template-columns:90px 240px minmax(0,1fr);padding:8px 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500"><span>Status</span><span>Where</span><span>Copy</span></div><sc-for list="{{ g.table }}" as="r" hint-placeholder-count="3"><div style="display:grid;grid-template-columns:90px 240px minmax(0,1fr);gap:0;padding:10px 12px;border-top:1px solid var(--ui-border);line-height:20px"><span style="font:500 13px 'IBM Plex Mono',monospace;color:var(--ui-text-highlighted)">{{ r.a }}</span><span style="color:var(--ui-text-toned);padding-right:16px">{{ r.b }}</span><span style="color:var(--ui-text-highlighted);text-wrap:pretty">{{ r.c }}</span></div></sc-for></div></div></sc-if>
|
||||
</section>
|
||||
</sc-for>
|
||||
|
||||
</div>
|
||||
</x-dc>
|
||||
<script type="text/x-dc" data-dc-script data-props="{"theme":{"editor":"enum","options":["system","light","dark"],"default":"light","tsType":"'system' | 'light' | 'dark'"}}">
|
||||
class Component extends DCLogic {
|
||||
state = { mode: this.props.theme ?? 'light' }
|
||||
rootRef = React.createRef()
|
||||
light = { '--ui-bg': '#ffffff', '--ui-bg-muted': '#fafafa', '--ui-bg-elevated': '#f3f2f0', '--ui-bg-accented': '#e6e4e0', '--ui-bg-inverted': '#111111', '--ui-text-dimmed': '#999999', '--ui-text-muted': '#666666', '--ui-text-toned': '#444444', '--ui-text': '#222222', '--ui-text-highlighted': '#111111', '--ui-text-inverted': '#ffffff', '--ui-border': '#e6e4e0', '--ui-border-muted': '#f3f2f0', '--ui-border-accented': '#8a8783', '--ui-primary': '#111111', '--ui-secondary': '#635643', '--ui-success': '#315b33', '--ui-info': '#34536d', '--ui-warning': '#6c4700', '--ui-error': '#882c21', '--rc-sand': '#e8dfd1', '--rc-success-soft': '#eaefea', '--rc-info-soft': '#ebeef0', '--rc-warning-soft': '#f0ede6', '--rc-error-soft': '#f3eae9', '--rc-overlay': 'rgb(10 10 10 / 0.4)', '--rc-shadow-pop': '0 4px 16px rgb(17 17 17 / 0.08), 0 1px 2px rgb(17 17 17 / 0.06)', '--rc-shadow-modal': '0 16px 48px rgb(17 17 17 / 0.18)', '--rc-canvas': '#ecebe8' }
|
||||
dark = { '--ui-bg': '#111111', '--ui-bg-muted': '#0a0a0a', '--ui-bg-elevated': '#1a1a1a', '--ui-bg-accented': '#222222', '--ui-bg-inverted': '#fafafa', '--ui-text-dimmed': '#666666', '--ui-text-muted': '#999999', '--ui-text-toned': '#cfccc7', '--ui-text': '#e6e4e0', '--ui-text-highlighted': '#fafafa', '--ui-text-inverted': '#111111', '--ui-border': '#333333', '--ui-border-muted': '#222222', '--ui-border-accented': '#666666', '--ui-primary': '#fafafa', '--ui-secondary': '#d4c5b0', '--ui-success': '#a3caa3', '--ui-info': '#a5c2db', '--ui-warning': '#dfb67d', '--ui-error': '#fba394', '--rc-sand': '#d4c5b0', '--rc-success-soft': '#1f241f', '--rc-info-soft': '#202428', '--rc-warning-soft': '#2a251e', '--rc-error-soft': '#2c201f', '--rc-overlay': 'rgb(0 0 0 / 0.6)', '--rc-shadow-pop': '0 4px 16px rgb(0 0 0 / 0.5)', '--rc-shadow-modal': '0 16px 48px rgb(0 0 0 / 0.6)', '--rc-canvas': '#1c1c1c' }
|
||||
resolved() {
|
||||
if (this.state.mode === 'system') return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
|
||||
return this.state.mode
|
||||
}
|
||||
apply() {
|
||||
const el = this.rootRef.current
|
||||
if (!el) return
|
||||
const vars = this.resolved() === 'dark' ? this.dark : this.light
|
||||
for (const k in vars) el.style.setProperty(k, vars[k])
|
||||
document.body.style.background = vars['--rc-canvas']
|
||||
}
|
||||
componentDidMount() { this.apply() }
|
||||
componentDidUpdate(p) {
|
||||
if (p.theme !== this.props.theme && this.props.theme) this.setState({ mode: this.props.theme })
|
||||
this.apply()
|
||||
}
|
||||
groups() {
|
||||
const withM = (st, mo = {}) => ({ ...st, m: { ...st, ...mo } })
|
||||
return this.finish([
|
||||
{ label: 'API keys', title: 'API keys', route: '/integration/api-keys', api: 'GET /v1/api-key · POST /v1/api-key · DELETE /v1/api-key/{id} (session only)', note: 'Recommendation: place it under Integration, as a sub-page linked from the Authentication section and from the sidebar item. Keys exist to call the API, so they belong next to the reference. Settings is owner-only today, but admins can also create keys. The screen is session only: an API key cannot manage keys. Key name: required, up to 60 characters. Expiry: optional, in the future. A key is shown in full once; afterwards only its prefix is visible.', states: [
|
||||
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "Owner: list", trigger: "Owners see every user's keys and a \"Created by\" column. Expired keys keep their Revoke action.", ak: {"view":"owner"} }, { ak: {"view":"owner"} }),
|
||||
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "Admin: own keys only", trigger: "Admins see only the keys they created, with no \"Created by\" column.", ak: {"view":"admin"} }, { ak: {"view":"admin"} }),
|
||||
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "Loading", trigger: "The list request is in flight. Skeleton rows appear after 150 ms.", ak: {"state":"loading"} }, { ak: {"state":"loading"} }),
|
||||
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "Empty", trigger: "No keys yet.", ak: {"state":"empty"} }, { ak: {"state":"empty"} }),
|
||||
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "Error", trigger: "A 500 or network failure on the list request.", ak: {"state":"error"} }, { ak: {"state":"error"} }),
|
||||
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "Create key", trigger: "\"Create key\" in the page header, or the bottom action on mobile. Name is required and limited to 60 characters; expiry is optional.", ak: {"modal":"create"} }, { ak: {"modal":"create"} }),
|
||||
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "Create key: validation", trigger: "On submit or blur. Nothing is sent. The name is empty and the expiry is in the past.", ak: {"modal":"invalid"} }, { ak: {"modal":"invalid"} }),
|
||||
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "Create key: name too long", trigger: "Over 60 characters. Checked as you type.", ak: {"modal":"toolong"} }, { ak: {"modal":"toolong"} }),
|
||||
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "One-time reveal", trigger: "201: the full key is shown once. Closing the dialog discards it from the screen.", ak: {"modal":"reveal"} }, { ak: {"modal":"reveal"} }),
|
||||
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "One-time reveal: copied", trigger: "Copy was pressed. The button reads \"Copied\" for 2 s and this is announced.", ak: {"modal":"copied"} }, { ak: {"modal":"copied"} }),
|
||||
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "Revoke: confirm", trigger: "Revoke on an active or expired row.", ak: {"modal":"revoke"} }, { ak: {"modal":"revoke"} }),
|
||||
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "Revoked", trigger: "204: the key stays in the list, greyed, with no Revoke action. A toast confirms.", ak: {"revoked":1,"toast":1} }, { ak: {"revoked":1,"toast":1} })
|
||||
] }
|
||||
])
|
||||
}
|
||||
finish(gs) { return gs.map(g => ({ ...g, states: g.states.map(st => ({ notMedia: !st.isMedia, ...st, m: { ...st.m } })) })) }
|
||||
renderVals() {
|
||||
const modes = [['system', 'System'], ['light', 'Light'], ['dark', 'Dark']].map(([k, label]) => {
|
||||
const on = this.state.mode === k
|
||||
return { label, on, bg: on ? 'var(--ui-primary)' : 'transparent', fg: on ? 'var(--ui-bg)' : 'var(--ui-text-toned)', pick: () => this.setState({ mode: k }) }
|
||||
})
|
||||
return { rootRef: this.rootRef, modes, groups: this.groups() }
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -118,6 +118,18 @@ class Component extends DCLogic {
|
||||
const rowFail = { n: 'roof.png', sz: '1.4 MB', st: 'fail', im: 10 }
|
||||
const gone = [1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12]
|
||||
const pk = (o = {}, x = {}) => MS({ kind: 'picker', picker: true, pk: { tab: 'Library', ...o }, ...x })
|
||||
const TB = { neutral: 'var(--ui-bg-muted)', success: 'var(--rc-success-soft)', info: 'var(--rc-info-soft)', warning: 'var(--rc-warning-soft)', error: 'var(--rc-error-soft)' }
|
||||
const B = (t, kind, icon, dis) => ({ t, icon, bg: kind === 'primary' ? 'var(--ui-primary)' : 'var(--ui-bg)', fg: kind === 'primary' ? 'var(--ui-bg)' : 'var(--ui-text-highlighted)', bd: kind === 'primary' ? 'var(--ui-primary)' : 'var(--ui-border-accented)', op: dis ? '0.4' : '1' })
|
||||
const UPD = (o) => { const rdy = o.title === 'Version 2.3.0 is ready to install' && o.btns && o.btns.length; if (rdy) o = { ...o, tone: 'warning', icon: 'clock', pendingTag: true, inBtn: o.btns[0], btns: undefined }; const tone = o.tone || 'neutral'; return { v: 'v2.2.0-beta', focus: 'none', ...o, fg: tone === 'neutral' ? 'var(--ui-text-toned)' : 'var(--ui-' + tone + ')', bg: TB[tone], bar: o.pct !== undefined || !!o.indet, barW: o.indet ? '35%' : (o.pct || 0) + '%', barL: o.indet ? '30%' : '0', pct: o.indet ? undefined : o.pct } }
|
||||
const NOTES = (open) => ({ open, chev: open ? 'chevron-down' : 'chevron-right', ver: '2.3.0', date: 'Released 24 Sep 2026', items: [{ t: 'Images upload faster, and large images no longer stall.' }, { t: 'Fixed a problem where a draft could show an old title after saving.' }, { t: 'Small improvements to the Users page.' }] })
|
||||
const SU = (o, extra) => withM({ kind: 'settings', nav: 'settings', crumbs: ['Settings'], mTitle: 'Settings', ...extra, upd: UPD(o) })
|
||||
const LAST = 'Last checked today at 09:41'
|
||||
const RESTART_FOOT = 'Restart takes about 10 seconds. Your site is unavailable while it restarts.'
|
||||
const bn = (icon, title, text) => ({ icon, title, text, btn: 'Go to Settings', fg: 'var(--ui-info)', bg: 'var(--rc-info-soft)' })
|
||||
const cmdLine = 'renewcms enable-browser-updates'
|
||||
const notPrep = (copied) => ({ icon: 'info', tone: 'info', title: 'Version 2.3.0 is available', text: 'This site can\'t update itself from the browser yet. Whoever manages your server can set it up once, or update RenewCMS for you.', meta: LAST, cmd: { line: cmdLine, t: copied ? 'Copied' : 'Copy', icon: copied ? 'check' : 'copy', fg: copied ? 'var(--ui-success)' : 'var(--ui-text-highlighted)', note: 'They run this once on the server. After that, Update and Restart appear here.' }, link: 'How to update' })
|
||||
const restartModal = (o) => ({ title: 'Restart the site?', desc: 'Your site will be unavailable for about 10 seconds. This page reloads on its own when the site is back. Save anything you\'re editing first.', cancel: 'Cancel', confirm: 'Restart site', ...o })
|
||||
const installModal = (o) => ({ title: 'Restart to finish the update?', desc: 'RenewCMS will install version 2.3.0 and restart. Your site will be unavailable for about 10 seconds. This page reloads on its own when the site is back. Save anything you\'re editing first.', cancel: 'Restart later', confirm: 'Restart now', ...o })
|
||||
return this.finish([
|
||||
{ label: 'Boot', title: 'App boot', route: 'any route, first load', api: 'GET /v1/auth/me (pending)', note: 'While the session is checked, the shell renders with skeletons, never a spinner. The possible outcomes are: 200 with a verified user, which renders the route; 200 with an unverified user, which goes to /register/pending; and 401, which goes to /login?redirect=<path>. Public routes skip this check.', states: [
|
||||
withM({ ...home, name: 'Checking session', trigger: 'The first paint on any back-office URL, and usually visible for well under a second.', boot: true })
|
||||
@@ -126,7 +138,9 @@ class Component extends DCLogic {
|
||||
withM({ ...home, name: 'Default', trigger: 'The articles loaded.', home: { sub: 'Here\'s where things stand on your site.', stats, recent } }),
|
||||
withM({ ...home, name: 'Loading', trigger: 'The list request is in flight. Skeletons appear after 150 ms.', home: { sub: 'Here\'s where things stand on your site.', stats: stats.map(() => ({ skel: true })), recent: Array.from({ length: 5 }, () => ({ skel: true })) } }),
|
||||
withM({ ...home, name: 'Empty, first run', trigger: 'Zero articles: a single call to action, and no stats.', home: { sub: 'Welcome to RenewCMS.', empty: true } }),
|
||||
withM({ ...home, name: 'Error', trigger: 'A 500 or network failure on the list request.', home: { sub: 'Here\'s where things stand on your site.', error: true } })
|
||||
withM({ ...home, name: 'Error', trigger: 'A 500 or network failure on the list request.', home: { sub: 'Here\'s where things stand on your site.', error: true } }),
|
||||
withM({ ...home, navBadge: true, name: 'Update available (owner)', trigger: 'The owner only. A quiet banner above the content, and an "Update" pill on the Settings item (a dot on the menu icon on mobile, read as "Update available"). Dismissing hides the banner until the next version; the pill stays. Admins see neither.', home: { sub: 'Here\'s where things stand on your site.', stats, recent, banner: bn('circle-arrow-up', 'Version 2.3.0 is available', 'Update it from Settings. It takes about 2 minutes and the site stays online.') } }),
|
||||
withM({ ...home, navBadge: true, name: 'Update ready to install (owner)', trigger: 'The download is checked. The same banner changes its copy, and a dismiss comes back on the next visit because the update is waiting.', home: { sub: 'Here\'s where things stand on your site.', stats, recent, banner: bn('circle-check', 'Version 2.3.0 is ready to install', 'Restart from Settings to finish. The site is unavailable for about 10 seconds.') } })
|
||||
] },
|
||||
{ label: 'Articles', title: 'Articles', route: '/article', api: 'GET /v1/article/ · PATCH …/publish · PATCH …/unpublish · DELETE /v1/article/{id}', note: 'Rows update when the server responds, not optimistically. Search, tab and sort are stored in the query string.', states: [
|
||||
withM({ ...L(), name: 'Default', trigger: 'The list loaded, sorted by last updated.' }),
|
||||
@@ -251,9 +265,15 @@ class Component extends DCLogic {
|
||||
MS({ kind: 'picker', inArticle: true, picker: false, modal: { k: 'remove' }, name: 'Remove image: confirm', trigger: 'Remove image on an image in the article. It now only removes it from this article, and the copy says the file stays in the library. The confirm button is neutral, not red, because nothing is deleted. Title: "Remove this image from the article?"' }),
|
||||
MS({ kind: 'picker', name: 'Removed', trigger: 'Confirmed. The image leaves the article body, which now has unsaved changes.', toasts: [TT('success', 'circle-check', 'Image removed', 'It\'s still in your library.')] })
|
||||
] },
|
||||
{ label: 'Integration', title: 'Connect your website', route: '/integration', api: 'none (static)', note: 'Written for a developer. The base URL is window.location.origin.', states: [
|
||||
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: 'Default', trigger: 'Opened from the sidebar or the Home card.' }),
|
||||
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', copied: true, name: 'Copied', trigger: 'The base URL was copied. The button reads "Copied" for 2 s and this is announced.' })
|
||||
{ label: 'Integration', title: 'Integration: API reference', route: '/integration', api: 'none (static). Replaces "Connect your website".', note: 'Navigation: a sticky section index on the right on desktop, and a "Jump to" select on mobile. A long reference is read in one scroll and searched with the browser, so tabs would hide content and break find-in-page; the index keeps every group on one page, links to anchors and shows where you are. Written for a developer. The base URL is window.location.origin. The API keys screen has its own board.', states: [
|
||||
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: "1. Default", trigger: "Opened from the sidebar or the Home card. Every endpoint card is collapsed. Desktop shows the sticky index on the right; mobile shows the \"Jump to\" select above the content.", int: {} }, { int: {} }),
|
||||
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: "2. Group scrolled, one card expanded", trigger: "POST /v1/media/ opened in the Media group: multipart body with 1 file field, curl tab shown. Only one example block is visible per card. Other cards stay collapsed.", int: {"scroll":"media","open":"med-up","tab":"curl"} }, { int: {"scroll":"ep-med-up","open":"med-up","tab":"curl"} }),
|
||||
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: "3a. Copied: base URL", trigger: "The base URL was copied. The button reads \"Copied\" for 2 s and this is announced.", int: {"copied":"base"} }, { int: {"copied":"base"} }),
|
||||
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: "3b. Copied: CodeBlock", trigger: "The Copy button in the API key example after a click. Back to \"Copy\" after 2 s.", int: {"scroll":"auth","copied":"auth"} }, { int: {"scroll":"auth","copied":"auth"} }),
|
||||
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: "4. Authentication", trigger: "The API key card with its example, the \"Manage API keys\" link (goes to the API keys board) and the two notes.", int: {"scroll":"auth"} }, { int: {"scroll":"auth"} }),
|
||||
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: "5. Session only", trigger: "Routes API keys cannot call. Dashed, muted and locked, so they read as unavailable and not as an error.", int: {"scroll":"session"} }, { int: {"scroll":"session"} }),
|
||||
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: "6. Errors", trigger: "Status table and the plain-text error response (status line plus a one-sentence body). Key-specific causes are in the 401, 403 and 429 rows.", int: {"scroll":"errors"} }, { int: {"scroll":"errors"} }),
|
||||
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: "7. Navigation", trigger: "Desktop: the sticky index with the active item (Media). Mobile: the \"Jump to\" select open. Keyboard: the index buttons and the select are in the tab order, Enter jumps, Escape closes the list.", int: {"scroll":"media"} }, { int: {"scroll":"media","jump":true} })
|
||||
] },
|
||||
{ label: 'Users', title: 'Users', route: '/users', api: 'GET /v1/user/ · POST /v1/user/invite · DELETE /v1/user/invite/:id (pending) · POST /v1/user/invite/:id/renew (pending)', note: 'One shared workspace: every user sees the same articles and this same list. Columns: email, display name, role (owner or admin), invite status and created date. A pending invite can be cancelled and an expired one renewed; accepted accounts have no row actions. An invite is Pending until its link is used, Expired after 3 days, and Accepted once the account is created.', states: [
|
||||
withM({ ...U(), name: 'Default', trigger: 'The list loaded, newest first.' }),
|
||||
@@ -274,8 +294,50 @@ class Component extends DCLogic {
|
||||
withM({ ...U({ toasts: [T('error', 'circle-x', 'Couldn\'t renew the invite', 'Try again in a moment.')] }), name: 'Renew invite: failed', trigger: '500 or network failure. The row stays Expired and the button can be pressed again.' }),
|
||||
withM({ ...U({ users: { rows: [{ email: 'lea.martin@renew.example', role: 'admin', st: 'pending', c: 'Today', hl: true }, ...people] } , toasts: [T('success', 'circle-check', 'Invite sent', 'lea.martin@renew.example has 3 days to accept.')] }), name: 'Invite sent', trigger: '201: the dialog closes, the new invite appears at the top as Pending, and a toast confirms.' })
|
||||
] },
|
||||
{ label: 'Settings', title: 'Settings', route: '/settings', api: 'none (static)', note: 'Opened from the sidebar. For now it holds only the Version section.', states: [
|
||||
withM({ kind: 'settings', nav: 'settings', crumbs: ['Settings'], mTitle: 'Settings', name: 'Default', trigger: 'Opened from the sidebar.' })
|
||||
{ label: 'Settings', title: 'Settings: Updates', route: '/settings', api: 'GET /v1/system/update · POST …/check · POST …/download · POST …/update/restart (all pending)', note: 'New Updates card under Version, owner only. Update downloads and checks the new version and changes nothing. Restart installs it and restarts the site (about 10 seconds). "Restart later" is simply leaving the card or the dialog. A plain Restart shows only when no update is waiting. Admins see the version and a note. When the server isn\'t prepared, the card shows the notice and a "How to update" link with no buttons. Progress is a progressbar with a value, announced at 25% steps and when each step changes. The card is a polite live region. After the restart the page reloads, focus lands on the "Updates" heading, and a toast confirms. Buttons are disabled while any step runs, and any owner on any device sees the same state from the server. Cue elsewhere: see Home. Out of scope: choosing versions, downgrades, automatic updates, update history.', states: [
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'You\'re up to date', text: 'You have the latest version of RenewCMS.', meta: LAST, btns: [B('Check for updates', 'sec', 'refresh-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT }, { name: 'Up to date', trigger: 'Opened with no newer version. Restart is available but not emphasised.' }),
|
||||
SU({ icon: 'loader-circle', title: 'Checking for updates…', text: 'This usually takes a few seconds.', btns: [B('Checking…', 'sec', 'loader-circle', true)] }, { name: 'Checking', trigger: 'Check for updates pressed, or the first open after 24 hours. Announced as "Checking for updates". Buttons are disabled.' }),
|
||||
SU({ icon: 'wifi-off', tone: 'warning', title: 'Couldn\'t check for updates', text: 'RenewCMS couldn\'t reach the update server. Check your connection and try again. Your site isn\'t affected.', meta: 'Last checked yesterday at 18:12', btns: [B('Try again', 'primary', 'rotate-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT }, { name: 'Check failed', trigger: 'Offline, or the update server didn\'t answer (500, network). The last known result is kept.' }),
|
||||
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart.', meta: LAST, notes: NOTES(false), btns: [B('Update', 'primary', 'download')], hint: 'Takes about 2 minutes. Your site stays online.' }, { name: 'Update available', trigger: 'A newer version exists. Release notes are collapsed. Update is the one primary button.', navBadge: true }),
|
||||
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart.', meta: LAST, notes: NOTES(true), btns: [B('Update', 'primary', 'download')], hint: 'Takes about 2 minutes. Your site stays online.' }, { name: 'Update available, notes open', trigger: '"What\'s new in 2.3.0" expanded. It is a button with aria-expanded, and the list is plain text.', navBadge: true }),
|
||||
SU({ icon: 'download', tone: 'info', title: 'Downloading version 2.3.0…', text: 'You can leave this page. The download continues and your site stays online.', pct: 42, barLabel: 'Downloading version 2.3.0', barText: '42% · 11 of 26 MB', btns: [B('Updating…', 'sec', 'loader-circle', true)] }, { name: 'Downloading', trigger: 'Update pressed (202). Progress polls every second. Announced as "Downloading, 25 percent" and so on, never every tick.', navBadge: true }),
|
||||
SU({ icon: 'shield-check', tone: 'info', title: 'Checking the download…', text: 'Making sure the file is complete and safe to install. This takes a few seconds.', indet: true, barLabel: 'Checking the download', barText: 'Almost there', btns: [B('Updating…', 'sec', 'loader-circle', true)] }, { name: 'Verifying', trigger: 'The download finished. No percentage, so the bar is indeterminate. Announced as "Checking the download".', navBadge: true }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'Version 2.3.0 is ready to install', text: 'The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds.', meta: 'Nothing has changed yet.', notes: NOTES(false), btns: [B('Restart', 'primary', 'power')], hint: 'Not now? Leave this page. The update waits here, and the banner on Home reminds you.' }, { name: 'Ready to install', trigger: 'The file passed its checks. Restart becomes the primary action. "Restart later" is closing the dialog or leaving the page.', navBadge: true }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'Version 2.3.0 is ready to install', text: 'The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds.', meta: 'Nothing has changed yet.', btns: [B('Restart', 'primary', 'power')] }, { name: 'Restart: confirm', trigger: 'Restart pressed. Same dialog behaviour as the delete confirm: focus moves to the first button, Escape and "Restart later" close it, and focus returns to Restart. The confirm button is neutral, not red, because nothing is lost.', navBadge: true, modal: installModal() }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'Version 2.3.0 is ready to install', text: 'The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds.', meta: 'Nothing has changed yet.', btns: [B('Restart', 'primary', 'power')] }, { name: 'Restart: request failed', trigger: '500 or network failure before the restart began. The site is still running.', navBadge: true, modal: installModal({ notice: 'Couldn\'t start the restart. Nothing was changed and your site is still running. Try again in a moment.' }) }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'Version 2.3.0 is ready to install', text: '', btns: [] }, { name: 'Restarting to install', trigger: 'Full-page overlay, so it survives the server going away. The page polls until the site answers, then reloads. It is a live region announced once as "Installing version 2.3.0. Your site is restarting."', overlay: { title: 'Installing version 2.3.0', text: 'Your site is restarting with the new version. This takes about 10 seconds. This page reloads on its own when the site is back.', meta: 'Started at 09:51', barL: '30%' } }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: '', text: '', btns: [] }, { name: 'Restarting, taking longer', trigger: 'No answer after 60 seconds. The copy changes and a manual reload appears. The overlay stays until the site is back.', overlay: { title: 'Still restarting', text: 'This is taking longer than usual. Keep this page open. It reloads on its own when the site is back, or you can reload it now.', meta: 'Started at 09:51 · 1 minute ago', btn: 'Reload page', barL: '65%' } }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'You\'re on version 2.3.0', text: 'The update is installed and your site is running again.', meta: 'Updated today at 09:52', btns: [B('Check for updates', 'sec', 'refresh-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT, link: 'Read the release notes', v: 'v2.3.0', focus: '2px solid var(--ui-primary)', toasts: undefined }, { name: 'Update done', trigger: 'The page reloaded on the new version. Focus lands on the "Updates" heading (ring shown), the toast is announced, and the version updates.', toasts: [T('success', 'circle-check', 'Update installed', 'RenewCMS is now on version 2.3.0.')] }),
|
||||
SU({ icon: 'triangle-alert', tone: 'warning', title: 'The update didn\'t install', text: 'RenewCMS put the previous version back, so your site is running as before. Nothing was lost.', meta: 'What to do next: try again in a few minutes. If it fails again, ask whoever manages your server to check the update.', btns: [B('Try again', 'primary', 'rotate-cw')] }, { name: 'Update failed, rolled back', trigger: 'The site came back on v2.2.0-beta. The error toast stays until dismissed and the card keeps the explanation.', toasts: [T('error', 'circle-x', 'The update didn\'t install', 'Your site is back on v2.2.0-beta.')] }),
|
||||
SU({ icon: 'circle-x', tone: 'error', title: 'The download didn\'t finish', text: 'The connection dropped before the file was complete. Nothing was changed and your site is running as before.', btns: [B('Try again', 'primary', 'rotate-cw')] }, { name: 'Download failed', trigger: 'A 500, or the connection dropped. Focus moves to the card heading. Try again restarts the download.', navBadge: true }),
|
||||
SU({ icon: 'triangle-alert', tone: 'warning', title: 'We didn\'t use this update', text: 'The file didn\'t pass our safety check, so it was not installed. Nothing was changed. Try downloading it again. If this keeps happening, contact RenewCMS support.', btns: [B('Try again', 'primary', 'rotate-cw')] }, { name: 'Verification failed', trigger: 'The downloaded file isn\'t trusted. The tone is a warning, and the file is thrown away. Technical detail goes to the server log, not the screen.', navBadge: true }),
|
||||
SU({ icon: 'info', tone: 'info', title: 'Too many tries', text: 'Wait a moment before trying again.', btns: [B('Try again in 0:42', 'sec', 'clock', true)] }, { name: 'Too many requests (429)', trigger: 'Retry-After counted down in the button. It re-enables at zero.' }),
|
||||
SU(notPrep(false), { name: 'Not prepared', trigger: 'The server can\'t update from the browser. No buttons, not even Restart. The command is for the person who runs the server and is a single line. The placeholder command is subject to the real one.', navBadge: true }),
|
||||
SU(notPrep(true), { name: 'Not prepared: command copied', trigger: 'Copy pressed. The button reads "Copied" for 2 s and it is announced.', navBadge: true }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'You\'re up to date', text: 'You have the latest version of RenewCMS.', meta: LAST, btns: [B('Check for updates', 'sec', 'refresh-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT }, { name: 'Plain restart: confirm', trigger: 'Restart with no update waiting. Nothing is installed.', modal: restartModal() }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: '', text: '', btns: [] }, { name: 'Plain restart: restarting', trigger: 'Same overlay as the update restart with shorter copy.', overlay: { title: 'Restarting your site', text: 'This takes about 10 seconds. This page reloads on its own when the site is back.', meta: 'Started at 09:51', barL: '30%' } }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'Your site is back', text: '', btns: [] }, { name: 'Plain restart: done', trigger: 'The page reloaded. Focus lands on the "Updates" heading.', toasts: [T('success', 'circle-check', 'Site restarted', 'Your site is running again.')] }),
|
||||
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site.', meta: LAST }, { name: 'Admin view', trigger: 'Admins see the version and the note, with no buttons. Up to date: "You\'re up to date" and "Only the owner can update or restart the site." No Home banner or Settings pill.' }),
|
||||
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site.', meta: LAST }, { name: 'Role changed (403)', trigger: 'An owner was changed to admin while the page was open and pressed a button. The card reloads in the admin view.', toasts: [T('error', 'circle-x', 'Only the owner can do this', 'Ask the owner of this site to update RenewCMS.')] }),
|
||||
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart.', meta: LAST, btns: [B('Update', 'primary', 'download', true)] }, { name: 'Update already running (409)', trigger: 'Another owner started it. The card switches to that run\'s progress.', navBadge: true, toasts: [T('info', 'info', 'An update is already running', 'Another owner started it. Progress shows here.')] })
|
||||
], tableTitle: 'Status to copy', table: [
|
||||
{ a: '200', b: 'Check, up to date', c: '"You\'re up to date" / "You have the latest version of RenewCMS." / "Last checked today at 09:41"' },
|
||||
{ a: '200', b: 'Check, newer version', c: '"Version 2.3.0 is available" / "You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart."' },
|
||||
{ a: '202', b: 'Update, Restart', c: 'Accepted. The card switches to progress. Announced: "Downloading version 2.3.0, 25 percent".' },
|
||||
{ a: '200', b: 'Update finished', c: '"Version 2.3.0 is ready to install" / "The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds."' },
|
||||
{ a: '200', b: 'After restart', c: 'Toast: "Update installed" / "RenewCMS is now on version 2.3.0." Plain restart: "Site restarted" / "Your site is running again."' },
|
||||
{ a: '400', b: 'Update, nothing to install', c: 'Toast (info): "Nothing to update" / "You already have the latest version." The card refreshes.' },
|
||||
{ a: '401', b: 'Any call', c: 'Handled globally: /login?redirect=/settings&reason=expired. No local copy.' },
|
||||
{ a: '403', b: 'Any button, not the owner', c: 'Toast (error): "Only the owner can do this" / "Ask the owner of this site to update RenewCMS." The card reloads as the admin view. An unverified account is handled globally.' },
|
||||
{ a: '409', b: 'Update, Restart', c: 'Already running: toast (info) "An update is already running" / "Another owner started it. Progress shows here." Not prepared: the card shows the "Not prepared" state and "How to update".' },
|
||||
{ a: '422', b: 'Update, file not trusted', c: '"We didn\'t use this update" / "The file didn\'t pass our safety check, so it was not installed. Nothing was changed. Try downloading it again. If this keeps happening, contact RenewCMS support."' },
|
||||
{ a: '429', b: 'Check, Update', c: 'Card alert (info): "Too many tries" / "Wait a moment before trying again." Button reads "Try again in 0:42" and counts down.' },
|
||||
{ a: '500 / network', b: 'Check', c: '"Couldn\'t check for updates" / "RenewCMS couldn\'t reach the update server. Check your connection and try again. Your site isn\'t affected." with "Try again".' },
|
||||
{ a: '500 / network', b: 'Update', c: '"The download didn\'t finish" / "The connection dropped before the file was complete. Nothing was changed and your site is running as before." with "Try again".' },
|
||||
{ a: '500 / network', b: 'Restart dialog', c: '"Couldn\'t start the restart. Nothing was changed and your site is still running. Try again in a moment."' },
|
||||
{ a: 'Site back, old version', b: 'After restart', c: '"The update didn\'t install" / "RenewCMS put the previous version back, so your site is running as before. Nothing was lost." Next step: "try again in a few minutes. If it fails again, ask whoever manages your server to check the update."' },
|
||||
{ a: 'No answer, 60 s', b: 'Restart overlay', c: '"Still restarting" / "This is taking longer than usual. Keep this page open. It reloads on its own when the site is back, or you can reload it now."' },
|
||||
{ a: 'Offline', b: 'Whole page', c: 'Existing banner. Check, Update and Restart are disabled. During a restart, the overlay keeps polling and ignores the offline state.' }
|
||||
] },
|
||||
{ label: 'Profile', title: 'Profile', route: '/profile', api: 'GET /v1/auth/me · PATCH /v1/user/me (pending) · POST /v1/auth/password-reset', note: 'Opened from the account menu at the bottom of the sidebar. Username, email and password are read-only. The display name is optional, trimmed, and up to 60 characters. Once saved it replaces the username everywhere a person is named: the sidebar, the account menu, the Home greeting, the Users list (with the username beside it) and the emails RenewCMS sends, such as "Marta Alves invited you to RenewCMS". Saving it empty goes back to the username. The reset link uses the same flow as "Forgot password" and ends on the auth board\'s "Choose a new password" screen.', states: [
|
||||
withM({ ...home, home: { sub: 'Here\'s where things stand on your site.', stats, recent }, userMenu: true, name: 'Account menu', trigger: 'The account chip at the bottom of the sidebar. On mobile, the account row in the navigation drawer opens it as a sheet. Escape or a click outside closes it.' }),
|
||||
|
||||
+55
-3
@@ -134,8 +134,26 @@ Every state is drawn at desktop and mobile on the screen boards, with final copy
|
||||
| Media picker | `/article/:id/edit` | Inserted | Insert image from either tab | [media-picker](screens/media-picker.md) |
|
||||
| Media picker | `/article/:id/edit` | Remove image: confirm | Remove image on an image in the article | [media-picker](screens/media-picker.md) |
|
||||
| Media picker | `/article/:id/edit` | Removed | Confirmed | [media-picker](screens/media-picker.md) |
|
||||
| Integration | `/integration` | Default | Page load | [integration](screens/integration.md) |
|
||||
| Integration | `/integration` | Copied | Copy clicked (2 s) | [integration](screens/integration.md) |
|
||||
| Integration | `/integration` | Default | Page load, every endpoint card collapsed | [integration](screens/integration.md) |
|
||||
| Integration | `/integration` | Group scrolled, one card expanded | A card opened, one example visible | [integration](screens/integration.md) |
|
||||
| Integration | `/integration` | Copied: base URL | Copy clicked (2 s) | [integration](screens/integration.md) |
|
||||
| Integration | `/integration` | Copied: CodeBlock | Copy clicked in a code block (2 s) | [integration](screens/integration.md) |
|
||||
| Integration | `/integration` | Authentication | API key card, link and notes | [integration](screens/integration.md) |
|
||||
| Integration | `/integration` | Session only | Routes API keys cannot call | [integration](screens/integration.md) |
|
||||
| Integration | `/integration` | Errors | Status table and plain-text error shape | [integration](screens/integration.md) |
|
||||
| Integration | `/integration` | Navigation | Section index active item; mobile Jump to open | [integration](screens/integration.md) |
|
||||
| API keys | `/integration/api-keys` | Owner: list | Owner sees every key, with Created by | [integration-api-keys](screens/integration-api-keys.md) |
|
||||
| API keys | `/integration/api-keys` | Admin: own keys only | Admin sees only their own keys | [integration-api-keys](screens/integration-api-keys.md) |
|
||||
| API keys | `/integration/api-keys` | Loading | First load or retry | [integration-api-keys](screens/integration-api-keys.md) |
|
||||
| API keys | `/integration/api-keys` | Empty | No keys yet | [integration-api-keys](screens/integration-api-keys.md) |
|
||||
| API keys | `/integration/api-keys` | Error | 500 or network | [integration-api-keys](screens/integration-api-keys.md) |
|
||||
| API keys | `/integration/api-keys` | Create key | Modal opened | [integration-api-keys](screens/integration-api-keys.md) |
|
||||
| API keys | `/integration/api-keys` | Create key: validation | Name empty or expiry not in the future | [integration-api-keys](screens/integration-api-keys.md) |
|
||||
| API keys | `/integration/api-keys` | Create key: name too long | More than 60 characters | [integration-api-keys](screens/integration-api-keys.md) |
|
||||
| API keys | `/integration/api-keys` | One-time reveal | Key created, shown once | [integration-api-keys](screens/integration-api-keys.md) |
|
||||
| API keys | `/integration/api-keys` | One-time reveal: copied | Copy clicked (2 s) | [integration-api-keys](screens/integration-api-keys.md) |
|
||||
| API keys | `/integration/api-keys` | Revoke: confirm | Revoke pressed on a key | [integration-api-keys](screens/integration-api-keys.md) |
|
||||
| API keys | `/integration/api-keys` | Revoked | Confirmed, key stays listed as revoked | [integration-api-keys](screens/integration-api-keys.md) |
|
||||
| Users | `/users` | Default | List loaded, newest first | [users](screens/users.md) |
|
||||
| Users | `/users` | Loading | First load or retry | [users](screens/users.md) |
|
||||
| Users | `/users` | Only you | Nobody invited yet | [users](screens/users.md) |
|
||||
@@ -149,7 +167,33 @@ Every state is drawn at desktop and mobile on the screen boards, with final copy
|
||||
| Users | `/users` | Renew invite: sending | "Renew invite" on an Expired row; POST in flight | [users](screens/users.md) |
|
||||
| Users | `/users` | Renew invite: done | 200: row Pending on top, toast | [users](screens/users.md) |
|
||||
| Users | `/users` | Renew invite: failed | 500 or network: toast, row stays Expired | [users](screens/users.md) |
|
||||
| Settings | `/settings` | Default | Opened from the sidebar | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Up to date | Opened with no newer version | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Checking | Check for updates pressed, or the first open after 24 hours | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Check failed | Offline, or the update server didn't answer (500, network) | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Update available | A newer version exists | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Update available, notes open | "What's new in 2.3.0" expanded | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Downloading | Update pressed (202) | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Verifying | The download finished | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Ready to install | The file passed its checks | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Restart: confirm | Restart pressed | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Restart: request failed | 500 or network failure before the restart began | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Restarting to install | Full-page overlay, so it survives the server going away | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Restarting, taking longer | No answer after 60 seconds | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Update done | The page reloaded on the new version | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Update failed, rolled back | The site came back on v2.2.0-beta | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Download failed | A 500, or the connection dropped | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Verification failed | The downloaded file isn't trusted | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Too many requests (429) | Retry-After counted down in the button | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Not prepared | The server can't update from the browser | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Not prepared: command copied | Copy pressed | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Plain restart: confirm | Restart with no update waiting | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Plain restart: restarting | Same overlay as the update restart with shorter copy | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Plain restart: done | The page reloaded | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Admin view | Admins see the version and the note, with no buttons | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Role changed (403) | An owner was changed to admin while the page was open and pressed a button | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Update already running (409) | Another owner started it | [settings](screens/settings.md) |
|
||||
| Home | `/home` | Update available (owner) | Owner only: quiet banner and Settings pill | [home](screens/home.md) |
|
||||
| Home | `/home` | Update ready to install (owner) | Download checked: banner copy changes | [home](screens/home.md) |
|
||||
| Profile | `/profile` | Account menu | Account chip clicked | [profile](screens/profile.md) |
|
||||
| Profile | `/profile` | Loading | Opened by URL before /auth/me returns | [profile](screens/profile.md) |
|
||||
| Profile | `/profile` | Default, no display name | First visit | [profile](screens/profile.md) |
|
||||
@@ -220,6 +264,14 @@ Still not supported, so shown disabled or omitted:
|
||||
|
||||
Renaming a title (shown read-only, with an explanation in Details), resending the verification email (the pending page explains how to start over), changing the email or username, removing users, promoting or demoting anyone, and any role other than owner and admin. Changing the password while logged in works only through the emailed reset link on the Profile page.
|
||||
|
||||
Added by the Updates card, none of which exists yet (owner only unless noted, see [settings](screens/settings.md)):
|
||||
|
||||
- `GET /v1/system/update` (any verified user): `{ current, latest, available, notes: { version, released_at, items }, checked_at, can_apply, state, progress, error, started_at }`. `state` is `idle`, `downloading`, `verifying`, `ready`, `restarting`, `succeeded` or `failed`. `can_apply` is false when the server hasn't been prepared, or for admins.
|
||||
- `POST /v1/system/update/check`: asks the release feed. 200, 429 with `Retry-After`, 500 when the feed can't be reached.
|
||||
- `POST /v1/system/update/download`: 202 starts the download and verification, 400 when there is nothing to update, 403, 409 when one is already running or the server isn't prepared, 422 when the file fails verification, 429.
|
||||
- `POST /v1/system/update/restart`: 202 starts the install and restart (or only a restart when no update is ready), 403, 409, 500.
|
||||
- A restart must survive the server going away: the SPA polls `/healthz` and `GET /v1/system/update` until they answer.
|
||||
|
||||
Added by the Media screens, none of which exist yet:
|
||||
|
||||
- `GET /v1/media/?q=&filter=&sort=&limit=&cursor=&hash=`: the library, newest first by default. `hash` (SHA-256 hex) returns only the images with that content, which is how the browser checks for a duplicate before uploading. Each item carries `id`, `filename`, `url`, `size`, `content_type`, `width`, `height` (null for SVG), `uploaded_by`, `created_at`, `used_in` (count) and `duplicate` (bool). The response also carries the counts for the Unused and Duplicates tabs.
|
||||
|
||||
@@ -17,7 +17,7 @@ Rules: bullets are full sentences ending with a period; user-facing wording, no
|
||||
|
||||
## Published releases
|
||||
|
||||
Each body lives in `docs/releases/<tag>.md`. Publish with `tea releases create --tag <tag> --title "<name>" --note-file docs/releases/<tag>.md --prerelease --asset <binary>` (one `--asset` per binary), after `task release`.
|
||||
Each body lives in `docs/releases/<tag>.md`. Publish with `tea releases create --tag <tag> --title "<name>" --note-file docs/releases/<tag>.md --prerelease --asset <file>` after `task release`, with one `--asset` per file: the six binaries, `bin/checksums.txt` and `bin/checksums.txt.sig`. `task release` produces all eight and fails before building when the signing key is missing or wrong (see [deployment.md](deployment.md#release-signing-key-maintainers-once)). Never publish a release without the two checksum files.
|
||||
|
||||
| Tag | Name |
|
||||
| --- | --- |
|
||||
@@ -27,3 +27,7 @@ Each body lives in `docs/releases/<tag>.md`. Publish with `tea releases create -
|
||||
| `v2.3.0-beta` | v2.3.0-beta - Multi-user invitations, display names & profile page |
|
||||
| `v2.4.0-beta` | v2.4.0-beta - Owner role, invite management & Settings page |
|
||||
| `v2.5.0-beta` | v2.5.0-beta - Media library & image picker |
|
||||
| `v2.6.0-beta` | v2.6.0-beta - Signed updates and browser restart |
|
||||
| `v2.6.2-beta` | v2.6.2-beta - English and French interface |
|
||||
| `v2.7.0-beta` | v2.7.0-beta - Markdown and block article bodies |
|
||||
| `v2.8.0-beta` | v2.8.0-beta - API keys and API reference |
|
||||
@@ -0,0 +1,46 @@
|
||||
RenewCMS can now check for releases, download a signed update and install it from Settings. On Linux with systemd, the owner can restart the site from the browser, with automatic binary rollback if the new version fails to start.
|
||||
|
||||
## New
|
||||
|
||||
**Updates in Settings**
|
||||
- Owners can check for a newer release, read its release notes and download it while the site stays online.
|
||||
- Downloads show progress, verify the release signature and binary checksum, check the staged version and back up the database before becoming ready to install.
|
||||
- The Home page and Settings navigation show an owner-only update notification, and the Home banner can be dismissed for each version.
|
||||
- Admins can read the update status without starting an update or restart.
|
||||
|
||||
**Browser restart and installation**
|
||||
- Owners can confirm an update installation or a plain site restart from Settings.
|
||||
- A restart overlay waits for the site to return and offers a reload action when the restart takes longer than expected.
|
||||
- Linux installations with systemd can enable browser updates using `renewcms enable-browser-updates` and remove the helper using `renewcms disable-browser-updates`.
|
||||
- The helper verifies the staged files again, keeps the previous binary and restores it if the new version does not start successfully.
|
||||
|
||||
## Improvements and fixes
|
||||
- Update status and download progress survive navigation and are shared between owners.
|
||||
- Update checks and download starts have separate per-user rate limits with retry countdowns.
|
||||
- Restart confirmations identify whether the action installs an update or only restarts the site, and refuse a request when another owner's action has changed that state.
|
||||
- Completion messages are shown in the browser tab that requested the restart.
|
||||
|
||||
## API
|
||||
- `GET /v1/system/update` returns the current and latest versions, release notes, release URL, helper availability, progress, state, error kind and operation timestamps for verified users, without changing state.
|
||||
- `POST /v1/system/update/check` checks the release feed for owners and returns 200, 403 for insufficient permissions, 429 with `Retry-After`, or 500 when the feed cannot be reached.
|
||||
- `POST /v1/system/update/download` starts an owner-only background download with 202, or returns 400 when nothing is available, 403, 409 for an unavailable helper or conflicting job, 422 for a pre-flight refusal, or 429.
|
||||
- `POST /v1/system/update/restart` accepts an optional `kind` of `update` or `restart` and returns 202, 400 for invalid input, 403, 409 for an unavailable helper or conflicting state, or 500 when the request cannot be saved.
|
||||
|
||||
## Under the hood
|
||||
- Releases include signed `checksums.txt` and `checksums.txt.sig` files alongside the six platform binaries.
|
||||
- The update helper runs separately from the unprivileged app, copies staged files into a private directory and verifies the bytes it installs rather than trusting a mutable staged path.
|
||||
- Feature specifications, fake-backed Go tests and SPA tests cover release checks, downloads, restart requests and rollback decisions.
|
||||
|
||||
## Upgrading
|
||||
- Back up your SQLite database and uploads, then replace the binary and restart manually for this first release with browser-update support.
|
||||
- No database schema change is introduced by the update features.
|
||||
- `UPDATE_FEED_URL` is optional and defaults to the project's release feed; existing configuration remains usable.
|
||||
- On Linux with systemd, run `sudo renewcms enable-browser-updates` after the manual upgrade to enable future updates and restarts from Settings.
|
||||
- Keep the update status files, staged files and backups beside the database in the data directory, with the permissions described in `docs/deployment.md`.
|
||||
|
||||
## Known limitations
|
||||
- The privileged update helper has automated coverage through fakes, but its first real Linux/systemd update and rollback checks are still pending.
|
||||
- Browser installation and restart require Linux with systemd; Windows, macOS and other init systems remain manual upgrades.
|
||||
- Updating or restarting briefly takes the site offline, and a reverse proxy may return errors during that interval.
|
||||
- Automatic rollback restores the previous binary; it does not restore the database, so schema-changing upgrades still require a backup and a recovery plan.
|
||||
- Update assets and redirects must use HTTPS on the configured feed host.
|
||||
@@ -0,0 +1,29 @@
|
||||
This release adds English and French throughout the SPA, with an instant language switch and a preference remembered on this browser.
|
||||
|
||||
## New
|
||||
|
||||
**English and French interface**
|
||||
|
||||
- Choose English or Français from the Language control in the desktop or mobile profile submenu.
|
||||
- Switch interface language immediately while keeping your current page and unsaved work.
|
||||
- Keep your selected language after navigation, reload and logout, including on authentication screens.
|
||||
- See translated forms, validation, notifications, dialogs and accessibility labels, with localized dates, numbers and counts.
|
||||
|
||||
## Improvements and fixes
|
||||
|
||||
- Keep partial bulk-delete failure notifications available after retrying, including when switching languages.
|
||||
|
||||
## Under the hood
|
||||
|
||||
- Add translation catalog parity, fallback, persistence and SPA interaction tests.
|
||||
|
||||
## Upgrading
|
||||
|
||||
- Install the signed update through Settings on a prepared Linux/systemd installation, or replace the binary and restart the service.
|
||||
- No database migration or new environment variable is required.
|
||||
- English remains the default until a language is selected; the preference is stored locally in the browser.
|
||||
- User content, API data and transactional emails retain their existing language.
|
||||
|
||||
## Known limitations
|
||||
|
||||
- Visual parity checks for this feature were skipped under the accepted slice waiver.
|
||||
@@ -0,0 +1,35 @@
|
||||
This release lets your website read article bodies as markdown, HTML or structured blocks, and fixes text alignment in the editor.
|
||||
|
||||
## New
|
||||
|
||||
**Article body formats**
|
||||
|
||||
- Read an article body as markdown, HTML or a typed block array with the `format` query parameter, so a headless frontend can render it with markdown-it, comark or its own components.
|
||||
- Keep text alignment in every format: markdown wraps centered, right-aligned and justified blocks in a `div` with an inline style, and the block array carries an `align` field.
|
||||
- Keep plain text plain: text that merely looks like markdown, such as `# not a heading` or `- not a list`, is escaped in the markdown output.
|
||||
- See the Integration page snippets and [the article API reference](../api/articles.md) for the full contract.
|
||||
|
||||
## Improvements and fixes
|
||||
|
||||
- Fix the text alignment buttons in the article editor, which were disabled and showed a blocked cursor. Paragraphs and headings can be aligned left, center, right or justified again, and unaligned text stays free of inline styles.
|
||||
- The web interface requests HTML explicitly when it loads, saves, publishes, unpublishes or creates an article, so the editor and the image counts behave exactly as before.
|
||||
|
||||
## API
|
||||
|
||||
- Changed: `GET /v1/article/`, `GET /v1/article/{id}`, `POST /v1/article/`, `PATCH /v1/article/{id}`, `PATCH /v1/article/{id}/publish` and `PATCH /v1/article/{id}/unpublish` now return `body` as markdown by default. Pass `?format=html` to keep the previous HTML body.
|
||||
- Every article object now includes `body_format` (`markdown`, `html` or `json`), which names the format of `body`.
|
||||
- `?format=json` on the same routes returns `body` as a JSON array of typed blocks instead of a string.
|
||||
- An unsupported `format` answers `400` before anything is read or written.
|
||||
- Storage and the request bodies of `POST` and `PATCH` stay HTML.
|
||||
|
||||
## Under the hood
|
||||
|
||||
- Add the article body renderer port in the domain, with a markdown and JSON block adapter, and tests for every supported element.
|
||||
- Update `golang.org/x/crypto` to v0.57.0 and add `golang.org/x/net` as a direct dependency for HTML parsing.
|
||||
- Add `@tiptap/extension-text-align` to the web interface.
|
||||
|
||||
## Upgrading
|
||||
|
||||
- Replace the binary. No database migration or new environment variable is required.
|
||||
- Clients that read an article `body` as HTML must add `?format=html` to their article requests, because the default is now markdown.
|
||||
- A markdown renderer needs raw HTML enabled for text alignment to show, for example `html: true` in markdown-it.
|
||||
@@ -0,0 +1,41 @@
|
||||
This release adds API keys, so a script or service can use the whole API without the web interface, and turns the Integration page into a complete API reference.
|
||||
|
||||
## New
|
||||
|
||||
**API keys**
|
||||
|
||||
- Create named API keys from the new API keys screen under Integration, with an optional expiry date. The full key is shown once, when you create it, and only its prefix is visible afterwards.
|
||||
- Send a key as `Authorization: Bearer rcms_...` to manage articles, media, users and invites, and to read settings. A key acts with exactly the rights of the user who created it, so an admin's key cannot do owner-only things.
|
||||
- Revoke a key at any time. Active, expired and revoked keys all stay listed with their status, creation date and last use.
|
||||
- The owner sees every key and who created it. Admins see only their own.
|
||||
- Each key is limited to 120 requests per minute.
|
||||
- Resetting a user's password revokes all of that user's keys.
|
||||
|
||||
**API reference**
|
||||
|
||||
- The Integration page now documents every route a developer can call, grouped by area: articles, media, users and invites, and settings. Each endpoint lists who can call it, its request body, ready-to-copy fetch and curl examples, a sample response and its error statuses.
|
||||
- A new Authentication section explains public access and API keys, and a section index lets you jump between groups.
|
||||
- Routes that need a signed-in browser session are listed separately, and the page shows the real error messages the API returns.
|
||||
- The Integration page and the API keys screen are available in English and French.
|
||||
|
||||
## API
|
||||
|
||||
- `POST /v1/api-key` creates a key. It answers `201` with the key, shown once.
|
||||
- `GET /v1/api-key` lists keys, newest first, each with a `status` of `active`, `expired` or `revoked`. For the owner, each entry also carries `created_by_name`.
|
||||
- `DELETE /v1/api-key/{id}` revokes a key and answers `204`, also when the key is already revoked.
|
||||
- An invalid, unknown, expired or revoked key answers `401` on every route, including public ones, and is never treated as anonymous.
|
||||
- A key calling a session-only route answers `403` with "This action needs a real session." These routes are `/v1/api-key`, `POST /v1/auth/verify`, `DELETE /v1/auth/register` and everything under `/v1/system`.
|
||||
- `GET /v1/auth/me` accepts an API key, so a client can check who a key belongs to.
|
||||
- A key beyond 120 requests per minute gets `429` with a `Retry-After` header.
|
||||
- Cross-origin requests now allow the `PATCH` method.
|
||||
|
||||
## Under the hood
|
||||
|
||||
- Add the API key domain, use cases, SQLite repository and an authentication middleware that runs after each token verifier. Keys are generated by a new domain interface and stored as SHA-256 hashes, never in clear.
|
||||
- Add a typed API catalogue that drives the Integration page, with a test that every route has a description.
|
||||
- Add the API keys and Integration specifications and QA procedures to `features/`, and the API key reference to `docs/api/`.
|
||||
|
||||
## Upgrading
|
||||
|
||||
- Replace the binary. The new API keys table is created automatically at startup. No new environment variable is required.
|
||||
- Browsers calling the API from another origin can now use `PATCH`. Check your CORS configuration only if you restricted methods in a reverse proxy.
|
||||
@@ -0,0 +1,457 @@
|
||||
Feature: Developers authenticate against /v1 with named API keys instead of the jwt cookie
|
||||
|
||||
As a developer integrating with RenewCMS
|
||||
I want to create named API keys and send them as a Bearer token
|
||||
So that I can manage articles, media and users without the UI, with exactly the rights of the
|
||||
user who created the key and never more
|
||||
|
||||
Background:
|
||||
Given internal/domain/apikey defines the entity APIKey with ID uint32, UserID uint32, Name,
|
||||
Prefix, HashedKey, ExpiresAt *time.Time, RevokedAt *time.Time, LastUsedAt *time.Time and
|
||||
CreatedAt, with snake_case json tags
|
||||
And internal/domain/apikey defines the sentinels apikey.ErrAPIKeyNotFound,
|
||||
apikey.ErrAPIKeyInvalid and apikey.ErrExpiryNotInFuture
|
||||
And apikey.ErrAPIKeyInvalid covers an unknown, malformed, expired or revoked key and a key
|
||||
whose user is deleted or unverified
|
||||
And internal/domain/apikey defines the interface Repository with Create, Get(id),
|
||||
GetByHashedKey(hashedKey), ListByUser(userId), ListAll(), Revoke(id, at),
|
||||
RevokeAllByUser(userId, at) and TouchLastUsed(id, at)
|
||||
And RevokeAllByUser sets RevokedAt to at on every key of that user that is not yet revoked and
|
||||
leaves the RevokedAt of already revoked keys and every other user's keys untouched
|
||||
And internal/domain/apikey defines the interface KeyGenerator with Generate() returning the
|
||||
raw key, its display prefix and its SHA-256 hash, and Hash(rawKey) returning the SHA-256 hash
|
||||
And internal/infrastructure/hashing implements KeyGenerator, asserted with
|
||||
var _ apikey.KeyGenerator = &SHA256KeyGenerator{}
|
||||
And a generated raw key is "rcms_" followed by the base64url encoding, without padding, of 32
|
||||
random bytes, so it matches ^rcms_[A-Za-z0-9_-]{43}$
|
||||
And the display prefix is the first 12 characters of the raw key
|
||||
And only the SHA-256 hash and the prefix are persisted, never the raw key
|
||||
And the use cases CreateAPIKey, ListAPIKeys, RevokeAPIKey and AuthenticateAPIKey depend only
|
||||
on apikey.Repository, apikey.KeyGenerator, user.Repository and an injected clock
|
||||
And ResetPasswordUseCase additionally receives apikey.Repository and an injected clock, and
|
||||
after a successful password reset calls RevokeAllByUser(userId, now); it never reaches
|
||||
persistence directly
|
||||
And persistence has a GORM model, a mapper and a repository for the entity, the model is
|
||||
added to the AutoMigrate list in api/dependecyInjection.go, and wiring happens only in
|
||||
api/dependecyInjection.go
|
||||
And a new middleware resolves "Authorization: Bearer rcms_<...>" to a user and places a jwt in
|
||||
the same jwtauth request context the cookie path fills, with the claims user_id and
|
||||
token_version taken from the user's current record
|
||||
And that middleware runs after jwtauth.Verifier and ahead of jwtauth.Authenticator on the
|
||||
/article routes (public and protected), /user, /media, /settings and GET /auth/me
|
||||
And jwtauth.Authenticator, RequireCurrentToken, RequireVerifiedUser, RequireOwner and every
|
||||
handler stay unchanged
|
||||
And a new middleware RequireSession, mounted ahead of jwtauth.Verifier, answers 403 with
|
||||
apperr.SessionRequiredErrorMessage whenever the Authorization header is a Bearer token that
|
||||
starts with "rcms_", whether that key is valid, expired, revoked, unknown or garbage
|
||||
And RequireSession is mounted on the key management routes POST /v1/api-key, GET /v1/api-key
|
||||
and DELETE /v1/api-key/{id}, on the session-only auth routes POST /v1/auth/verify and
|
||||
DELETE /v1/auth/register, and on every /v1/system route (all under /v1/system/update)
|
||||
And a request on those routes without a "Bearer rcms_" header passes through RequireSession
|
||||
unchanged, so cookie-only and jwt-Bearer behaviour there does not change
|
||||
And the public auth routes login, register, registration, logout, password-reset,
|
||||
password-reset/confirm, invite and invite/accept do not use the key middleware or
|
||||
RequireSession and behave exactly as they do without a key header
|
||||
And the routes are mounted under /v1 inside the jwtauth.Verifier, jwtauth.Authenticator,
|
||||
RequireCurrentToken and RequireVerifiedUser group:
|
||||
POST /v1/api-key, GET /v1/api-key and DELETE /v1/api-key/{id}
|
||||
And a Bearer key on a key-accepting route that cannot authenticate gets 401 with
|
||||
apperr.UnauthorizedErrorMessage, and a request without an rcms_ key keeps the existing
|
||||
jwtauth.Authenticator response, status 401, unchanged by this feature
|
||||
And new apperr strings: APIKeyNotFoundErrorMessage = "API key not found",
|
||||
APIKeyExpiryErrorMessage = "The expiry must be a date in the future." and
|
||||
SessionRequiredErrorMessage = "This action needs a real session."
|
||||
And the per-key rate limit is 120 requests per minute, as constants in api/router.go
|
||||
And enableCorsIfConfigured allows the methods GET, POST, PUT, PATCH, DELETE and OPTIONS
|
||||
And users: owner id 1 "marta" (verified), admin id 2 "dev" (verified), admin id 3 "pat"
|
||||
(verified), unverified id 4 "quinn"
|
||||
|
||||
Scenario: Creating a key returns the full key exactly once
|
||||
Given a valid jwt cookie for admin 2
|
||||
When the client sends POST /v1/api-key with body {"name": "ci-deploy"}
|
||||
Then the response status is 201
|
||||
And the header Cache-Control is "no-store"
|
||||
And the body has exactly the keys id, name, prefix, key, created_at, expires_at
|
||||
And name is "ci-deploy", expires_at is null, and key matches ^rcms_[A-Za-z0-9_-]{43}$
|
||||
And prefix equals the first 12 characters of key
|
||||
And the stored record has user_id 2 and HashedKey equal to the SHA-256 of key
|
||||
And neither the raw key nor the stored hash appears in any later response
|
||||
|
||||
Scenario: The key can't be retrieved afterwards
|
||||
Given admin 2 created the key "ci-deploy" and holds its raw key
|
||||
When the same jwt cookie sends GET /v1/api-key
|
||||
Then the response status is 200
|
||||
And the body is a JSON array with one entry whose keys are exactly id, user_id, name, prefix,
|
||||
status, created_at, last_used_at, expires_at, revoked_at
|
||||
And the entry has no "key" and no "hashed_key" field
|
||||
And the raw key and its hash appear nowhere in the body
|
||||
And the entry's prefix is the first 12 characters of the raw key
|
||||
|
||||
Scenario: Creating a key with an expiry
|
||||
Given a valid jwt cookie for admin 2
|
||||
When the client sends POST /v1/api-key with body
|
||||
{"name": "temp", "expires_at": "<now + 30 days, RFC3339>"}
|
||||
Then the response status is 201
|
||||
And expires_at in the body equals the requested instant
|
||||
|
||||
Scenario Outline: Creating a key with an invalid body is refused and creates nothing
|
||||
Given a valid jwt cookie for admin 2
|
||||
When the client sends POST /v1/api-key with <body>
|
||||
Then the response status is 400
|
||||
And the response body is <message>
|
||||
And no key exists in the repository
|
||||
|
||||
Examples:
|
||||
| body | message |
|
||||
| body not-json | apperr.BodyErrorMessage |
|
||||
| body {} | text containing 'Name' and 'required' |
|
||||
| body {"name": ""} | text containing 'Name' and 'required' |
|
||||
| body {"name": "<61 characters>"} | text containing 'Name' and 'max' |
|
||||
| body {"name": "x", "expires_at": "yesterday"} | apperr.BodyErrorMessage |
|
||||
| body {"name": "x", "expires_at": "<now - 1h>"} | apperr.APIKeyExpiryErrorMessage |
|
||||
|
||||
Scenario: A request body can't choose the owner or the role of a new key
|
||||
Given a valid jwt cookie for admin 2
|
||||
When the client sends POST /v1/api-key with body {"name": "sneaky", "user_id": 1, "role": "owner"}
|
||||
Then the response status is 201
|
||||
And the stored key belongs to user 2
|
||||
And using that key on POST /v1/user/invite returns 403 with apperr.OwnerRequiredErrorMessage
|
||||
|
||||
Scenario Outline: Key management needs a verified real session
|
||||
Given <caller>
|
||||
When the client sends POST /v1/api-key with body {"name": "x"}
|
||||
Then the response status is <status>
|
||||
And the response body is <message>
|
||||
And no key exists in the repository
|
||||
|
||||
Examples:
|
||||
| caller | status | message |
|
||||
| no credentials | 401 | the existing Authenticator response |
|
||||
| a jwt cookie for user 4 | 403 | apperr.VerificationRequiredErrorMessage |
|
||||
| a stale token_version cookie | 401 | the existing Authenticator response |
|
||||
|
||||
Scenario Outline: A valid key acts as its creator on every key-accepting route
|
||||
Given an active key created by admin 2
|
||||
When the client sends <method> <path> with "Authorization: Bearer <that key>" and no cookie <body>
|
||||
Then the response status is <status>
|
||||
And the effect is attributed to user 2
|
||||
|
||||
Examples:
|
||||
| method | path | body | status |
|
||||
| GET | /v1/settings | | 200 |
|
||||
| GET | /v1/user | | 200 |
|
||||
| PATCH | /v1/user/me | and body {"display_name": "Dev"} | 200 |
|
||||
| POST | /v1/article | and body {"title": "A valid title", "body": "x"} | 201 |
|
||||
| PATCH | /v1/article/1/publish | | 200 |
|
||||
| DELETE | /v1/article/1 | | 204 |
|
||||
| GET | /v1/media | | 200 |
|
||||
| DELETE | /v1/media/1 | | 204 |
|
||||
|
||||
Scenario: A key can read its creator through GET /v1/auth/me
|
||||
Given an active key created by admin 2
|
||||
When the client sends GET /v1/auth/me with that key and no cookie
|
||||
Then the response status is 200
|
||||
And the body is the same JSON the jwt cookie of admin 2 gets on GET /v1/auth/me
|
||||
And the body describes user 2 "dev"
|
||||
|
||||
Scenario: A key that can't authenticate gets 401 on GET /v1/auth/me
|
||||
When the client sends GET /v1/auth/me with "Authorization: Bearer rcms_unknown"
|
||||
Then the response status is 401
|
||||
And the response body is apperr.UnauthorizedErrorMessage
|
||||
|
||||
Scenario: A key sees offline articles on the public article routes, an anonymous caller does not
|
||||
Given an offline article 5 and an online article 6
|
||||
And an active key created by admin 2
|
||||
When the client sends GET /v1/article with that key
|
||||
Then the body lists articles 5 and 6
|
||||
When the client sends GET /v1/article with no credentials
|
||||
Then the body lists only article 6
|
||||
When the client sends GET /v1/article/5 with that key
|
||||
Then the response status is 200
|
||||
When the client sends GET /v1/article/5 with no credentials
|
||||
Then the response status is 404
|
||||
|
||||
Scenario: An invalid key on a public article route is refused, not treated as anonymous
|
||||
When the client sends GET /v1/article with "Authorization: Bearer rcms_unknown"
|
||||
Then the response status is 401
|
||||
And the response body is apperr.UnauthorizedErrorMessage
|
||||
|
||||
Scenario: An owner's key can do owner-only things
|
||||
Given an active key created by owner 1
|
||||
When the client sends POST /v1/user/invite with that key and body {"email": "new@example.com"}
|
||||
Then the response status is 201
|
||||
And the invite's invited_by is 1
|
||||
|
||||
Scenario: An admin's key can not do owner-only things
|
||||
Given an active key created by admin 2
|
||||
When the client sends POST /v1/user/invite with that key and body {"email": "new@example.com"}
|
||||
Then the response status is 403
|
||||
And the response body is apperr.OwnerRequiredErrorMessage
|
||||
And no invite exists
|
||||
|
||||
Scenario Outline: A key that can't authenticate gets the same 401 as a bad jwt
|
||||
Given <state>
|
||||
When the client sends GET /v1/settings with "Authorization: Bearer <credential>"
|
||||
Then the response status is 401
|
||||
And the response body is apperr.UnauthorizedErrorMessage
|
||||
And no handler or use case behind the route runs
|
||||
|
||||
Examples:
|
||||
| state | credential |
|
||||
| no key stored for it | rcms_unknownunknownunknownunknownunknownunknown1 |
|
||||
| a key whose expires_at is one second ago | that key |
|
||||
| a key that was revoked | that key |
|
||||
| a key of user 1 whose user record was deleted | that key |
|
||||
| a key of an unverified user | that key |
|
||||
| nothing after the prefix | rcms_ |
|
||||
| a key with one character changed | that key, last character changed |
|
||||
| a key's hash passed instead of the key | the stored HashedKey, status 401 only |
|
||||
|
||||
Scenario: Key behaviour does not change the jwt cookie path
|
||||
Given a valid jwt cookie for admin 2
|
||||
When the client sends GET /v1/settings with only that cookie
|
||||
Then the response status is 200
|
||||
When the client sends GET /v1/settings with an Authorization header "Bearer <a valid jwt>" and no cookie
|
||||
Then the response status is 200
|
||||
When the client sends GET /v1/settings with a stale token_version cookie
|
||||
Then the response status is 401
|
||||
|
||||
Scenario: A Bearer key wins over the cookie, and a bad key is not rescued by a good cookie
|
||||
Given an active key created by admin 3 and a valid jwt cookie for owner 1
|
||||
When the client sends POST /v1/user/invite with both the key and the cookie
|
||||
Then the response status is 403
|
||||
When the client sends GET /v1/settings with "Authorization: Bearer rcms_unknown" and the owner cookie
|
||||
Then the response status is 401
|
||||
|
||||
Scenario Outline: Session-only routes refuse any rcms_ credential with 403
|
||||
Given <state>
|
||||
When the client sends <method> <path> with "Authorization: Bearer <credential>" <body>
|
||||
Then the response status is 403
|
||||
And the response body is apperr.SessionRequiredErrorMessage
|
||||
And no use case behind the route runs
|
||||
And no key was created, listed or revoked
|
||||
|
||||
Examples:
|
||||
| state | credential | method | path | body |
|
||||
| an active key of owner 1 | that key | POST | /v1/api-key | and body {"name": "child"} |
|
||||
| an active key of owner 1 | that key | GET | /v1/api-key | |
|
||||
| an active key of owner 1 | that key | DELETE | /v1/api-key/1 | |
|
||||
| an active key of owner 1 | that key | POST | /v1/auth/verify | and body {"code": "x"} |
|
||||
| an active key of owner 1 | that key | DELETE | /v1/auth/register | |
|
||||
| an active key of owner 1 | that key | GET | /v1/system/update | |
|
||||
| an active key of owner 1 | that key | POST | /v1/system/update/check | |
|
||||
| an active key of owner 1 | that key | POST | /v1/system/update/download | |
|
||||
| an active key of owner 1 | that key | POST | /v1/system/update/restart | |
|
||||
| a revoked key | that key | GET | /v1/api-key | |
|
||||
| no key stored for it | rcms_unknownunknownunknownunknownunknownunknown1 | POST | /v1/system/update/check | |
|
||||
| nothing | rcms_ | DELETE | /v1/auth/register | |
|
||||
|
||||
Scenario Outline: The session-only routes still work as before with a session
|
||||
Given a valid jwt cookie for owner 1
|
||||
When the client sends <method> <path> with only that cookie <body>
|
||||
Then the response is the same as before this feature
|
||||
And a request with no credentials still gets status 401 from the existing Authenticator
|
||||
|
||||
Examples:
|
||||
| method | path | body |
|
||||
| POST | /v1/api-key | and body {"name": "x"} |
|
||||
| GET | /v1/api-key | |
|
||||
| GET | /v1/system/update | |
|
||||
| POST | /v1/system/update/check | |
|
||||
|
||||
Scenario Outline: A key never obtains a session through the public auth routes
|
||||
Given an active key created by owner 1
|
||||
When the client sends <method> <path> with that key and body <body>
|
||||
Then the response is the same as without the key
|
||||
And no jwt cookie is set unless the credentials in the body are valid
|
||||
And the stored user and password are unchanged
|
||||
|
||||
Examples:
|
||||
| method | path | body |
|
||||
| POST | /v1/auth/login | {"username": "marta", "password": "wrong-pass-1"} |
|
||||
| POST | /v1/auth/password-reset/confirm | {"email": "marta@example.com", "code": "nope", "password": "newpassword1"} |
|
||||
|
||||
Scenario: A successful password reset revokes every key of that user
|
||||
Given user 2 has active keys "a" and "b", and each works on GET /v1/settings
|
||||
And user 2's stored PasswordResetCode is the hash of "reset-code-1" with an unexpired expiration
|
||||
When the client sends POST /v1/auth/password-reset/confirm with body
|
||||
{"email": "dev@example.com", "code": "reset-code-1", "password": "newpassword1"}
|
||||
Then the response status is 200
|
||||
And GET /v1/settings with key "a" returns 401 with apperr.UnauthorizedErrorMessage
|
||||
And GET /v1/settings with key "b" returns 401 with apperr.UnauthorizedErrorMessage
|
||||
|
||||
Scenario: A password reset leaves other users' keys untouched
|
||||
Given user 2 has an active key "a" and user 3 has an active key "c"
|
||||
And user 2 has a valid password reset code "reset-code-1"
|
||||
When user 2's password reset is confirmed with "reset-code-1"
|
||||
Then GET /v1/settings with key "c" returns 200
|
||||
And key "c" has no revoked_at
|
||||
|
||||
Scenario: Keys revoked by a password reset show as revoked
|
||||
Given user 2 has active keys "a" and "b", and a clock at T
|
||||
And user 2 has a valid password reset code "reset-code-1"
|
||||
When user 2's password reset is confirmed with "reset-code-1"
|
||||
And admin 2 logs in again with the new password and sends GET /v1/api-key with the new cookie
|
||||
Then the entries "a" and "b" have status "revoked" and revoked_at T
|
||||
|
||||
Scenario: A password reset does not move the revoked_at of a key that was already revoked
|
||||
Given user 2 has a key "old" revoked at T0 and an active key "a"
|
||||
And user 2 has a valid password reset code "reset-code-1"
|
||||
When user 2's password reset is confirmed with "reset-code-1" at a later time T
|
||||
Then key "old" still has revoked_at T0
|
||||
And key "a" has revoked_at T
|
||||
|
||||
Scenario Outline: A failed password reset confirmation revokes nothing
|
||||
Given user 2 has an active key "a"
|
||||
And user 2's stored PasswordResetCode is the hash of "reset-code-1" with <expiration>
|
||||
When the client sends POST /v1/auth/password-reset/confirm with <body>
|
||||
Then the response status is not 200
|
||||
And key "a" has no revoked_at
|
||||
And GET /v1/settings with key "a" returns 200
|
||||
|
||||
Examples:
|
||||
| expiration | body |
|
||||
| an unexpired expiration | {"email": "dev@example.com", "code": "wrong", "password": "newpassword1"} |
|
||||
| an expiration in the past | {"email": "dev@example.com", "code": "reset-code-1", "password": "newpassword1"} |
|
||||
| an unexpired expiration | {"email": "nobody@example.com", "code": "reset-code-1", "password": "newpassword1"} |
|
||||
|
||||
Scenario: Listing as an admin shows only that admin's keys
|
||||
Given keys "a" and "b" created by admin 2 and key "c" created by admin 3
|
||||
When admin 2 sends GET /v1/api-key with a jwt cookie
|
||||
Then the body lists exactly "a" and "b"
|
||||
|
||||
Scenario: Listing as the owner shows every user's keys, with the creator's id
|
||||
Given the same three keys and key "d" created by owner 1
|
||||
When owner 1 sends GET /v1/api-key with a jwt cookie
|
||||
Then the body lists "a", "b", "c" and "d" newest first
|
||||
And each entry has the user_id of its creator
|
||||
|
||||
Scenario Outline: The list reports each key's state
|
||||
Given a key that is <state>
|
||||
When its creator sends GET /v1/api-key with a jwt cookie
|
||||
Then the entry's status is "<status>", revoked_at is <revoked_at>, and last_used_at is <last_used>
|
||||
|
||||
Examples:
|
||||
| state | status | revoked_at | last_used |
|
||||
| active, never used | active | null | null |
|
||||
| active, used 5 minutes ago | active | null | that time |
|
||||
| expired one hour ago | expired | null | unchanged |
|
||||
| revoked | revoked | a time | unchanged |
|
||||
| both expired and revoked | revoked | a time | unchanged |
|
||||
|
||||
Scenario: Revoking a key ends it immediately
|
||||
Given an active key "ci-deploy" created by admin 2
|
||||
And the key works on GET /v1/settings
|
||||
When admin 2 sends DELETE /v1/api-key/<its id> with a jwt cookie
|
||||
Then the response status is 204 and the body is empty
|
||||
And GET /v1/settings with that key returns 401 with apperr.UnauthorizedErrorMessage
|
||||
And GET /v1/api-key lists it with status "revoked"
|
||||
|
||||
Scenario: Revoking twice is idempotent
|
||||
Given a key revoked at time T
|
||||
When its creator sends DELETE /v1/api-key/<its id> again
|
||||
Then the response status is 204
|
||||
And revoked_at is still T
|
||||
|
||||
Scenario: An admin can't revoke someone else's key, and learns nothing about it
|
||||
Given a key created by admin 3
|
||||
When admin 2 sends DELETE /v1/api-key/<its id> with a jwt cookie
|
||||
Then the response status is 404
|
||||
And the response body is apperr.APIKeyNotFoundErrorMessage
|
||||
And the key still works
|
||||
|
||||
Scenario: The owner can revoke any key
|
||||
Given a key created by admin 3
|
||||
When owner 1 sends DELETE /v1/api-key/<its id> with a jwt cookie
|
||||
Then the response status is 204
|
||||
And the key gets 401 on GET /v1/settings
|
||||
|
||||
Scenario Outline: Revoking with a bad id
|
||||
Given a valid jwt cookie for admin 2
|
||||
When the client sends DELETE /v1/api-key/<id>
|
||||
Then the response status is <status>
|
||||
And the response body is <message>
|
||||
|
||||
Examples:
|
||||
| id | status | message |
|
||||
| abc | 400 | apperr.IdUint32ErrorMessage |
|
||||
| -1 | 400 | apperr.IdUint32ErrorMessage |
|
||||
| 4294967296 | 400 | apperr.IdUint32ErrorMessage |
|
||||
| 999 | 404 | apperr.APIKeyNotFoundErrorMessage |
|
||||
|
||||
Scenario: Using a key records last_used_at, at most once per minute
|
||||
Given an active key never used, and a fake clock at T
|
||||
When the key authenticates a request at T
|
||||
Then last_used_at is T
|
||||
When it authenticates again at T + 30s
|
||||
Then no write happened and last_used_at is still T
|
||||
When it authenticates again at T + 61s
|
||||
Then last_used_at is T + 61s
|
||||
|
||||
Scenario: A failure to record last_used_at doesn't fail the request
|
||||
Given an active key and a repository whose TouchLastUsed returns an error
|
||||
When the client sends GET /v1/settings with that key
|
||||
Then the response status is 200
|
||||
|
||||
Scenario: A rejected key never records last_used_at
|
||||
Given an expired key and a revoked key
|
||||
When each is used on GET /v1/settings
|
||||
Then each gets 401 and no last_used_at is written
|
||||
|
||||
Scenario: Each key has its own rate limit
|
||||
Given two active keys "a" and "b" and a limit of N requests per minute per key
|
||||
When key "a" sends N+1 requests to GET /v1/settings
|
||||
Then request N+1 gets 429 with apperr.TooManyRequestsErrorMessage and a Retry-After header
|
||||
And key "b" still gets 200
|
||||
And a jwt cookie request still gets 200
|
||||
|
||||
Scenario: The rate limit does not apply to unauthenticated requests
|
||||
When the client sends N+1 requests with "Authorization: Bearer rcms_unknown"
|
||||
Then every response is 401, never 429
|
||||
|
||||
Scenario: The CORS preflight allows PATCH
|
||||
Given settings with CorsAllowedOrigins ["https://app.example.com"]
|
||||
When the client sends OPTIONS /v1/article/1 with Origin "https://app.example.com" and
|
||||
Access-Control-Request-Method "PATCH"
|
||||
Then the response is a successful preflight
|
||||
And Access-Control-Allow-Methods includes PATCH
|
||||
And a preflight for method "TRACE" is not allowed
|
||||
|
||||
Scenario: Use case: creating a key hashes it and stores no plaintext
|
||||
Given a fake KeyGenerator returning raw "rcms_fake", prefix "rcms_fake", hash "hash:rcms_fake"
|
||||
When CreateAPIKey is called with user 2 and name "ci"
|
||||
Then the repository's Create receives HashedKey "hash:rcms_fake", Prefix "rcms_fake", UserID 2
|
||||
And the result carries the raw key, which is not stored
|
||||
|
||||
Scenario: Use case: authenticating returns the user and rejects every invalid case with one sentinel
|
||||
Given a fake KeyGenerator and keys that are unknown, expired, revoked, and owned by a missing or
|
||||
unverified user
|
||||
When AuthenticateAPIKey is called with each raw key
|
||||
Then every call returns apikey.ErrAPIKeyInvalid, asserted with errors.Is
|
||||
And a key expiring exactly at the clock's now is expired
|
||||
And a valid key returns the user from user.Repository
|
||||
|
||||
Scenario: Use case: a failing repository is not reported as an invalid key
|
||||
Given a repository whose GetByHashedKey returns an unexpected error
|
||||
When AuthenticateAPIKey is called
|
||||
Then the error is returned and errors.Is(err, apikey.ErrAPIKeyInvalid) is false
|
||||
And the middleware answers 500 "Internal server error"
|
||||
|
||||
Scenario: Use case: ResetPassword revokes the user's keys through the domain repository
|
||||
Given a fake apikey.Repository holding active keys of users 2 and 3, a fake clock at T, and a
|
||||
user.Repository fake with a valid reset code for user 2
|
||||
When ResetPasswordUseCase.ResetPassword succeeds for user 2
|
||||
Then the fake apikey.Repository received exactly one RevokeAllByUser(2, T)
|
||||
And user 3's keys are untouched
|
||||
|
||||
Scenario: Use case: ResetPassword does not call RevokeAllByUser when the reset fails
|
||||
Given a fake apikey.Repository and a user.Repository fake with a wrong or expired reset code
|
||||
When ResetPasswordUseCase.ResetPassword is called
|
||||
Then it returns the existing invalid or expired sentinel
|
||||
And RevokeAllByUser is never called
|
||||
|
||||
Scenario: Use case: a failure to revoke keys after a reset is reported
|
||||
Given a valid reset code and an apikey.Repository whose RevokeAllByUser returns an error
|
||||
When ResetPasswordUseCase.ResetPassword is called
|
||||
Then the use case returns that error
|
||||
And the password was already changed
|
||||
@@ -0,0 +1,171 @@
|
||||
# QA procedure: API keys
|
||||
|
||||
Package: `test` (black-box). No live server, no real SQLite file, no real SMTP.
|
||||
|
||||
## Setup shared by every case
|
||||
1. Call `validator.InitValidator()` once per test.
|
||||
2. Add in-memory fakes with unique type names across the package: `mockAPIKeyRepo`
|
||||
(implements `apikey.Repository` including `RevokeAllByUser`, with a `fail` switch per method such as
|
||||
`failNext("TouchLastUsed")`, a `touchCalls` counter and a `revokeAllCalls` log of `(userId, at)`) and
|
||||
`stubKeyGenerator` (deterministic raw/prefix/hash). Reuse `mockUserRepo`, `stubHasher` and the
|
||||
article, media and invite fakes.
|
||||
3. HTTP tests use the real SHA-256 generator, so key format and hashing are real. Unit-level tests
|
||||
use `stubKeyGenerator`.
|
||||
4. Build the handler stack from a `*api.UseCases` container holding fakes and mount
|
||||
`api.InitBackendRoutes(container, settings)` on a test server (unused use cases stay nil). It is the
|
||||
most faithful way to test the middleware order and the exclusions. If a nil use case breaks a
|
||||
handler constructor, fall back to a fresh `chi.NewRouter()` that mirrors `api/router.go`:
|
||||
`jwtauth.Verifier`, the key middleware, `jwtauth.Authenticator`, `RequireCurrentToken`,
|
||||
`RequireVerifiedUser` (and `RequireOwner` on the invite group) for the key-accepting routes
|
||||
(including `GET /auth/me`); `RequireSession` ahead of `jwtauth.Verifier` on `/api-key`,
|
||||
`POST /auth/verify`, `DELETE /auth/register` and `/system`; and the public auth routes with neither.
|
||||
The test token is `jwtauth.New("HS256", []byte("test-secret"), nil)`.
|
||||
5. Inject a fake clock (`now func() time.Time`) into the key use cases and `ResetPasswordUseCase`.
|
||||
6. Seed users: owner 1 "marta", admin 2 "dev", admin 3 "pat" (all verified), unverified 4 "quinn".
|
||||
7. Helpers: `cookieFor(userId, tokenVersion)` mints a jwt cookie with
|
||||
`token.Encode(map[string]any{"user_id": id, "token_version": v})`; `bearer(raw)` sets the header.
|
||||
Create real keys through `POST /v1/api-key` with the cookie so the shown-once value is genuine.
|
||||
|
||||
## POST /v1/api-key
|
||||
8. Admin 2 cookie, `{"name":"ci-deploy"}` -> `201`, `Cache-Control: no-store`, key set is exactly `id`,
|
||||
`name`, `prefix`, `key`, `created_at`, `expires_at`; `key` matches `^rcms_[A-Za-z0-9_-]{43}$`; prefix
|
||||
is `key[:12]`; stored `HashedKey` equals the generator's `Hash(key)`; `UserID` 2; the raw key is
|
||||
stored nowhere in the fake.
|
||||
9. Two creations give two different keys and ids.
|
||||
10. With `expires_at` 30 days ahead -> `201`, echoed instant.
|
||||
11. Invalid bodies (table): not-json -> `400` `apperr.BodyErrorMessage`; `{}`, `{"name":""}` -> `400`,
|
||||
body contains `'Name'` and `required`; 61-char name -> `400`, contains `max`; `expires_at`
|
||||
"yesterday" -> `400` `BodyErrorMessage`; past `expires_at` -> `400` `apperr.APIKeyExpiryErrorMessage`.
|
||||
Each: repository still empty.
|
||||
12. Body `{"name":"sneaky","user_id":1,"role":"owner"}` with admin 2 -> `201`; stored `UserID` 2; that
|
||||
key on `POST /v1/user/invite` -> `403` `apperr.OwnerRequiredErrorMessage`, no invite.
|
||||
13. Access table: no credentials -> `401`; user 4 cookie -> `403` `apperr.VerificationRequiredErrorMessage`;
|
||||
stale `token_version` -> `401`. Each: repository empty.
|
||||
|
||||
## Shown once
|
||||
14. After case 8, `GET /v1/api-key` -> entry keys exactly `id`, `user_id`, `name`, `prefix`, `status`,
|
||||
`created_at`, `last_used_at`, `expires_at`, `revoked_at`; assert the response bytes contain neither
|
||||
the raw key nor the stored hash. Also assert the raw key and hash are absent from the `DELETE`
|
||||
response and from every error body in this file.
|
||||
15. There is no route that returns a key again: `GET /v1/api-key/{id}` -> `404` or `405` (whatever the
|
||||
router yields; assert not `200`).
|
||||
|
||||
## Authentication
|
||||
16. Table over `GET /v1/settings`, `GET /v1/user`, `PATCH /v1/user/me`, `POST /v1/article`,
|
||||
`PATCH /v1/article/{id}/publish`, `DELETE /v1/article/{id}`, `GET /v1/media`, `DELETE /v1/media/{id}`
|
||||
with only the Bearer key of admin 2 -> `200` each; the stored side effects (author, display name)
|
||||
belong to user 2.
|
||||
17. Public article routes: seed offline article 5, online article 6. Key -> list has both, `GET /5` is
|
||||
`200`. No credentials -> list has only 6, `GET /5` is `404`. `Bearer rcms_unknown` on `GET /v1/article`
|
||||
-> `401` `apperr.UnauthorizedErrorMessage`.
|
||||
18. Owner key `POST /v1/user/invite` -> `201`, `invited_by` 1. Admin key -> `403`
|
||||
`apperr.OwnerRequiredErrorMessage`, no invite and no mail.
|
||||
19. Table of 401 cases on `GET /v1/settings`, all with body `apperr.UnauthorizedErrorMessage` exactly (the
|
||||
stored-hash case has no `rcms_` prefix, so it takes the jwt path: assert status `401` only):
|
||||
unknown well-formed key; expired (clock one second past `expires_at`); revoked; creator deleted from
|
||||
the user fake; creator unverified (set `IsVerified=false` in the fake); `Bearer rcms_`; one
|
||||
character changed; the stored hash sent as the key. Assert each also leaves `touchCalls == 0`.
|
||||
Without an `rcms_` key the existing `jwtauth.Authenticator` response is unchanged: assert status `401`.
|
||||
20. A key whose `ExpiresAt` equals the clock's now is rejected; one second later than now is accepted.
|
||||
21. Cookie path unchanged: valid cookie -> `200`; valid jwt in `Authorization: Bearer` with no cookie ->
|
||||
`200`; stale `token_version` -> `401`; no credentials on a protected route -> `401`.
|
||||
22. Precedence: valid key of admin 3 plus an owner cookie on `POST /v1/user/invite` -> `403`
|
||||
(acts as admin 3); `Bearer rcms_unknown` plus an owner cookie on `GET /v1/settings` -> `401`.
|
||||
23. Role is read live: change the stored role of user 2 from admin to owner in the fake (test-only) and
|
||||
assert the key is now owner-capable, then back, and assert it is not. This pins "never more
|
||||
rights than the creator's current rights".
|
||||
24. `GET /v1/auth/me` with only admin 2's key -> `200`, body byte-equal to the body admin 2's cookie gets
|
||||
on the same route, describing user 2. `Bearer rcms_unknown` on `GET /v1/auth/me` -> `401`
|
||||
`apperr.UnauthorizedErrorMessage`.
|
||||
|
||||
## Session-only routes (RequireSession)
|
||||
25. Table, each with body `apperr.SessionRequiredErrorMessage`, status `403`, assert the underlying use
|
||||
cases (key repository, verify, cancel registration, update status/check/download/restart) were
|
||||
not invoked and the key repository is unchanged:
|
||||
- owner 1's active key on `POST /v1/api-key`, `GET /v1/api-key`, `DELETE /v1/api-key/1`,
|
||||
`POST /v1/auth/verify`, `DELETE /v1/auth/register`, `GET /v1/system/update`,
|
||||
`POST /v1/system/update/check`, `POST /v1/system/update/download`, `POST /v1/system/update/restart`;
|
||||
- a revoked key on `GET /v1/api-key`;
|
||||
- an unknown well-formed `rcms_...` key on `POST /v1/system/update/check`;
|
||||
- the bare string `rcms_` on `DELETE /v1/auth/register`.
|
||||
The 403 comes before any authentication, so assert the same 403 for an owner key and a garbage key.
|
||||
26. Session routes unchanged for sessions: owner cookie on `POST /v1/api-key`, `GET /v1/api-key`,
|
||||
`GET /v1/system/update`, `POST /v1/system/update/check` -> the same status and body as before this
|
||||
feature; no credentials -> status `401` (existing Authenticator); a jwt in `Authorization: Bearer`
|
||||
(not starting with `rcms_`) -> the same result as the cookie.
|
||||
27. Public auth routes with an owner key attached: `POST /v1/auth/login` with wrong credentials -> `403`
|
||||
`apperr.LogsErrorMessage`, no `jwt` Set-Cookie; `POST /v1/auth/password-reset/confirm` with a wrong
|
||||
code -> the same response as without the key, and the key is not rejected with
|
||||
`SessionRequiredErrorMessage`. The user's stored password hash and `TokenVersion` are unchanged.
|
||||
|
||||
## Password reset revokes keys
|
||||
28. Seed user 2 with active keys "a" and "b" (each `200` on `GET /v1/settings`), user 3 with key "c", and a
|
||||
reset code for user 2 (hash of "reset-code-1", unexpired). `POST /v1/auth/password-reset/confirm`
|
||||
`{"email":"dev@example.com","code":"reset-code-1","password":"newpassword1"}` -> `200`; then keys "a"
|
||||
and "b" get `401` `apperr.UnauthorizedErrorMessage` on `GET /v1/settings`.
|
||||
29. Same seed: key "c" still gets `200` and has no `revoked_at`.
|
||||
30. Same seed with the fake clock at T: log in as user 2 with the new password, `GET /v1/api-key` with the
|
||||
new cookie; "a" and "b" have status `revoked` and `revoked_at` equal to T.
|
||||
31. A key of user 2 already revoked at T0 keeps `revoked_at` T0 after a reset at a later T; the active
|
||||
key gets T.
|
||||
32. Failed confirms (table: wrong code; expired code; unknown email) -> status not `200`; key "a" has no
|
||||
`revoked_at`, still `200` on `GET /v1/settings`, and `revokeAllCalls` is empty.
|
||||
|
||||
## Listing
|
||||
33. Admin 2 sees only own keys; owner 1 sees all, newest first, each with its `user_id`.
|
||||
34. Status table: active never used (`active`, nulls), active used (timestamp kept), expired
|
||||
(`expired`), revoked (`revoked`, `revoked_at` set), expired-and-revoked (`revoked`).
|
||||
|
||||
## Revoke
|
||||
35. Own key -> `204`, empty body; the key then gets `401` on `GET /v1/settings`; the list shows `revoked`.
|
||||
36. Second `DELETE` -> `204`, `revoked_at` unchanged.
|
||||
37. Admin 2 revoking admin 3's key -> `404` `apperr.APIKeyNotFoundErrorMessage`; the key still works.
|
||||
Owner revoking it -> `204`; it then gets `401`.
|
||||
38. Ids `abc`, `-1`, `4294967296` -> `400` `apperr.IdUint32ErrorMessage`; unknown id -> `404`.
|
||||
39. Repository failure on `Revoke` -> `500` "Internal server error"; the key still works.
|
||||
|
||||
## last_used_at
|
||||
40. Use-case level with the fake clock: first auth at T writes T; at T+30s no write
|
||||
(`touchCalls` unchanged); at T+61s writes T+61s.
|
||||
41. `TouchLastUsed` failing -> the request still returns `200`.
|
||||
42. Rejected keys (case 19) never write.
|
||||
|
||||
## Rate limit
|
||||
43. Mirror a group using the new per-key limiter with a limit of 2 (an exported constructor taking max
|
||||
attempts and window): third request with key A -> `429`, body `apperr.TooManyRequestsErrorMessage`,
|
||||
`Retry-After` header; key B and a cookie request still `200`; invalid keys stay `401`, never `429`.
|
||||
44. Through `api.InitBackendRoutes`, send 121 requests with one key to `GET /v1/settings` -> the 121st is
|
||||
`429`, the first 120 are `200`.
|
||||
|
||||
## CORS
|
||||
45. Through `api.InitRoutes` with `CorsAllowedOrigins` `["https://app.example.com"]`: `OPTIONS /v1/article/1`
|
||||
with `Origin` and `Access-Control-Request-Method: PATCH` -> success, `Access-Control-Allow-Methods`
|
||||
includes `PATCH`; with `TRACE` it is not allowed.
|
||||
|
||||
## Use case level (no HTTP)
|
||||
46. `CreateAPIKey` with `stubKeyGenerator`: repository receives the hash and the prefix and the user id;
|
||||
the raw key appears only in the return value; a generator error -> returned, nothing stored; past
|
||||
expiry -> `errors.Is(err, apikey.ErrExpiryNotInFuture)`.
|
||||
47. `AuthenticateAPIKey`: each invalid case in 19 and 20 -> `errors.Is(err, apikey.ErrAPIKeyInvalid)`; a
|
||||
valid key returns the user; an unexpected repository error is returned and is not `ErrAPIKeyInvalid`.
|
||||
48. `ListAPIKeys` for admin and owner; `RevokeAPIKey` own, other's (`ErrAPIKeyNotFound` for admin),
|
||||
owner any, unknown (`ErrAPIKeyNotFound`).
|
||||
49. `ResetPasswordUseCase` built over `mockUserRepo`, `stubHasher`, `mockAPIKeyRepo` and a fake clock at T:
|
||||
a successful reset for user 2 -> exactly one `RevokeAllByUser(2, T)` and user 3's keys untouched; a
|
||||
wrong or expired code -> the existing sentinel and `revokeAllCalls` empty; `RevokeAllByUser`
|
||||
failing -> that error is returned (the password was already changed).
|
||||
50. `mockAPIKeyRepo.RevokeAllByUser` semantics: sets `RevokedAt` only on that user's not-yet-revoked
|
||||
keys.
|
||||
51. SHA-256 generator: raw matches the regex, `Hash(raw)` equals the generated hash, two generated keys
|
||||
differ, prefix is the first 12 characters.
|
||||
|
||||
## Manual verification (not exercised by the Go tests)
|
||||
- Real SQLite: start `task dev:api`, confirm `AutoMigrate` creates the api_keys table with a unique index
|
||||
on the hashed key, create a key, restart, and check it still authenticates.
|
||||
- With `curl`, run `Authorization: Bearer <key>` against a running server for an article create, a media
|
||||
upload, an owner invite and `GET /v1/auth/me`, and confirm `PATCH` works from a browser origin listed
|
||||
in `CORS_ALLOWED_ORIGINS`.
|
||||
- Confirm the full key is shown only in the creation response and appears in no server log
|
||||
(`ENVIRONMENT=development` enables httplog).
|
||||
- A real reverse proxy: confirm `Authorization` is forwarded and `Retry-After` reaches the client.
|
||||
- A real password reset by email: confirm the keys stop working after the link is used.
|
||||
@@ -0,0 +1,352 @@
|
||||
Feature: API keys screen
|
||||
|
||||
As a verified RenewCMS owner or admin
|
||||
I want /integration/api-keys to list my API keys, create new ones and revoke them
|
||||
So that a script or service can call the API with my rights, and I can cut it off at any time
|
||||
|
||||
Background:
|
||||
Given /integration/api-keys is a verified route (meta.auth "verified") rendered as ApiKeysPage
|
||||
with CreateApiKeyModal, ApiKeyReveal and a revoke confirmation dialog, inside
|
||||
DashboardShell, per docs/design/routes.md
|
||||
And the screen is a sub-page of Integration, per docs/design/screens/integration.md
|
||||
And the screen calls, with relative URLs through useApi only, GET /v1/api-key,
|
||||
POST /v1/api-key and DELETE /v1/api-key/{id}
|
||||
And a GET /v1/api-key entry has the fields id, user_id, name, prefix (12 characters), status
|
||||
("active", "expired" or "revoked"), created_at, last_used_at, expires_at and revoked_at, and
|
||||
never a key or a hash, per features/api_keys.feature
|
||||
And an owner's entries also carry created_by_name, the creator's display name or username (see
|
||||
the API scenarios below)
|
||||
And the list arrives newest first; an owner receives every user's keys, an admin only their own
|
||||
And the PageHeader shows breadcrumb "Integration › API keys" (Integration links to
|
||||
/integration), title "API keys" and a primary "Create key" button on the right at desktop
|
||||
And the description reads "Keys act as the user who created them. As an owner you see
|
||||
everyone's keys." for an owner, and "Keys act as you, with your role. You only see your own
|
||||
keys." for an admin; a session without a role gets the admin rendering
|
||||
And the table, on desktop, has the columns Name, Key, Status, Created by (owner only), Created,
|
||||
Last used, Expires and an action column, in a UTable with a 36 px header and 48 px rows
|
||||
And below md, each key is a card: name and status badge, prefix in monospace, then
|
||||
"Created {date}[ by {name}] · Last used {date} · Expires {date}", then a 44 px "Revoke" button
|
||||
And the Key column and the card show the prefix cut to its first 9 characters followed by "…",
|
||||
for example "rcms_Kf3x…", and the full key is never shown in the list
|
||||
And the revoke text uses the same 9-character prefix plus "…"
|
||||
And dates are absolute and formatted for the current locale, for example "12 Mar 2026" in
|
||||
English; a null expires_at reads "None" and a null last_used_at reads "Never"
|
||||
And a Created by cell with an empty created_by_name shows "—"
|
||||
And the Status badge is a UBadge: active success soft, expired warning soft, revoked neutral
|
||||
with a muted row
|
||||
And "Revoke" is offered on active and expired keys, never on revoked keys
|
||||
And a note with an info icon always closes the page: "Resetting a user's password revokes all of
|
||||
their keys."
|
||||
And the Integration page (/integration, features/integration.feature) gains a "Manage API
|
||||
keys" link to /integration/api-keys (see the Integration link scenario)
|
||||
And on /integration/api-keys the sidebar and drawer item "Integration" carries
|
||||
aria-current="page"
|
||||
And every visible string goes through t(...), with the English text as the key and its French
|
||||
entry in web/src/i18n/messages.ts
|
||||
And the screen uses Nuxt UI components and design tokens only, with no raw colors
|
||||
And the owner fixture is, newest first as the board draws it:
|
||||
| name | prefix | status | created by | created | last used | expires |
|
||||
| Website build | rcms_Kf3x… | active | Marta Alves | 12 Mar 2026 | 3 Oct 2026 | None |
|
||||
| Nightly media import | rcms_Mq7b… | active | Jonas | 2 Apr 2026 | 3 Oct 2026 | 31 Dec 2026 |
|
||||
| Staging preview | rcms_Zt2d… | expired | Marta Alves | 14 Jun 2026 | 20 Aug 2026 | 30 Aug 2026 |
|
||||
| Old migration script | rcms_Hn5w… | revoked | Inès Duarte | 3 Apr 2026 | 9 May 2026 | None |
|
||||
And the admin fixture (user "Jonas") is:
|
||||
| name | prefix | status | created | last used | expires |
|
||||
| Nightly media import | rcms_Mq7b… | active | 2 Apr 2026 | 3 Oct 2026 | 31 Dec 2026 |
|
||||
| Old CI token | rcms_Lp9c… | revoked | 18 Jan 2026 | 2 Feb 2026 | None |
|
||||
|
||||
Scenario: Owner: list
|
||||
Given the session role is "owner"
|
||||
And GET /v1/api-key answers 200 with the owner fixture
|
||||
When the user navigates to /integration/api-keys
|
||||
Then the four rows show in fixture order with the columns Name, Key, Status, Created by,
|
||||
Created, Last used, Expires
|
||||
And "Staging preview" shows an "expired" badge and "Revoke"
|
||||
And "Old migration script" shows a "revoked" badge, a muted row and no "Revoke"
|
||||
And the description is the owner description
|
||||
|
||||
Scenario: Admin: own keys only
|
||||
Given the session role is "admin"
|
||||
And GET /v1/api-key answers 200 with the admin fixture
|
||||
When the user navigates to /integration/api-keys
|
||||
Then the two rows show with no "Created by" column
|
||||
And on mobile the cards read "Created 2 Apr 2026 · Last used 3 Oct 2026 · Expires 31 Dec 2026"
|
||||
without " by {name}"
|
||||
And the description is the admin description
|
||||
|
||||
Scenario: Loading
|
||||
Given GET /v1/api-key is pending
|
||||
When the user navigates to /integration/api-keys
|
||||
Then four skeleton rows are drawn in the table (two-bar cards below md) and the table has
|
||||
aria-busy "true"
|
||||
And the header "Create key" button is shown
|
||||
|
||||
Scenario: Empty
|
||||
Given GET /v1/api-key answers 200 with []
|
||||
When the user navigates to /integration/api-keys
|
||||
Then a panel shows title "No API keys yet", text "Create a key to call the API from a script or
|
||||
service." and a primary "Create key" button
|
||||
And no table is drawn
|
||||
|
||||
Scenario Outline: Error on load
|
||||
Given GET /v1/api-key fails with <failure>
|
||||
When the user navigates to /integration/api-keys
|
||||
Then an alert (role "alert") shows "Couldn't load your API keys" and "Check your connection and
|
||||
try again." with a "Try again" action
|
||||
And no table, no cards and no empty panel are drawn
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| status 500 |
|
||||
| a network error |
|
||||
|
||||
Scenario: Try again after an error
|
||||
Given the load failed and the error alert is shown
|
||||
When the user activates "Try again"
|
||||
Then GET /v1/api-key is requested again and, on 200, the list replaces the alert
|
||||
|
||||
Scenario Outline: Session problems use the app-wide handling
|
||||
Given GET /v1/api-key answers <status>
|
||||
When the user navigates to /integration/api-keys
|
||||
Then <outcome>
|
||||
|
||||
Examples:
|
||||
| status | outcome |
|
||||
| 401 | the user lands on /login?redirect=/integration/api-keys&reason=expired |
|
||||
| 403 | the user lands on /register/pending |
|
||||
|
||||
Scenario: Create key: modal opened
|
||||
Given the list is shown
|
||||
When the user activates "Create key"
|
||||
Then a modal titled "Create API key" opens with the text "The key acts as you, with your role. It
|
||||
is shown in full once."
|
||||
And it has a Name field with a "0 / 60" counter and help "Required. Up to 60 characters."
|
||||
And it has an "Expiry date (optional)" date input with help "Optional. Must be in the future.
|
||||
Leave it empty for a key that does not expire."
|
||||
And it has the buttons "Cancel" and "Create key"
|
||||
And Name has focus
|
||||
|
||||
Scenario Outline: Create key: validation
|
||||
Given the Create API key modal is open
|
||||
When the user submits with name "<name>" and expiry "<expiry>"
|
||||
Then no request is sent
|
||||
And <name_error>
|
||||
And <expiry_error>
|
||||
|
||||
Examples:
|
||||
| name | expiry | name_error | expiry_error |
|
||||
| | 12 Mar 2026 | Name shows the error "Enter a name." in red | Expiry shows the error "Choose a date in the future." in red |
|
||||
| | | Name shows the error "Enter a name." in red | Expiry shows no error |
|
||||
| Deploy | 12 Mar 2026 | Name shows no error | Expiry shows the error "Choose a date in the future." in red |
|
||||
|
||||
Scenario: Create key: name too long
|
||||
Given the Create API key modal is open
|
||||
When the user types a name of 75 characters
|
||||
Then the counter reads "75 / 60" in the error color
|
||||
And Name shows the error "Use 60 characters or fewer." in red
|
||||
And submitting sends no request
|
||||
|
||||
Scenario: Create key: success reveals the key once
|
||||
Given the Create API key modal is open
|
||||
When the user submits name "Nightly media import" and an empty expiry
|
||||
Then exactly one POST /v1/api-key is sent with body {"name": "Nightly media import"} and no
|
||||
expires_at
|
||||
And on 201 the form modal is replaced by a modal titled "Your new API key" with the text
|
||||
"\"Nightly media import\" is ready. Copy the key and store it somewhere safe."
|
||||
And a warning alert (UAlert, color warning, triangle-alert icon) reads "You won't be able to
|
||||
see this key again."
|
||||
And the full key from the response is shown in a monospace box with a "Copy" button (icon copy)
|
||||
And the note "Closing this window discards the key from the screen. Copy it first." is shown
|
||||
And the only button is a primary "Done"
|
||||
|
||||
Scenario: Create key: with an expiry
|
||||
Given the Create API key modal is open
|
||||
And the local date is D
|
||||
When the user submits name "temp" and the expiry date D + 30 days
|
||||
Then the POST body carries name "temp" and expires_at equal to 23:59:59 local time on D + 30
|
||||
days, as an RFC3339 instant with the local offset
|
||||
|
||||
Scenario Outline: The expiry date is checked against the same instant the API checks
|
||||
Given the Create API key modal is open and the current time is T
|
||||
When the user submits a name and the expiry date <date>
|
||||
Then <outcome>
|
||||
|
||||
Examples:
|
||||
| date | outcome |
|
||||
| today | the request is sent, because 23:59:59 today is after T |
|
||||
| yesterday | no request is sent and Expiry shows "Choose a date in the future." |
|
||||
| tomorrow | the request is sent |
|
||||
|
||||
Scenario: One-time reveal: copied
|
||||
Given the key reveal is open
|
||||
When the user activates "Copy"
|
||||
Then the full key is written to the clipboard
|
||||
And the button shows icon check and text "Copied" in the success color, announced to assistive
|
||||
technology
|
||||
When 2 seconds elapse
|
||||
Then the button reverts to icon copy and text "Copy"
|
||||
|
||||
Scenario: One-time reveal: Done discards the key
|
||||
Given the key reveal is open
|
||||
When the user activates "Done"
|
||||
Then the modal closes
|
||||
And the full key is no longer in the DOM, the component state, the URL or any storage
|
||||
And the new key is listed first with its 9-character prefix and "…" only, status "active",
|
||||
created by the current user (owner view), last used "Never", expires per the request, and no
|
||||
second GET /v1/api-key is made
|
||||
And reopening "Create key" shows an empty form
|
||||
|
||||
Scenario Outline: Dismissing the modals
|
||||
Given <modal> is open
|
||||
When the user <action>
|
||||
Then <outcome>
|
||||
|
||||
Examples:
|
||||
| modal | action | outcome |
|
||||
| the key reveal | presses Escape | the modal closes and the key is discarded, as for Done |
|
||||
| the key reveal | clicks the backdrop | the modal stays open |
|
||||
| the Create key form | presses Escape | the modal closes with no request |
|
||||
| the Create key form | clicks the backdrop | the modal stays open |
|
||||
|
||||
Scenario: Create key: Cancel discards the form
|
||||
Given the Create API key modal is open with typed values
|
||||
When the user activates "Cancel"
|
||||
Then the modal closes without a request, focus returns to the opening button, and reopening it
|
||||
shows an empty form
|
||||
|
||||
Scenario: Revoke: confirm
|
||||
Given the owner list is shown
|
||||
When the user activates "Revoke" on "Nightly media import"
|
||||
Then a dialog titled "Revoke this key?" opens with the text "\"Nightly media import\"
|
||||
(rcms_Mq7b…) will stop working right away. Requests that use it answer 401. This can't be
|
||||
undone."
|
||||
And its buttons are "Keep key" and a destructive "Revoke key"
|
||||
And "Keep key" closes the dialog with no request and the row unchanged
|
||||
|
||||
Scenario: Revoked
|
||||
Given the revoke dialog is open for "Nightly media import" (id 2)
|
||||
When the user activates "Revoke key"
|
||||
Then exactly one DELETE /v1/api-key/2 is sent
|
||||
And on 204 the dialog closes and the row stays listed with status "revoked", a muted row and no
|
||||
"Revoke" button
|
||||
And a success toast shows title "Key revoked" and text "\"Nightly media import\" can no longer
|
||||
be used."
|
||||
And no second GET /v1/api-key is made
|
||||
|
||||
Scenario: Mobile Create key button, not drawn on board
|
||||
Given the viewport is below md
|
||||
When the list, the loading skeleton or the error alert is shown
|
||||
Then a primary full-width 48 px "Create key" button is pinned to the bottom of the screen
|
||||
And it is hidden while any modal or dialog is open, and in the Empty state where the panel has
|
||||
its own "Create key" button
|
||||
And the header has no "Create key" button below md
|
||||
|
||||
Scenario: Integration page links to the keys screen
|
||||
Given the user is on /integration
|
||||
Then a "Manage API keys" link (UButton variant link, arrow-right trailing icon) is shown below
|
||||
the three info notes
|
||||
When the user activates it
|
||||
Then the user lands on /integration/api-keys and the sidebar "Integration" item keeps
|
||||
aria-current="page"
|
||||
|
||||
Scenario: Language: every string has a French entry
|
||||
Given the language is "fr"
|
||||
When the user opens each state of the screen
|
||||
Then every visible string is the French message and none falls back to English
|
||||
And dates are formatted for "fr"
|
||||
|
||||
Scenario: Create key: sending, not drawn on board, no visual state
|
||||
Given the Create API key modal is open with a valid name
|
||||
When the user submits and POST /v1/api-key is pending
|
||||
Then the primary button reads "Creating…", Name, Expiry and "Cancel" are disabled
|
||||
And Escape does not close the modal
|
||||
|
||||
Scenario Outline: Create key: failed, not drawn on board, no visual state
|
||||
Given the Create API key modal is open with name "Nightly media import"
|
||||
When POST /v1/api-key fails with <failure>
|
||||
Then an alert in the modal reads "<copy>"
|
||||
And the typed values are kept, the form is enabled again, no row is added, and no field error
|
||||
is shown
|
||||
|
||||
Examples:
|
||||
| failure | copy |
|
||||
| status 500 | Couldn't create the key. Try again in a moment. |
|
||||
| a network error | Couldn't reach RenewCMS. Check your connection and try again. |
|
||||
| status 429 | Too many requests. Wait a moment, then try again. |
|
||||
| status 400 | Something in the form isn't valid. Check the highlighted fields. |
|
||||
|
||||
Scenario: Create key: retry after failure, not drawn on board, no visual state
|
||||
Given a failed create left the modal open
|
||||
When the user submits again and POST answers 201
|
||||
Then the reveal opens and the row is added
|
||||
|
||||
Scenario: Revoke: sending, not drawn on board, no visual state
|
||||
Given the revoke dialog is open
|
||||
When the user activates "Revoke key" and DELETE is pending
|
||||
Then "Revoke key" reads "Revoking…", both buttons are disabled, and Escape does not close the
|
||||
dialog
|
||||
|
||||
Scenario Outline: Revoke: failed, not drawn on board, no visual state
|
||||
Given the revoke dialog is open for "Nightly media import"
|
||||
When DELETE fails with <failure>
|
||||
Then a notice in the dialog reads "<copy>"
|
||||
And the dialog stays open, the buttons are enabled again, and the row is unchanged
|
||||
|
||||
Examples:
|
||||
| failure | copy |
|
||||
| status 500 | Couldn't revoke the key. Try again in a moment. |
|
||||
| a network error | Couldn't reach RenewCMS. Check your connection and try again. |
|
||||
|
||||
Scenario: Revoke: key already gone, 404, not drawn on board, no visual state
|
||||
Given the revoke dialog is open for "Nightly media import" (id 2)
|
||||
When DELETE /v1/api-key/2 answers 404
|
||||
Then the dialog closes, the row is removed from the list, and an error toast reads "That key no
|
||||
longer exists."
|
||||
|
||||
Scenario: Last used, never, not drawn on board, no visual state
|
||||
Given an entry whose last_used_at is null
|
||||
Then its Last used cell and its mobile card text read "Never"
|
||||
|
||||
Scenario: API: an owner's list carries the creator's name
|
||||
Given owner 1 "marta" with display name "Marta Alves", admin 2 "dev" with display name "Dev Two"
|
||||
and admin 3 "pat" with an empty display name
|
||||
And keys "a" by user 1, "b" by user 2 and "c" by user 3
|
||||
When owner 1 sends GET /v1/api-key with a jwt cookie
|
||||
Then each entry has the key created_by_name
|
||||
And entry "a" has "Marta Alves", "b" has "Dev Two" and "c" has "pat"
|
||||
And the other nine fields are unchanged from features/api_keys.feature
|
||||
|
||||
Scenario: API: a whitespace-only display name falls back to the username
|
||||
Given admin 3 "pat" with display name " " and a key "c"
|
||||
When owner 1 sends GET /v1/api-key
|
||||
Then entry "c" has created_by_name "pat"
|
||||
|
||||
Scenario: API: an admin's list is unchanged
|
||||
Given admin 2 with keys "a" and "b"
|
||||
When admin 2 sends GET /v1/api-key with a jwt cookie
|
||||
Then every entry has exactly the keys id, user_id, name, prefix, status, created_at,
|
||||
last_used_at, expires_at, revoked_at
|
||||
And no entry has created_by_name
|
||||
|
||||
Scenario: API: a key whose creator no longer exists
|
||||
Given a key whose user record was deleted
|
||||
When owner 1 sends GET /v1/api-key
|
||||
Then its entry has created_by_name ""
|
||||
And the response status is 200 and the other entries are unaffected
|
||||
|
||||
Scenario: API: a failing user lookup fails the list
|
||||
Given the user repository fake returns an unexpected error on Get for a creator
|
||||
When owner 1 sends GET /v1/api-key
|
||||
Then the response status is 500 and the body is "Internal server error"
|
||||
|
||||
Scenario: API: the creator name is resolved once per user
|
||||
Given owner 1 has 3 keys and admin 2 has 2 keys
|
||||
When owner 1 sends GET /v1/api-key
|
||||
Then the user repository received one Get per distinct creator, not one per key
|
||||
|
||||
Scenario: Use case: ListAPIKeys returns the creator name only to an owner
|
||||
Given a fake apikey.Repository and a fake user.Repository
|
||||
When ListAPIKeys is called for an owner
|
||||
Then every APIKeyEntry carries the creator's name
|
||||
When ListAPIKeys is called for an admin
|
||||
Then every APIKeyEntry has an empty creator name and the handler omits the field
|
||||
@@ -0,0 +1,235 @@
|
||||
# QA: API keys screen
|
||||
|
||||
Two parts: the Go API change (HTTP-level, in `test/`) and the SPA (Vitest and visual).
|
||||
|
||||
## What changes in the backend
|
||||
|
||||
Only `GET /v1/api-key` called by an owner changes: each entry gains `created_by_name`, the creator's
|
||||
display name (trimmed, non-empty) or else username, and `""` when the creator no longer exists.
|
||||
Admin entries keep exactly the nine existing fields and never carry `created_by_name`.
|
||||
`features/api_keys.feature` is not edited. Its exact-fields scenario is made as an admin and stays
|
||||
true. No domain or persistence change: `ListAPIKeysUseCase` already holds `user.Repository` and
|
||||
resolves each distinct creator once through `Get`.
|
||||
|
||||
## Go: created_by_name on GET /v1/api-key
|
||||
|
||||
Extend `test/api_keys_http_test.go`. Build the handler from `NewHandler(...)` over use cases wired
|
||||
to the existing in-memory fakes (apikey.Repository, user.Repository, KeyGenerator, fake clock).
|
||||
Mount it on a fresh `chi.NewRouter()` that mirrors `api/router.go`, wrapped in `jwtauth.Verifier`
|
||||
and `jwtauth.Authenticator` with a test `jwtauth.New("HS256", ...)`; call
|
||||
`validator.InitValidator()`; exercise it with `httptest`. No live server, no real SQLite, no real
|
||||
SMTP. Users: owner 1 "marta" (display name "Marta Alves"), admin 2 "dev" ("Dev Two"), admin 3
|
||||
"pat" (empty display name), all verified.
|
||||
|
||||
1. **Owner sees names** - keys a (user 1), b (user 2), c (user 3); owner cookie GET /v1/api-key;
|
||||
assert 200, every entry has `created_by_name`, a "Marta Alves", b "Dev Two", c "pat", and the
|
||||
other nine fields as before (newest first).
|
||||
2. **Whitespace display name** - user 3 display name " "; assert "pat".
|
||||
3. **Admin unchanged** - admin 2 cookie; assert every entry has exactly the nine existing fields
|
||||
(use `apiKeyAssertExactFields`) and no `created_by_name`. Check that the existing exact-fields
|
||||
test at line 341 is made as an admin; if it is made as an owner, update it and report it.
|
||||
4. **Deleted creator** - key whose user was removed from the fake; owner GET; assert 200 and
|
||||
`created_by_name` "" for it.
|
||||
5. **User lookup fails** - the fake user repository returns an error on Get for a creator; assert
|
||||
500 and body "Internal server error".
|
||||
6. **One lookup per creator** - the fake counts Get calls; owner with 3 + 2 keys over 2 creators;
|
||||
assert the creator lookups equal the distinct creators (plus the requester's own Get).
|
||||
7. **Use case level** - ListAPIKeys for an owner returns entries with the creator name; for an
|
||||
admin returns empty creator names; the other existing ListAPIKeys tests pass unchanged.
|
||||
8. **Regression** - the existing api_keys tests still pass; list order, statuses, 401 and 403
|
||||
behaviour are unchanged.
|
||||
|
||||
Run with `task test`; one test with `task test -- -run 'TestName'`.
|
||||
|
||||
## Automated SPA (Vitest + Vue Test Utils, `task test:web`)
|
||||
|
||||
Mock `useApi`'s `request` for GET /v1/api-key, POST /v1/api-key and DELETE /v1/api-key/{id} per
|
||||
case. Mount ApiKeysPage inside DashboardShell with a resolved verified session (id 1, "marta",
|
||||
display name "Marta Alves", role "owner") and a test router at /integration/api-keys; admin cases
|
||||
use role "admin", username "jonas". Mocked owner entries carry `created_by_name`. Stub
|
||||
`navigator.clipboard.writeText` per case. No test freezes the system date; specs assert on the
|
||||
fixtures' absolute dates only, and the expiry cases build their dates from the real clock. Run
|
||||
layout cases at desktop and below-md (mock `matchMedia`).
|
||||
|
||||
1. **Owner: list** - breadcrumb (with the Integration link), title, owner description, header
|
||||
labels, rows in fixture order with every cell (prefix cut to 9 characters plus "…", Created by
|
||||
from `created_by_name`), badge words, "Revoke" on rows 1 to 3 and not row 4, row 4 muted, the
|
||||
note; the below-md cards. An entry with an empty `created_by_name` shows "—".
|
||||
2. **Admin: own keys only** - no "Created by" header or cell, admin description, two rows, cards
|
||||
without " by {name}"; a session with no role gets the same rendering.
|
||||
3. **Loading** - unresolved GET; 4 skeleton rows, aria-busy "true", header "Create key"; resolve
|
||||
and assert rows.
|
||||
4. **Empty** - `[]`; the panel copy and its "Create key", no table.
|
||||
5. **Error, Examples-driven** - ApiError(500), then NetworkError; alert copy as drawn, "Try again",
|
||||
no rows; click "Try again" and assert the second request and the rows.
|
||||
6. **401 and 403** - the app-wide redirects, no alert on the page.
|
||||
7. **Create key: opened** - title, text, "0 / 60", helps, buttons, focus on Name.
|
||||
8. **Create key: validation, Examples-driven** - the three Outline rows; error text, no request,
|
||||
errors clear when fixed.
|
||||
9. **Create key: name too long** - 75 characters; counter, error class and text, no request.
|
||||
10. **Create key: success** - one POST with `{"name":"Nightly media import"}` and no expires_at
|
||||
key; the reveal: title, text, warning alert, key equal to the mocked `key`, "Copy", note, only
|
||||
"Done".
|
||||
11. **Create key: expiry** - date D + 30 days; assert expires_at is 23:59:59 local on that day
|
||||
with the local offset. Examples today (sent), yesterday (blocked), tomorrow (sent); build the
|
||||
dates from `new Date()` in the test.
|
||||
12. **Reveal: copied** - fake timers; click "Copy"; writeText with the full key, icon check,
|
||||
"Copied", aria-live announcement; advance 2 s; "Copy" again.
|
||||
13. **Reveal: Done and Escape discard** - assert the modal is gone, the key string appears nowhere
|
||||
in `wrapper.html()`, the router URL, localStorage or sessionStorage; the new row shows the
|
||||
prefix only, status "active", "Never", created by the session user; no second GET; a reopened
|
||||
form is empty. A backdrop click leaves the reveal open.
|
||||
14. **Create key: Cancel and Escape** - no request, empty on reopen, focus back on the opener;
|
||||
a backdrop click does not close.
|
||||
15. **Revoke: confirm and Keep key** - dialog copy with the 9-character prefix, both buttons;
|
||||
"Keep key" closes with no request.
|
||||
16. **Revoked** - confirm; one DELETE with the key's id; row "revoked", muted, no "Revoke"; toast
|
||||
title and text; no second GET.
|
||||
17. **Not drawn: Create sending** - pending POST; "Creating…", disabled fields and Cancel, Escape
|
||||
ignored.
|
||||
18. **Not drawn: Create failed, Examples-driven** - ApiError(500) "Couldn't create the key. Try
|
||||
again in a moment.", NetworkError "Couldn't reach RenewCMS. Check your connection and try
|
||||
again.", ApiError(429) "Too many requests. Wait a moment, then try again.", ApiError(400)
|
||||
"Something in the form isn't valid. Check the highlighted fields."; values kept, form
|
||||
re-enabled, no row added; submit again, resolve 201, assert the reveal.
|
||||
19. **Not drawn: Revoke sending** - "Revoking…", both buttons disabled, Escape ignored.
|
||||
20. **Not drawn: Revoke failed, Examples-driven** - ApiError(500) "Couldn't revoke the key. Try
|
||||
again in a moment." and NetworkError "Couldn't reach RenewCMS. Check your connection and try
|
||||
again."; the notice in the open dialog, row unchanged; retry succeeds.
|
||||
21. **Not drawn: Revoke 404** - the dialog closes, the row is removed, the error toast "That key no
|
||||
longer exists.".
|
||||
22. **Not drawn: Last used "Never"** - null `last_used_at`, desktop cell and mobile card.
|
||||
23. **Mobile pinned button** - below md the pinned 48 px "Create key" exists in list, loading and
|
||||
error; hidden while a modal is open and in Empty; no header button below md.
|
||||
24. **Integration link and navigation** - on /integration assert "Manage API keys" is a link to
|
||||
/integration/api-keys below the three info notes; navigate; assert the sidebar and drawer
|
||||
"Integration" item has aria-current="page" on /integration/api-keys. Update the existing
|
||||
integration specs (features/integration.qa.md case 1) for the extra link.
|
||||
25. **French** - `setLocale('fr')`; walk cases 1, 4, 7, 10, 15, 16, 17, 21; no visible English
|
||||
source string remains; dates use the French format.
|
||||
26. **Messages** - every new `t()` key has a French entry (extend the i18n spec pattern).
|
||||
|
||||
Un-run web tests are reported as NOT RUN, never as passing.
|
||||
|
||||
## Visual (`task visual:check -- integration-api-keys`, desktop and mobile, light and dark)
|
||||
|
||||
Reference: docs/design/screens/integration.md, board `docs/design/source/RenewCMS Screens API
|
||||
keys.dc.html`, exact values in `docs/design/source/ApiKeysPage.dc.html`. Add each state's setup to
|
||||
`web/visual/states.ts` with the board's own sample data (mocked GET /v1/api-key responses include
|
||||
`created_by_name` and 12-character prefixes whose first 9 characters match the board). Hard gate:
|
||||
every capture of every state within 10 %.
|
||||
|
||||
Sample data: the owner and admin fixtures from the feature's Background; Create modal name
|
||||
"Nightly media import" (20 / 60) and expiry 31 Dec 2026; validation: empty name (0 / 60) and
|
||||
expiry 12 Mar 2026; too long: "Nightly import of the new media library from the Brussels office
|
||||
file server" (75 / 60); reveal key rcms_Kf3x9QwL0aBcT7nV2uYdE5sHjR8mPz4WqXg6C1oIyNe for
|
||||
"Nightly media import"; revoke and toast for "Nightly media import" (rcms_Mq7b…).
|
||||
|
||||
No state is clock-sensitive, since every date is fixed text. The Create sample expiry 31 Dec 2026
|
||||
becomes a past date after that day, but the state only displays it, so it gets no skip.
|
||||
|
||||
States:
|
||||
- [ ] Owner: list
|
||||
- [ ] Admin: own keys only
|
||||
- [ ] Loading (the setup holds the request)
|
||||
- [ ] Empty
|
||||
- [ ] Error
|
||||
- [ ] Create key
|
||||
- [ ] Create key: validation
|
||||
- [ ] Create key: name too long
|
||||
- [ ] One-time reveal
|
||||
- [ ] One-time reveal: copied (timer-driven, so it is checked)
|
||||
- [ ] Revoke: confirm
|
||||
- [ ] Revoked (list with the revoked row and the toast)
|
||||
- [ ] Layout from the page component, not components.md: 36 px header, 48 px rows, 20 px status
|
||||
badge; desktop modal 480 px wide 120 px from the top; mobile modal full width, bottom-aligned,
|
||||
buttons stacked with Cancel under the primary; mobile card Revoke 44 px; toast 320 px wide
|
||||
bottom-right on desktop and 16 px inset on mobile.
|
||||
- [ ] Not drawn on the board, no visual state, Vitest only: Create sending, Create failed (500,
|
||||
network, 429, 400), Revoke sending, Revoke failed, Revoke 404, "Never", the dismissal rules,
|
||||
and the Integration "Manage API keys" link.
|
||||
|
||||
Risk: the mobile pinned "Create key" button is not on the board, and the Integration link is not
|
||||
on the board's frames for the current Integration page. Either may push a mobile or Integration
|
||||
capture over 10 %. Re-run `task visual:check -- integration` and the API keys screen. If either
|
||||
fails, the user must decide: an approved per-state exception needs `approvedBy`, or a design
|
||||
update.
|
||||
|
||||
Manual checks screenshots cannot cover:
|
||||
- Keyboard and focus order: Tab reaches "Create key", then each "Revoke" in row order; modal focus
|
||||
starts on Name, is trapped, and returns to the opener on close; the reveal's initial focus lands
|
||||
on "Copy".
|
||||
- Hover and motion: outline and primary button hover; modal motion; skeleton pulse stopped under
|
||||
reduced motion.
|
||||
|
||||
## Manual verification
|
||||
|
||||
- Real round trip against `task dev`: create a key, copy it, run
|
||||
`curl -H "Authorization: Bearer <key>" <origin>/v1/auth/me` and get 200; revoke it from the
|
||||
screen and get 401; confirm the key gets 403 "This action needs a real session." on
|
||||
/v1/api-key.
|
||||
- Owner and admin: as owner confirm the Created by names (display name, else username); as admin
|
||||
confirm only your own keys and no Created by column.
|
||||
- Reset-password revocation: reset a user's password and confirm their keys show "revoked" after
|
||||
reload.
|
||||
- Clipboard on a real HTTPS or localhost origin.
|
||||
|
||||
## French strings for web/src/i18n/messages.ts
|
||||
|
||||
Keyed by the English text. `{0}` and `{1}` are the `t()` placeholders.
|
||||
|
||||
- API keys = Clés d'API
|
||||
- Integration › API keys = Intégration › Clés d'API
|
||||
- Create key = Créer une clé
|
||||
- Name = Nom
|
||||
- Key = Clé
|
||||
- Status = Statut
|
||||
- Created by = Créée par
|
||||
- Created = Créée le
|
||||
- Last used = Dernière utilisation
|
||||
- Expires = Expire le
|
||||
- active = active
|
||||
- expired = expirée
|
||||
- revoked = révoquée
|
||||
- Revoke = Révoquer
|
||||
- None = Aucune
|
||||
- Never = Jamais
|
||||
- Keys act as the user who created them. As an owner you see everyone's keys. = Les clés agissent comme l'utilisateur qui les a créées. En tant que propriétaire, vous voyez les clés de tout le monde.
|
||||
- Keys act as you, with your role. You only see your own keys. = Les clés agissent en votre nom, avec votre rôle. Vous ne voyez que vos propres clés.
|
||||
- Resetting a user's password revokes all of their keys. = Réinitialiser le mot de passe d'un utilisateur révoque toutes ses clés.
|
||||
- No API keys yet = Aucune clé d'API pour l'instant
|
||||
- Create a key to call the API from a script or service. = Créez une clé pour appeler l'API depuis un script ou un service.
|
||||
- Couldn't load your API keys = Impossible de charger vos clés d'API
|
||||
- Check your connection and try again. = Vérifiez votre connexion et réessayez.
|
||||
- Try again = Réessayer
|
||||
- Create API key = Créer une clé d'API
|
||||
- The key acts as you, with your role. It is shown in full once. = La clé agit en votre nom, avec votre rôle. Elle n'est affichée en entier qu'une seule fois.
|
||||
- Required. Up to 60 characters. = Obligatoire. 60 caractères maximum.
|
||||
- Expiry date (optional) = Date d'expiration (facultative)
|
||||
- Optional. Must be in the future. Leave it empty for a key that does not expire. = Facultative. Doit être dans le futur. Laissez vide pour une clé qui n'expire pas.
|
||||
- Enter a name. = Saisissez un nom.
|
||||
- Use 60 characters or fewer. = Utilisez 60 caractères ou moins.
|
||||
- Choose a date in the future. = Choisissez une date dans le futur.
|
||||
- Cancel = Annuler
|
||||
- Your new API key = Votre nouvelle clé d'API
|
||||
- "{0}" is ready. Copy the key and store it somewhere safe. = « {0} » est prête. Copiez la clé et conservez-la en lieu sûr.
|
||||
- You won't be able to see this key again. = Vous ne pourrez plus revoir cette clé.
|
||||
- Copy = Copier
|
||||
- Copied = Copié
|
||||
- Closing this window discards the key from the screen. Copy it first. = Fermer cette fenêtre supprime la clé de l'écran. Copiez-la d'abord.
|
||||
- Done = Terminé
|
||||
- Revoke this key? = Révoquer cette clé ?
|
||||
- "{0}" ({1}) will stop working right away. Requests that use it answer 401. This can't be undone. = « {0} » ({1}) cessera de fonctionner immédiatement. Les requêtes qui l'utilisent recevront une réponse 401. Cette action est irréversible.
|
||||
- Keep key = Garder la clé
|
||||
- Revoke key = Révoquer la clé
|
||||
- Key revoked = Clé révoquée
|
||||
- "{0}" can no longer be used. = « {0} » ne peut plus être utilisée.
|
||||
- Creating… = Création…
|
||||
- Revoking… = Révocation…
|
||||
- Couldn't create the key. Try again in a moment. = Impossible de créer la clé. Réessayez dans un instant.
|
||||
- Couldn't reach RenewCMS. Check your connection and try again. = Impossible de joindre RenewCMS. Vérifiez votre connexion et réessayez.
|
||||
- Too many requests. Wait a moment, then try again. = Trop de requêtes. Patientez un instant, puis réessayez.
|
||||
- Something in the form isn't valid. Check the highlighted fields. = Un élément du formulaire n'est pas valide. Vérifiez les champs signalés.
|
||||
- Couldn't revoke the key. Try again in a moment. = Impossible de révoquer la clé. Réessayez dans un instant.
|
||||
- That key no longer exists. = Cette clé n'existe plus.
|
||||
- Manage API keys = Gérer les clés d'API
|
||||
@@ -0,0 +1,229 @@
|
||||
Feature: Article body content negotiation on read
|
||||
|
||||
As a headless frontend developer
|
||||
I want article routes to return the body as markdown (default), html or a typed json block array
|
||||
So that my client can render it without handling editor HTML
|
||||
|
||||
Background:
|
||||
Given article bodies are stored as Tiptap HTML
|
||||
And storage, the POST /v1/article body and the PATCH /v1/article/{id} body stay HTML and are unchanged
|
||||
And internal/domain/article defines BodyFormat with the values "markdown", "html" and "json"
|
||||
And internal/domain/article defines the port BodyRenderer and the sentinel ErrUnsupportedBodyFormat
|
||||
And ParseBodyFormat matches case-insensitively, treats an empty value as "markdown", and returns ErrUnsupportedBodyFormat otherwise
|
||||
And the use cases receive the BodyRenderer through their constructors, the handler only reads the "format" query value, and only api/dependecyInjection.go builds the converter
|
||||
And every article object in a response has the snake_case fields id, title, body, body_format, is_online, created_at, updated_at
|
||||
And body_format is "markdown", "html" or "json" and always names the format of body
|
||||
And for markdown and html, body is a JSON string; for json, body is a JSON array of blocks (not an escaped string)
|
||||
And the covered routes are GET /v1/article/, GET /v1/article/{id}, POST /v1/article/, PATCH /v1/article/{id}, PATCH /v1/article/{id}/publish and PATCH /v1/article/{id}/unpublish
|
||||
And visibility is unchanged: anonymous and unverified callers see only online articles, and an offline article reads as 404 "Article not found"
|
||||
And an unsupported format answers 400 with apperr.ArticleBodyFormatErrorMessage as plain text, before any article lookup or write
|
||||
And an invalid id answers apperr.IdUint32ErrorMessage first, ahead of the format check
|
||||
And a repeated "format" parameter uses its first value
|
||||
And a renderer failure answers 500 "Internal server error"
|
||||
And article 1 is online, titled "Backyard Renovation Update", with body "<h2>Plan</h2><p>Replace the <strong>old</strong> deck.</p>"
|
||||
|
||||
Scenario Outline: Single read negotiates the body format
|
||||
When an anonymous client sends GET /v1/article/1<query>
|
||||
Then the response status is 200
|
||||
And "body" is <body>
|
||||
And "body_format" is "<body_format>"
|
||||
|
||||
Examples:
|
||||
| query | body | body_format |
|
||||
| | "## Plan\n\nReplace the **old** deck." | markdown |
|
||||
| ?format= | "## Plan\n\nReplace the **old** deck." | markdown |
|
||||
| ?format=markdown | "## Plan\n\nReplace the **old** deck." | markdown |
|
||||
| ?format=MarkDown | "## Plan\n\nReplace the **old** deck." | markdown |
|
||||
| ?format=html | "<h2>Plan</h2><p>Replace the <strong>old</strong> deck.</p>" | html |
|
||||
| ?format=HTML | "<h2>Plan</h2><p>Replace the <strong>old</strong> deck.</p>" | html |
|
||||
| ?format=json | [{"type":"heading","level":2,"children":[{"type":"text","text":"Plan","marks":[]}]},{"type":"paragraph","children":[{"type":"text","text":"Replace the ","marks":[]},{"type":"text","text":"old","marks":[{"type":"bold"}]},{"type":"text","text":" deck.","marks":[]}]}] | json |
|
||||
| ?format=JSON | the same array as ?format=json | json |
|
||||
|
||||
Scenario: List read negotiates every element
|
||||
Given the repository also holds online article 3 with body "<p>Second</p>"
|
||||
When an anonymous client sends GET /v1/article/
|
||||
Then every element has body_format "markdown" and article 3 has body "Second"
|
||||
When an anonymous client sends GET /v1/article/?format=html
|
||||
Then every element has body_format "html" and its stored HTML as body
|
||||
When an anonymous client sends GET /v1/article/?format=json
|
||||
Then every element has body_format "json" and article 3 has body [{"type":"paragraph","children":[{"type":"text","text":"Second","marks":[]}]}]
|
||||
|
||||
Scenario Outline: An unsupported format is rejected
|
||||
When an anonymous client sends GET <path>
|
||||
Then the response status is 400
|
||||
And the response body is apperr.ArticleBodyFormatErrorMessage followed by a newline
|
||||
And no use case reads or renders an article
|
||||
|
||||
Examples:
|
||||
| path |
|
||||
| /v1/article/1?format=pdf |
|
||||
| /v1/article/?format=xml |
|
||||
| /v1/article/9999?format=pdf |
|
||||
| /v1/article/1?format=md |
|
||||
|
||||
Scenario: An invalid id is reported before an invalid format
|
||||
When an anonymous client sends GET /v1/article/abc?format=pdf
|
||||
Then the response status is 400
|
||||
And the response body is apperr.IdUint32ErrorMessage followed by a newline
|
||||
|
||||
Scenario: The first repeated format parameter wins
|
||||
When an anonymous client sends GET /v1/article/1?format=html&format=json
|
||||
Then "body_format" is "html"
|
||||
|
||||
Scenario: Offline articles stay hidden whatever the format
|
||||
Given article 2 is offline
|
||||
When an anonymous client sends GET /v1/article/2?format=json
|
||||
Then the response status is 404 and the body is "Article not found"
|
||||
|
||||
Scenario Outline: Authenticated routes negotiate the response body
|
||||
Given a valid jwt cookie for a verified user with id 1
|
||||
When the client sends <method> <path> with <request_body>
|
||||
Then the response status is <status>
|
||||
And "body_format" is "<body_format>"
|
||||
And the stored body is the HTML that was sent, never markdown or json
|
||||
|
||||
Examples:
|
||||
| method | path | request_body | status | body_format |
|
||||
| POST | /v1/article/ | {"title":"Deck","body":"<p>A</p>"} | 201 | markdown |
|
||||
| POST | /v1/article/?format=html | {"title":"Deck","body":"<p>A</p>"} | 201 | html |
|
||||
| POST | /v1/article/?format=json | {"title":"Deck","body":"<p>A</p>"} | 201 | json |
|
||||
| PATCH | /v1/article/1 | {"body":"<p>B</p>"} | 200 | markdown |
|
||||
| PATCH | /v1/article/1?format=json | {"body":"<p>B</p>"} | 200 | json |
|
||||
| PATCH | /v1/article/1/publish | | 200 | markdown |
|
||||
| PATCH | /v1/article/1/unpublish?format=html | | 200 | html |
|
||||
|
||||
Scenario: An unsupported format on a write route changes nothing
|
||||
Given a valid jwt cookie for a verified user with id 1
|
||||
When the client sends PATCH /v1/article/1?format=pdf with {"body":"<p>B</p>"}
|
||||
Then the response status is 400
|
||||
And the stored body of article 1 is unchanged
|
||||
When the client sends POST /v1/article/?format=pdf with {"title":"Deck","body":"<p>A</p>"}
|
||||
Then the response status is 400 and no article is created
|
||||
|
||||
Scenario: The authenticated list includes offline articles in the negotiated format
|
||||
Given a valid jwt cookie for a verified user and offline article 2
|
||||
When the client sends GET /v1/article/?format=json
|
||||
Then the array contains articles 1 and 2 with body_format "json"
|
||||
|
||||
Scenario: A converter failure answers 500
|
||||
Given the BodyRenderer fails on its next call
|
||||
When an anonymous client sends GET /v1/article/1
|
||||
Then the response status is 500 and the body is "Internal server error"
|
||||
|
||||
Scenario Outline: Markdown fidelity for Tiptap output
|
||||
Given the stored body is <html>
|
||||
When converted with the format "markdown"
|
||||
Then the body is <markdown>
|
||||
|
||||
Examples:
|
||||
| html | markdown |
|
||||
| <h1>T</h1><h3>S</h3> | # T\n\n### S |
|
||||
| <p><strong>b</strong> <em>i</em></p> | **b** *i* |
|
||||
| <p><a href="https://example.com/x">link</a></p> | [link](https://example.com/x) |
|
||||
| <ul><li><p>a</p></li><li><p>b</p></li></ul> | - a\n- b |
|
||||
| <ol><li><p>a</p></li><li><p>b</p></li></ol> | 1. a\n2. b |
|
||||
| <ul><li data-indent="2"><p>a</p></li></ul> | - a |
|
||||
| <blockquote><p>q</p></blockquote> | > q |
|
||||
| <pre><code class="language-go">x := 1</code></pre> | ```go\nx := 1\n``` |
|
||||
| <hr> | --- |
|
||||
| <img src="/static/uploadedImages/a.png" alt="A"> |  |
|
||||
| <p>ok</p><script>alert(1)</script><style>p{}</style> | ok |
|
||||
| <p>x<span style="color:red">y</span></p> | xy |
|
||||
| <p>use <code>go test</code></p> | use `go test` |
|
||||
|
||||
Scenario Outline: Json block shapes, one row per block and mark type
|
||||
Given the stored body is <html>
|
||||
When converted with the format "json"
|
||||
Then the body is <json>
|
||||
|
||||
Examples:
|
||||
| html | json |
|
||||
| <h1>T</h1> | [{"type":"heading","level":1,"children":[{"type":"text","text":"T","marks":[]}]}] |
|
||||
| <h6>S</h6> | [{"type":"heading","level":6,"children":[{"type":"text","text":"S","marks":[]}]}] |
|
||||
| <p>plain</p> | [{"type":"paragraph","children":[{"type":"text","text":"plain","marks":[]}]}] |
|
||||
| <p></p> | [{"type":"paragraph","children":[]}] |
|
||||
| <p><strong>b</strong></p> | [{"type":"paragraph","children":[{"type":"text","text":"b","marks":[{"type":"bold"}]}]}] |
|
||||
| <p><em>i</em></p> | [{"type":"paragraph","children":[{"type":"text","text":"i","marks":[{"type":"italic"}]}]}] |
|
||||
| <p><a href="https://example.com/x">l</a></p> | [{"type":"paragraph","children":[{"type":"text","text":"l","marks":[{"type":"link","href":"https://example.com/x"}]}]}] |
|
||||
| <p><a href="/a"><strong><em>x</em></strong></a></p> | [{"type":"paragraph","children":[{"type":"text","text":"x","marks":[{"type":"link","href":"/a"},{"type":"bold"},{"type":"italic"}]}]}] |
|
||||
| <p>a<br>b</p> | [{"type":"paragraph","children":[{"type":"text","text":"a\nb","marks":[]}]}] |
|
||||
| <ul><li><p>a</p></li><li><p>b</p></li></ul> | [{"type":"list","ordered":false,"items":[[{"type":"paragraph","children":[{"type":"text","text":"a","marks":[]}]}],[{"type":"paragraph","children":[{"type":"text","text":"b","marks":[]}]}]]}] |
|
||||
| <ol><li><p>a</p></li></ol> | [{"type":"list","ordered":true,"items":[[{"type":"paragraph","children":[{"type":"text","text":"a","marks":[]}]}]]}] |
|
||||
| <ul><li>bare</li></ul> | [{"type":"list","ordered":false,"items":[[{"type":"paragraph","children":[{"type":"text","text":"bare","marks":[]}]}]]}] |
|
||||
| <ul><li><p>a</p><ul><li><p>n</p></li></ul></li></ul> | a list item whose blocks are the paragraph "a" followed by a nested list block with ordered false and the item "n" |
|
||||
| <ul><li data-indent="2"><p>a</p></li></ul> | the same output as without data-indent |
|
||||
| <blockquote><p>q</p></blockquote> | [{"type":"blockquote","children":[{"type":"paragraph","children":[{"type":"text","text":"q","marks":[]}]}]}] |
|
||||
| <pre><code class="language-go">x := 1</code></pre> | [{"type":"code","language":"go","text":"x := 1"}] |
|
||||
| <pre><code>raw</code></pre> | [{"type":"code","language":"","text":"raw"}] |
|
||||
| <hr> | [{"type":"hr"}] |
|
||||
| <img src="/static/uploadedImages/a.png" alt="A"> | [{"type":"image","src":"/static/uploadedImages/a.png","alt":"A"}] |
|
||||
| <img src="/static/uploadedImages/a.png"> | [{"type":"image","src":"/static/uploadedImages/a.png","alt":""}] |
|
||||
| <p>x<img src="/i.png" alt="I">y</p> | [{"type":"paragraph","children":[{"type":"text","text":"x","marks":[]}]},{"type":"image","src":"/i.png","alt":"I"},{"type":"paragraph","children":[{"type":"text","text":"y","marks":[]}]}] |
|
||||
| <p>x<span style="color:red">y</span></p> | [{"type":"paragraph","children":[{"type":"text","text":"xy","marks":[]}]}] |
|
||||
| <p>use <code>go test</code></p> | [{"type":"paragraph","children":[{"type":"text","text":"use go test","marks":[]}]}] |
|
||||
| <p>ok</p><script>alert(1)</script><style>p{}</style> | [{"type":"paragraph","children":[{"type":"text","text":"ok","marks":[]}]}] |
|
||||
|
||||
Scenario Outline: Text alignment survives the conversion
|
||||
Given the stored body is <html>
|
||||
When converted with the format "markdown"
|
||||
Then the body is <markdown>
|
||||
When converted with the format "json"
|
||||
Then the body is <json>
|
||||
|
||||
Examples:
|
||||
| html | markdown | json |
|
||||
| <p style="text-align: center">a</p> | <div style="text-align: center">
|
||||
|
||||
a
|
||||
|
||||
</div> | [{"type":"paragraph","align":"center","children":[{"type":"text","text":"a","marks":[]}]}] |
|
||||
| <h2 style="text-align:right">T</h2> | <div style="text-align: right">
|
||||
|
||||
## T
|
||||
|
||||
</div> | [{"type":"heading","level":2,"align":"right","children":[{"type":"text","text":"T","marks":[]}]}] |
|
||||
| <p style="text-align: JUSTIFY">a</p> | <div style="text-align: justify">
|
||||
|
||||
a
|
||||
|
||||
</div> | [{"type":"paragraph","align":"justify","children":[{"type":"text","text":"a","marks":[]}]}] |
|
||||
| <p style="text-align: left">a</p> | a | [{"type":"paragraph","children":[{"type":"text","text":"a","marks":[]}]}] |
|
||||
| <p style="text-align: start">a</p> | a | the same output as the left row |
|
||||
| <p style="text-align: center"></p> | an empty string | [{"type":"paragraph","align":"center","children":[]}] |
|
||||
|
||||
Scenario Outline: Plain text that looks like markdown stays plain text
|
||||
Given the stored body is <html>
|
||||
When converted with the format "markdown"
|
||||
Then the body is <markdown>
|
||||
|
||||
Examples:
|
||||
| html | markdown |
|
||||
| <p># not a heading</p> | \# not a heading |
|
||||
| <p>#tag</p> | #tag |
|
||||
| <p>- not a list</p> | \- not a list |
|
||||
| <p>+ not a list</p> | \+ not a list |
|
||||
| <p>> not a quote</p> | \> not a quote |
|
||||
| <p>1. not a list</p> | 1\. not a list |
|
||||
| <p>2) not a list</p> | 2\) not a list |
|
||||
| <p>---</p> | \--- |
|
||||
| <p>a - b</p> | a - b |
|
||||
| <p>a * b _c_</p> | a \* b \_c\_ |
|
||||
| <p>a<br>- b</p> | a\n\- b |
|
||||
|
||||
Scenario: The editor lets the author align text
|
||||
Given the article editor registers the TextAlign extension for paragraphs and headings
|
||||
Then the left, center, right and justify toolbar buttons are enabled
|
||||
And clicking center writes style="text-align: center;" on the current paragraph or heading
|
||||
And paragraphs and headings that were never aligned carry no style attribute
|
||||
|
||||
Scenario: The SPA asks for html explicitly
|
||||
Given no visual change is expected, so docs/design is not consulted
|
||||
When EditorView loads an article, or ArticleView or HomeView load the list
|
||||
Then each request is /v1/article/{id}?format=html or /v1/article/?format=html
|
||||
And the draft save PATCH, the publish and unpublish PATCH and the create POST also carry ?format=html, so a converter failure cannot fail a save
|
||||
And the editor and the image counts receive HTML exactly as before
|
||||
|
||||
Scenario: The documentation reflects the contract
|
||||
Then docs/api has an article read page covering format, the markdown default, body_format, the json block schema, the 400 message and the breaking default change
|
||||
And web/src/views/IntegrationView.vue snippets show ?format
|
||||
And docs/releases has a note stating the default flip and that the SPA sends format=html
|
||||
@@ -0,0 +1,46 @@
|
||||
# QA procedure: article_body_format
|
||||
|
||||
Package: `test` (black-box). New files: `test/article_body_format_test.go`, `test/markdown_converter_test.go`, `test/json_blocks_converter_test.go`. No live server, no real SQLite file, no real SMTP.
|
||||
|
||||
## Setup
|
||||
1. Call `validator.InitValidator()` once.
|
||||
2. Reuse `mockArticleRepo` and `mockUserRepo`. Add a fake `fakeBodyRenderer` with a unique type name. It records each call's format and the html it received. For markdown it returns "MD:"+html. For html it returns the html unchanged. For json it returns `[{"type":"paragraph","children":[{"type":"text","text":"FAKE","marks":[]}]}]`. It has a failure switch.
|
||||
3. Wire the real use cases over the fakes, passing the renderer. Update every existing test that builds these use cases for the new constructor signatures. Build `article.NewHandler(...)`.
|
||||
4. Mount a fresh `chi.NewRouter()` mirroring `api/router.go` for `/v1/article`: `jwtauth.Verifier` on the group, GET `/` and `/{id}` public, and `Authenticator` + `RequireCurrentToken` + `RequireVerifiedUser` for POST, DELETE and PATCH.
|
||||
5. Mint a jwt cookie for user_id 1 with `token.Encode(map[string]any{"user_id": uint32(1)})`. Seed a verified user. Seed articles 1 (online) and 2 (offline).
|
||||
|
||||
## HTTP checks (fake renderer)
|
||||
6. Single read matrix: for each of none, `?format=`, markdown, MarkDown, html, HTML, json, JSON, assert status 200, `body_format`, the renderer's recorded format and the stored HTML passed in. For json, decode `body` and assert it is a JSON array (not a string).
|
||||
7. List with none, `?format=html` and `?format=json`: every element has the matching `body_format`.
|
||||
8. `format=pdf`, `xml` and `md` on single, list and unknown-id paths return 400 with `apperr.ArticleBodyFormatErrorMessage + "\n"`. The renderer and the repo are not called.
|
||||
9. `GET /v1/article/abc?format=pdf` returns 400 with `apperr.IdUint32ErrorMessage + "\n"`.
|
||||
10. `?format=html&format=json` returns html.
|
||||
11. `GET /v1/article/2?format=json` anonymous returns 404 `"Article not found\n"`.
|
||||
12. Write-route matrix with a cookie (POST, PATCH, publish, unpublish, each with none, html and json where listed): assert status, `body_format`, and that the repo holds the HTML that was sent.
|
||||
13. `PATCH /v1/article/1?format=pdf` and `POST /v1/article/?format=pdf` with a cookie return 400. The repo is unchanged and no article is created.
|
||||
14. Authenticated `GET /v1/article/?format=json` includes articles 1 and 2.
|
||||
15. Renderer failure switch, then `GET /v1/article/1` returns 500 `"Internal server error\n"`.
|
||||
|
||||
## Domain
|
||||
16. `ParseBodyFormat`: "", markdown, MARKDOWN, html, Html, json, JSON are accepted (empty returns markdown). pdf, md and " html" return `errors.Is(err, ErrUnsupportedBodyFormat)`.
|
||||
|
||||
## Converter tests (real library, real Tiptap HTML samples)
|
||||
17. `test/markdown_converter_test.go`: every row of the markdown fidelity table, plus a combined document (heading, paragraph with marks, list, image, code block, quote, hr). Assert exact output. For format html, assert the input comes back byte-identical.
|
||||
17b. Alignment and escaping: every row of the alignment and plain-text tables, for markdown and json, in `test/markdown_converter_test.go` and `test/json_blocks_converter_test.go`. `test/body_converter_documents_test.go` covers the combined hostile document (no raw script, style, iframe or span leaks in markdown or json), its block types, and code block text extraction.
|
||||
18. `test/json_blocks_converter_test.go`: every row of the json shapes table. Assert by unmarshalling both sides and comparing with deep equality. This also asserts `marks` is `[]` rather than null or absent, `ordered` is a bool, and code `language` is "" when absent. Also include a combined document with nested list, blockquote and an image inside a paragraph. Assert that script and style content never appears, and that no raw HTML survives in any output for any format except html.
|
||||
19. `test/json_blocks_converter_test.go` also asserts that html "" produces `[]`, and that the output is a non-null JSON array.
|
||||
|
||||
## SPA (Vitest, `task test:web`)
|
||||
20. Mock `/v1/article/12?format=html` and assert `EditorView` requests that URL and loads the HTML body into the draft.
|
||||
21. Assert `useArticles.listArticles` requests `/v1/article/?format=html`.
|
||||
22. Assert the `ArticleView` image count is computed from the HTML.
|
||||
23. Assert `useArticleDraft.save` sends PATCH `/v1/article/{id}?format=html` with the JSON body.
|
||||
24. Reported as NOT RUN if there is no runner. No visual check applies, because no visual change is expected.
|
||||
|
||||
## Docs
|
||||
25. Check that a docs/api article read page, the IntegrationView snippets and a docs/releases note exist as described.
|
||||
|
||||
## Manual verification
|
||||
- In the embedded SPA, edit and save an article against a real SQLite file and confirm the stored body is still HTML.
|
||||
- `curl` the public list and a single article with no format, `?format=html` and `?format=json` against a built binary.
|
||||
- No SMTP involvement.
|
||||
+181
-51
@@ -1,63 +1,193 @@
|
||||
Feature: Integration screen
|
||||
Feature: Integration screen (API reference)
|
||||
|
||||
As a verified RenewCMS owner
|
||||
I want /integration to show my site's base API URL and ready-to-use endpoint examples
|
||||
So that I, or the developer who builds my public site, can wire it up without reading the
|
||||
source
|
||||
As a developer building a frontend or an API-key client for a RenewCMS site
|
||||
I want /integration to be a complete, searchable API reference
|
||||
So that I can call every route a key may call without reading the source
|
||||
|
||||
Background:
|
||||
Given /integration is a verified route (meta.auth "verified") rendered as IntegrationPage
|
||||
inside DashboardShell, per docs/design/routes.md
|
||||
And the screen makes no /v1 calls; api: none (static)
|
||||
And the PageHeader shows title "Connect your website", description "A guide for the developer
|
||||
who builds your public site.", breadcrumb "Integration" (mobile title "Integration"), and no
|
||||
actions
|
||||
And an introductory paragraph reads "RenewCMS is headless: it stores and publishes your
|
||||
articles but doesn't show them to visitors. Your website fetches published articles from the
|
||||
two addresses below and displays them in its own design."
|
||||
And a "Base URL" row shows window.location.origin in a monospace box, with a "Copy" button
|
||||
(icon copy) beside it
|
||||
And two EndpointCard entries follow, in this order:
|
||||
And the PageHeader shows breadcrumb "Integration", title "API reference" and description
|
||||
"Everything a developer needs to build on RenewCMS."
|
||||
And the endpoint catalogue is a typed static data file at web/src/data/apiCatalogue.ts, and the view only renders it
|
||||
And the catalogue holds 20 key-callable endpoints in 4 expandable groups, in this order:
|
||||
| group | routes | endpoints |
|
||||
| Articles | 7 | GET /v1/article/, GET /v1/article/{id}, POST /v1/article/, PATCH /v1/article/{id}, PATCH /v1/article/{id}/publish, PATCH /v1/article/{id}/unpublish, DELETE /v1/article/{id} |
|
||||
| Media | 6 | GET /v1/media/, POST /v1/media/, PATCH /v1/media/{id}, DELETE /v1/media/{id}, POST /v1/media/merge, GET /v1/media/{id}/usage |
|
||||
| Users and invites | 6 | GET /v1/user/, PATCH /v1/user/me, POST /v1/user/invite, DELETE /v1/user/invite/{id}, POST /v1/user/invite/{id}/renew, GET /v1/auth/me |
|
||||
| Settings | 1 | GET /v1/settings |
|
||||
And the "Session only" group has 13 non-expandable rows in 3 sub-groups:
|
||||
| sub-group | rows |
|
||||
| System · owner only | GET /v1/system/update, POST /v1/system/update/check, POST /v1/system/update/download, POST /v1/system/update/restart |
|
||||
| Sign in and account | POST /v1/auth/login, POST /v1/auth/logout, POST /v1/auth/register, POST /v1/auth/verify, DELETE /v1/auth/register, POST /v1/auth/password-reset |
|
||||
| API key management | GET /v1/api-key, POST /v1/api-key, DELETE /v1/api-key/{id} |
|
||||
And a "Public auth flow" sub-list follows with 6 non-expandable rows and the chip "Public":
|
||||
| method | path | description |
|
||||
| GET | /v1/article/ | Lists every online article. |
|
||||
| GET | /v1/article/{id} | Returns one online article. Drafts and unknown ids both return 404. |
|
||||
And each EndpointCard's fetch example uses the current origin as the base of its URL:
|
||||
| path | fetch example |
|
||||
| /v1/article/ | const res = await fetch('{origin}/v1/article/')\nconst articles = await res.json() |
|
||||
| /v1/article/{id} | const res = await fetch('{origin}/v1/article/12')\nif (res.status === 404) return notFound()\nconst article = await res.json() |
|
||||
And each EndpointCard has fetch, curl and Response tabs, with fetch active by default, and its
|
||||
CodeBlock is labelled "JavaScript" with its own ghost "Copy" button
|
||||
And the curl tab's content is a plain curl command built from the current origin (e.g.
|
||||
"curl {origin}/v1/article/" and "curl {origin}/v1/article/12"), and the Response tab's
|
||||
content is a JSON sample built from the real domain Article fields; neither tab is active by
|
||||
default, and neither is visually checked, since the fetch tab is the one shown in the board
|
||||
And three info notes follow the endpoint cards, in this order:
|
||||
- "Anonymous callers only ever get online articles. Drafts stay private until you publish
|
||||
them."
|
||||
- "Images in body use paths like /static/uploadedImages/<uuid>.png. Prefix them with the
|
||||
base URL before rendering."
|
||||
- "Browsers can only call the API from origins listed in the server's CORS setting. Ask
|
||||
whoever runs the server to add your site's address."
|
||||
| GET | /v1/ | Hello world. |
|
||||
| GET | /v1/auth/registration | Whether registration is open. |
|
||||
| POST | /v1/auth/password-reset/confirm | Set a new password with the emailed code. |
|
||||
| GET | /v1/auth/invite | Check an invite code. |
|
||||
| POST | /v1/auth/invite/accept | Accept an invite. |
|
||||
| GET | /healthz | Plain text "ok". Outside /v1. |
|
||||
And every catalogue endpoint has a non-empty description, method, path, access chip, key chip,
|
||||
query-parameter table (or "No query parameters."), request-body table (or "No request body."),
|
||||
fetch, curl and Response examples, and error captions
|
||||
|
||||
Scenario: Default — the page loads with the app's own origin
|
||||
Given the app is served from origin "{origin}"
|
||||
Scenario: Default, every card collapsed
|
||||
When the user navigates to /integration
|
||||
Then the Base URL row shows exactly "{origin}"
|
||||
And the Base URL "Copy" button reads "Copy", not "Copied"
|
||||
And both EndpointCards' fetch examples use "{origin}" as the base of their URL
|
||||
Then the intro reads "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."
|
||||
And a "Base URL" row shows window.location.origin in a monospace box with a "Copy" button (icon copy)
|
||||
And every EndpointCard is collapsed as a 44 px row: method badge, mono path, one-line description, chips, chevron
|
||||
And the sticky section index lists the sections on desktop and a "Jump to" select lists them on mobile
|
||||
|
||||
Scenario: Copied — the Base URL copy button
|
||||
Given the user is on /integration, served from origin "{origin}"
|
||||
When the user activates the Base URL row's "Copy" button
|
||||
Scenario Outline: Method badge and chips per endpoint
|
||||
Then <method> <path> shows the <method> badge, access chip "<access>" and key chip "API key OK"
|
||||
Examples:
|
||||
| method | path | access |
|
||||
| GET | /v1/article/ | Public |
|
||||
| GET | /v1/article/{id} | Public |
|
||||
| POST | /v1/article/ | Verified user |
|
||||
| DELETE | /v1/article/{id} | Verified user |
|
||||
| GET | /v1/media/ | Verified user |
|
||||
| PATCH | /v1/user/me | Verified user |
|
||||
| GET | /v1/auth/me | Verified user |
|
||||
| POST | /v1/user/invite | Owner only |
|
||||
| DELETE | /v1/user/invite/{id} | Owner only |
|
||||
| POST | /v1/user/invite/{id}/renew | Owner only |
|
||||
| GET | /v1/settings | Verified user |
|
||||
|
||||
Scenario: Owner-only invite cards, user-approved divergence from the board
|
||||
Then the three invite cards show "Owner only", where the board shows "Verified user"
|
||||
And each lists a 403 error "Only the owner can do this."
|
||||
And each says it is rate limited and that too many requests answer 429, with no number
|
||||
|
||||
Scenario: Group scrolled, one card expanded
|
||||
When the user activates the "POST /v1/article/" row
|
||||
Then the row's button reports aria-expanded "true"
|
||||
And a "Query parameters" table lists "format", string, optional, "markdown, html or json. Default markdown."
|
||||
And a "Request body" table lists:
|
||||
| Name | Type | Required | Rule |
|
||||
| title | string | Yes | 3 to 200 characters. Can't be changed later. |
|
||||
| body | string | Yes | Up to 10 000 characters. |
|
||||
And tabs fetch, curl and Response show, fetch active, with a CodeBlock labelled "JavaScript" and a ghost "Copy" button
|
||||
And an "Errors" list shows a status chip with a one-line caption for 400, 401
|
||||
|
||||
Scenario: Query parameters table, new UI beyond the board, user-approved
|
||||
Then the "Query parameters" table sits above the "Request body" table in each card
|
||||
And it lists:
|
||||
| route | name | type | required | rule |
|
||||
| every /v1/article route | format | string | no | markdown, html or json. Default markdown. |
|
||||
| GET /v1/media/ | q | string | no | Search text. |
|
||||
| GET /v1/media/ | hash | string | no | SHA-256 of the content, lowercased. |
|
||||
| GET /v1/media/ | cursor | string | no | The next_cursor of the previous page. |
|
||||
| GET /v1/media/ | filter | string | no | all, unused or duplicates. Default all. |
|
||||
| GET /v1/media/ | sort | string | no | newest, oldest, name or largest. Default newest. |
|
||||
| GET /v1/media/ | limit | number | no | 1 to 100. Default 24. |
|
||||
And a card without query parameters shows "No query parameters."
|
||||
|
||||
Scenario Outline: Request body fields come from the handler validate tags
|
||||
Then <method> <path> lists these fields: <fields>
|
||||
Examples:
|
||||
| method | path | fields |
|
||||
| POST | /v1/article/ | title string required 3-200; body string required max 10000 |
|
||||
| PATCH | /v1/article/{id} | body string required max 10000 |
|
||||
| PATCH | /v1/media/{id} | filename string required |
|
||||
| POST | /v1/media/merge | keep_id number required >0; merge_ids number[] required min 1 each >0 |
|
||||
| POST | /v1/media/ | multipart/form-data, 1 file field named "file" |
|
||||
| PATCH | /v1/user/me | display_name string required max 60 |
|
||||
| POST | /v1/user/invite | email string required valid email |
|
||||
| GET | /v1/article/ | "No request body." |
|
||||
|
||||
Scenario: Response samples use the real domain JSON field names
|
||||
Then the GET /v1/article/{id} Response sample has exactly the keys id, title, body, body_format, is_online, created_at, updated_at
|
||||
And the sample has no "images" key and no "status" key
|
||||
And POST /v1/media/merge has the keys articles_updated and merged
|
||||
And GET /v1/media/ has the keys items, next_cursor and counts
|
||||
And GET /v1/media/{id}/usage items have the keys id, title, published
|
||||
And PATCH /v1/article/{id}/publish and /unpublish samples are articles with is_online true and false
|
||||
|
||||
Scenario: Article body format
|
||||
Then a note reads "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."
|
||||
And every article card's Errors list includes 400 "The format must be one of: markdown, html, json."
|
||||
|
||||
Scenario: Authentication section
|
||||
Then card "Public" reads "No key needed. Two read-only routes, and only online articles are returned." and names GET /v1/article/ and GET /v1/article/{id}
|
||||
And card "API key" reads "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."
|
||||
And its CodeBlock has tabs curl and fetch for GET /v1/auth/me, using the current origin
|
||||
And it says "Keys start with `rcms_` and are shown in full once, when you create them."
|
||||
And a "Manage API keys" link navigates to /integration/api-keys
|
||||
And Note 1 reads "A key can't create, list or revoke API keys, verify or cancel a registration, 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."
|
||||
And Note 2 reads "Each key can make 120 requests per minute. Beyond that the API answers 429 with a `Retry-After` header."
|
||||
|
||||
Scenario: Session only group
|
||||
Then the banner reads "These routes are made for a signed-in browser session. With an API key, verify, DELETE /auth/register, /api-key/* and /system/* answer 403 "This action needs a real session.""
|
||||
And each row has a dashed border and muted fill, uses no method colour and cannot be expanded
|
||||
And rows that answer 403 to a key show the lock icon and the chip "Session only"
|
||||
And Log in, Log out, Register and Reset password show the caption "Made for the browser. A key is ignored here, with no 403." and no 403 claim
|
||||
And no /v1/system route appears in any expandable group
|
||||
And the "Public auth flow" rows carry the chip "Public" and no lock icon
|
||||
|
||||
Scenario: Errors section
|
||||
Then the intro reads "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."
|
||||
And the table lists:
|
||||
| status | message |
|
||||
| 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. |
|
||||
| 401 | You must be logged in to access this resource. |
|
||||
| 403 | This action needs a real session. / Only the owner can do this. / You must verify your account to access this resource. |
|
||||
| 404 | Article not found / Image not found / Invite not found / API key not found |
|
||||
| 409 | There's already a pending invite for this address. / This invite has already been accepted. |
|
||||
| 429 | Too many requests. Please try again later. |
|
||||
| 500 | Internal server error |
|
||||
And a sample shows "HTTP/1.1 403 Forbidden", "Content-Type: text/plain", a blank line, and "This action needs a real session."
|
||||
And the table does not use the SPA copy of docs/design/states.md
|
||||
|
||||
Scenario Outline: Per-endpoint error captions use the real strings
|
||||
Then <method> <path> lists <status> "<caption>"
|
||||
Examples:
|
||||
| method | path | status | caption |
|
||||
| POST | /v1/media/ | 400 | the image could not be read |
|
||||
| POST | /v1/media/ | 413 | the file exceeds the maximum upload size |
|
||||
| POST | /v1/media/ | 415 | the file must be a PNG, JPEG, WEBP, or SVG image |
|
||||
| GET | /v1/media/ | 400 | The media query is invalid. |
|
||||
| POST | /v1/media/merge | 400 | Choose an image to keep and at least one other image to merge into it. |
|
||||
| POST | /v1/media/merge | 409 | Some of the images to merge changed. Refresh and try again. |
|
||||
| PATCH | /v1/media/{id} | 400 | Enter a filename. |
|
||||
| POST | /v1/article/ | 400 | Article title must be between 3 and 200 characters. |
|
||||
| GET | /v1/article/{id} | 400 | The server expects the ID to be in the format of an unsigned 32-bit integer (uint32). |
|
||||
| PATCH | /v1/user/me | 400 | Display name must be 60 characters or fewer. |
|
||||
| POST | /v1/user/invite | 409 | This address already has an account. |
|
||||
| POST | /v1/user/invite | 409 | There's already a pending invite for this address. |
|
||||
| POST | /v1/user/invite/{id}/renew | 409 | This invite has already been accepted. |
|
||||
| POST | /v1/user/invite | 403 | Only the owner can do this. |
|
||||
|
||||
Scenario: Notes
|
||||
Then the image-prefix note reads "Images in body use paths like /static/uploadedImages/<uuid>.png. Prefix them with the base URL before rendering."
|
||||
And the CORS note reads "Browsers can only call the API from origins listed in the server's CORS setting. Ask whoever runs the server to add your site's address."
|
||||
|
||||
Scenario: Copied, Base URL
|
||||
Given the app is served from origin "{origin}"
|
||||
When the user activates the Base URL "Copy" button
|
||||
Then "{origin}" is written to the clipboard
|
||||
And the button's icon changes to check and its text changes to "Copied"
|
||||
And the change is announced to assistive technology
|
||||
When 2 seconds elapse without a further click
|
||||
Then the button reverts to icon copy and text "Copy"
|
||||
And the button shows icon check and "Copied", announced to assistive technology
|
||||
When 2 seconds elapse
|
||||
Then the button reverts to icon copy and "Copy"
|
||||
|
||||
Scenario: Each EndpointCard's own Copy button is independent of the Base URL's
|
||||
Given the user is on /integration
|
||||
When the user activates the "/v1/article/" EndpointCard's "JavaScript" code block's "Copy"
|
||||
button
|
||||
Then that card's own code is written to the clipboard, and only that button reads "Copied"
|
||||
And the Base URL row's "Copy" button and the other EndpointCard's "Copy" button are unaffected
|
||||
Scenario: Copied, CodeBlock is independent of Base URL
|
||||
Given a card is expanded
|
||||
When the user activates that CodeBlock's "Copy JavaScript example" button
|
||||
Then that card's exact code string is written to the clipboard and only that button reads "Copied"
|
||||
And the Base URL button and other CodeBlocks are unaffected
|
||||
|
||||
Scenario: Examples use the current origin and the API key header
|
||||
Then every fetch and curl example starts from "{origin}" and carries no ?format= query
|
||||
And examples for non-public routes carry "Authorization: Bearer rcms_…"
|
||||
And examples for public routes carry no Authorization header
|
||||
|
||||
Scenario: Navigation
|
||||
When the user activates a section in the index (desktop)
|
||||
Then the page scrolls to that anchor and the item reports aria-current "true"
|
||||
And on mobile the "Jump to" select opens and lists the same sections
|
||||
|
||||
Scenario: The page stays static
|
||||
Then no /v1 request is made while the page renders or while any card is expanded
|
||||
+86
-54
@@ -1,66 +1,98 @@
|
||||
# QA: Integration screen
|
||||
# QA: Integration screen (API reference)
|
||||
|
||||
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
||||
|
||||
Mount IntegrationPage inside DashboardShell with a resolved verified session and a test router at
|
||||
/integration. Stub `window.location.origin` (or the equivalent composable/helper the coder uses to
|
||||
read it) to a fixed value for the test, and stub `navigator.clipboard.writeText` per case. No
|
||||
`/v1` mocks are needed; the screen makes no calls.
|
||||
/integration. Stub `window.location.origin` to `https://cms.renew.example` (the board's sample) and
|
||||
`navigator.clipboard.writeText` per case. No `/v1` mocks are needed. A spec fails if any `/v1` call
|
||||
is made.
|
||||
|
||||
1. **Default** — mount at /integration with origin stubbed to a fixed value (e.g.
|
||||
`https://cms.renew.example`, matching the design board's sample so the assertions read the same
|
||||
as the visual reference); assert breadcrumb "Integration"; assert the PageHeader title
|
||||
"Connect your website" and description "A guide for the developer who builds your public
|
||||
site."; assert the intro paragraph text; assert the Base URL row shows exactly the stubbed
|
||||
origin; assert the Base URL "Copy" button reads "Copy"; assert both EndpointCards render in
|
||||
order (GET /v1/article/, GET /v1/article/{id}) with their descriptions and their fetch examples
|
||||
containing the stubbed origin; assert the fetch tab is active by default on both cards; assert
|
||||
the three info notes render in order.
|
||||
2. **Copied** — from Default, use fake timers; click the Base URL row's "Copy" button; assert
|
||||
`navigator.clipboard.writeText` was called with the stubbed origin; assert the button's icon is
|
||||
check and its text is "Copied"; assert the change is exposed to assistive technology (e.g. an
|
||||
aria-live region or a status role holds "Copied"); advance the fake timer by 2 s; assert the
|
||||
button reverts to icon copy and text "Copy".
|
||||
3. **EndpointCard's own Copy button is independent** — from Default, click the "/v1/article/"
|
||||
card's "JavaScript" CodeBlock's "Copy" button; assert `navigator.clipboard.writeText` was called
|
||||
with that card's exact code string; assert only that button reads "Copied"; assert the Base URL
|
||||
button still reads "Copy" and the other card's Copy button still reads "Copy". This behavior is
|
||||
Vitest-only; it has no visual-check state of its own (see Visual below).
|
||||
4. **curl and Response tabs render, unchecked visually** — from Default, switch the "/v1/article/"
|
||||
card to its curl tab; assert its content is a plain curl command built from the stubbed origin
|
||||
(e.g. "curl https://cms.renew.example/v1/article/"); switch to its Response tab; assert its
|
||||
content is a JSON sample built from the real domain Article fields. Neither tab's content is
|
||||
asserted pixel-for-pixel anywhere, since the design board only ever shows the fetch tab active.
|
||||
Catalogue spec (pure data, no mount, imports web/src/data/apiCatalogue.ts):
|
||||
1. The catalogue holds exactly the 20 expected key-callable routes from an explicit hand-maintained
|
||||
list in the spec (Articles 7, Media 6, Users and invites 6, Settings 1), each once, with no other
|
||||
expandable route. Session only has the 13 rows and Public auth flow the 6 rows listed in the
|
||||
feature, from the same kind of explicit list.
|
||||
2. Every catalogue route has a non-empty `description`. An empty or missing one fails the spec and
|
||||
names the route.
|
||||
3. Every route has method, path, access chip, key chip, a query-parameter list and a body-field list
|
||||
(possibly empty), and fetch, curl and Response examples.
|
||||
4. The Response sample of each route parses as JSON and uses only keys from a fixture of the real
|
||||
fields:
|
||||
- article: id, title, body, body_format, is_online, created_at, updated_at;
|
||||
- media item: id, filename, url, size, content_type, width, height, sha256, uploaded_by,
|
||||
created_at, used_in, duplicate;
|
||||
- media list: items, next_cursor, counts (all, unused, duplicates);
|
||||
- merge: articles_updated, merged;
|
||||
- usage: id, title, published;
|
||||
- user list item: id, kind, username, display_name, email, role, status, created_at;
|
||||
- invite: id, kind, email, status, created_at, expires_at;
|
||||
- settings: version.
|
||||
Any other key fails the spec. "images" and "status" are explicitly rejected on articles.
|
||||
5. Request-body tables equal the validate tags (title 3-200, body max 10000, filename, keep_id,
|
||||
merge_ids, display_name, email). The multipart field is "file". Query tables: `format` on every
|
||||
article route, and q, hash, cursor, filter, sort, limit on GET /v1/media/.
|
||||
6. The three invite routes carry "Owner only", a 403 "Only the owner can do this." caption and the
|
||||
rate-limit sentence. No /v1/system route is in an expandable group. Login, Log out, Register and
|
||||
Reset password rows carry no 403 claim. Verify, DELETE /auth/register, /api-key/* and
|
||||
/system/* are the only rows that claim 403.
|
||||
7. Error captions equal fixtures copied from api/pkg/apperr/messages.go and the image domain
|
||||
errors (413, 415, 400 on upload).
|
||||
|
||||
Component specs, one per design state:
|
||||
1. **Default**: breadcrumb, title "API reference", description, intro, Base URL equals the stubbed
|
||||
origin, all cards collapsed (aria-expanded "false"), section index entries present, the three
|
||||
invite rows show "Owner only".
|
||||
2. **Group scrolled, one card expanded**: click the POST /v1/article/ row. Assert the Query
|
||||
parameters table above the Request body table, the body rows, tabs fetch/curl/Response with fetch
|
||||
active, the "JavaScript" CodeBlock, and the Errors list with 400 and 401.
|
||||
3. **Copied: base URL**: fake timers; click Copy. Clipboard gets the origin; check icon and "Copied";
|
||||
announced; reverts after 2 s.
|
||||
4. **Copied: CodeBlock**: expand a card; click "Copy JavaScript example". Clipboard gets that code,
|
||||
only that button reads "Copied", and it reverts after 2 s.
|
||||
5. **Authentication**: both cards, curl/fetch tabs for GET /v1/auth/me, the "Manage API keys" link
|
||||
href /integration/api-keys, Note 1, Note 2.
|
||||
6. **Session only**: the corrected banner; lock icon and "Session only" chip only on rows that
|
||||
answer 403; the caption on the login family; no expand control; the "Public auth flow" rows with
|
||||
the "Public" chip.
|
||||
7. **Errors**: table rows 400, 401, 403, 404, 409, 429, 500 with the real strings and the 403
|
||||
sample block.
|
||||
8. **Navigation**: clicking an index item sets aria-current and scrolls to its anchor; the mobile
|
||||
"Jump to" lists the same sections.
|
||||
9. **Tabs**: curl and Response render for a card. curl contains the stubbed origin and the
|
||||
Authorization header only on non-public routes. Not visually checked.
|
||||
10. **Notes**: format note, image-prefix note, CORS note.
|
||||
|
||||
## Visual (`task visual:check -- integration`, desktop and mobile, light and dark)
|
||||
|
||||
Reference: `docs/design/screens/integration.md` and
|
||||
`docs/design/source/RenewCMS Screens Back-office.dc.html`, group "Integration"; layout detail from
|
||||
`docs/design/source/AppFrame.dc.html`'s `isInteg` block.
|
||||
Reference: docs/design/screens/integration.md; board "Integration" drawn by
|
||||
docs/design/source/IntegrationPage.dc.html. Serve the SPA under `https://cms.renew.example`. Mocks
|
||||
reuse the board's script data: BASE, KEY, group and endpoint descriptions, the request bodies
|
||||
(for example the "Choosing tiles for a small bathroom" article). Response samples are not compared;
|
||||
the Response tab is never active in a board frame.
|
||||
|
||||
The visual-check setup for this screen serves the SPA under `https://cms.renew.example` via
|
||||
Playwright request routing, so the real `window.location.origin` the running app reads matches the
|
||||
board's sample text exactly; no production test hook or origin stub is needed in app code.
|
||||
Pre-approved exceptions: the user pre-approved visual exceptions for Session only, Group scrolled
|
||||
one card expanded, Errors and Default. For each of these four states the coder measures the real
|
||||
diff, sets the smallest `maxPercent` that is sufficient, writes the reason, and records
|
||||
`approvedBy` "Florian Sylvain". The other states must still pass 10 %.
|
||||
|
||||
- [ ] Default state: PageHeader ("Connect your website" / description), intro paragraph, Base URL
|
||||
row with monospace text and a "Copy" button (icon copy), two EndpointCards in order with
|
||||
their GET badge, path, description, fetch/curl/Response tabs (fetch active), JavaScript
|
||||
CodeBlock and its own "Copy" button, and the three info notes below — matches the board
|
||||
exactly at desktop and mobile, light and dark. Sample data for the mocked run: origin
|
||||
`https://cms.renew.example`, served as above.
|
||||
- [ ] Copied state: the Base URL button shows the check icon and "Copied" text, in the success
|
||||
color, matching the board's `copied: true` frame. This state is timer-driven, not
|
||||
date-driven, so it is not clock-sensitive and gets a real visual check, not a skip.
|
||||
- [ ] Keyboard/focus (manual, not a screenshot check): Tab order reaches the Base URL "Copy"
|
||||
button, then each EndpointCard's tab strip (fetch/curl/Response, reachable and operable with
|
||||
arrow keys per UTabs), then that card's own CodeBlock "Copy" button, then the pre's
|
||||
`tabindex="0"` for scrolling; Enter/Space activates each Copy button.
|
||||
- [ ] Hover (manual): ghost Copy buttons show a hover state consistent with other ghost buttons
|
||||
elsewhere in the app (UserMenu, ArticleTable row menu).
|
||||
- [ ] Default (exception: owner-only chips and rate-limit line)
|
||||
- [ ] Group scrolled, one card expanded (exception: Query parameters table)
|
||||
- [ ] Copied: base URL (must pass 10 %)
|
||||
- [ ] Copied: CodeBlock (must pass 10 %)
|
||||
- [ ] Authentication (must pass 10 %; Note 1 text changed)
|
||||
- [ ] Session only (exception: banner, 13th row, captions, Public auth flow block)
|
||||
- [ ] Errors (exception: 409 row)
|
||||
- [ ] Navigation (must pass 10 %)
|
||||
|
||||
## Manual verification
|
||||
None of these states is clock-sensitive, so none is skipped.
|
||||
|
||||
- Confirm the real running app's `window.location.origin` (e.g. `https://your-domain.example` in
|
||||
production, or `http://localhost:8080` under `task dev`) renders correctly in the Base URL row
|
||||
and in both fetch examples, since Vitest only ever exercises a stubbed origin, and
|
||||
`visual:check` only ever exercises the routed `https://cms.renew.example` origin.
|
||||
## Manual
|
||||
- Keyboard and focus order: index, Base URL Copy, each row (Enter/Space), tab strip (arrow keys),
|
||||
CodeBlock Copy, the pre (tabindex 0), Jump to on mobile.
|
||||
- Hover and motion on ghost Copy buttons and rows.
|
||||
- Find-in-page and a deep link to an `#ep-...` anchor.
|
||||
- Real origin in a production build and under `task dev`.
|
||||
- Run each documented example against a running server with a real `rcms_` key, including the
|
||||
403 on a session-only route and the owner-only 403 for an admin key on the invite routes. This
|
||||
needs a real server and is not automated.
|
||||
- docs/api.md matches the catalogue (hand check).
|
||||
@@ -0,0 +1,172 @@
|
||||
Feature: Language switcher conforms to the official design
|
||||
|
||||
Background:
|
||||
Given the design in docs/design is the visual spec of record for LanguageSwitcher and UserMenu
|
||||
And the interface supports exactly two languages, English and Français
|
||||
And each language is always written in its own name, whatever the interface language
|
||||
And the language rules of features/spa_internationalization.feature still apply
|
||||
And the language control no longer uses a form select anywhere
|
||||
And no language preference is sent to the server
|
||||
|
||||
Scenario Outline: Account menu lists Profile, Theme, Language and Log out in design order
|
||||
Given a signed-in user opens the account menu in the <surface>
|
||||
Then the entries appear in this order
|
||||
| Profile |
|
||||
| separator |
|
||||
| "Theme" section label |
|
||||
| System, Light, Dark |
|
||||
| separator |
|
||||
| "Language" section label |
|
||||
| English, Français |
|
||||
| separator |
|
||||
| Log out |
|
||||
And the "Theme" and "Language" labels are 11 px, weight 500, uppercase, letter-spacing 0.04em and --ui-text-muted
|
||||
And the label padding is <label_padding>
|
||||
And the menu is <size>
|
||||
And every item row is <row_height> high
|
||||
|
||||
Examples:
|
||||
| surface | label_padding | size | row_height |
|
||||
| desktop UserMenu popover | 6px 8px 2px | a 224 px popover above the chip | 32 px |
|
||||
| mobile AccountMenuSheet | 8px 16px 2px | a bottom sheet with grab handle | 48 px |
|
||||
|
||||
Scenario Outline: Language rows are a radio group naming each language in its own name
|
||||
Given the interface language is <locale>
|
||||
When the account menu is open in the <surface>
|
||||
Then the "Language" label names a group of two menuitemradio rows
|
||||
And the rows read "English" with lang "en" and "Français" with lang "fr"
|
||||
And the row for <locale_name> has aria-checked "true" and a check icon at the right edge
|
||||
And the other row has aria-checked "false" and no check icon
|
||||
And no Nuxt UI select, combobox or languages icon row is present in the menu
|
||||
|
||||
Examples:
|
||||
| surface | locale | locale_name |
|
||||
| desktop UserMenu popover | en | English |
|
||||
| desktop UserMenu popover | fr | Français |
|
||||
| mobile AccountMenuSheet | en | English |
|
||||
| mobile AccountMenuSheet | fr | Français |
|
||||
|
||||
Scenario Outline: Theme rows are radio items that keep the menu open
|
||||
Given the theme preference is <preference>
|
||||
When the account menu is open in the <surface>
|
||||
Then System, Light and Dark are menuitemradio rows in a group named "Theme"
|
||||
And only the <preference> row has aria-checked "true" and a check icon
|
||||
When the user chooses another theme row
|
||||
Then the theme applies at once and the menu stays open
|
||||
|
||||
Examples:
|
||||
| surface | preference |
|
||||
| desktop UserMenu popover | light |
|
||||
| mobile AccountMenuSheet | dark |
|
||||
|
||||
Scenario Outline: Choosing a language in the account menu applies it at once and keeps the menu open
|
||||
Given the interface language is en and the user is on /profile with an unsaved display name "Alice B."
|
||||
And the account menu is open in the <surface>
|
||||
When the user chooses "Français"
|
||||
Then all interface text, including the menu labels "Thème" and "Langue", is French
|
||||
And the document lang is "fr" and localStorage "renewcms-language" is "fr"
|
||||
And the Français row is checked and the menu stays open
|
||||
And the route, session, theme and unsaved display name are unchanged
|
||||
And no reload, navigation or /v1 request occurs
|
||||
When the user chooses "English"
|
||||
Then the interface is English, the document lang is "en" and the menu stays open
|
||||
|
||||
Examples:
|
||||
| surface |
|
||||
| desktop UserMenu popover |
|
||||
| mobile AccountMenuSheet |
|
||||
|
||||
Scenario Outline: Account menu keyboard and dismissal
|
||||
Given the account menu is open in the <surface>
|
||||
When the user moves with ArrowDown and ArrowUp
|
||||
Then focus visits Profile, the theme rows, the language rows and Log out in visual order and wraps at the ends
|
||||
When the user presses Enter or Space on a language row
|
||||
Then that language is applied and the menu stays open
|
||||
When the user presses Escape or clicks outside
|
||||
Then the menu closes without changing the language
|
||||
|
||||
Examples:
|
||||
| surface |
|
||||
| desktop UserMenu popover |
|
||||
| mobile AccountMenuSheet |
|
||||
|
||||
Scenario Outline: Auth footer shows the language chip beside the theme chip
|
||||
Given the user is signed out on <route>
|
||||
And the interface language is en
|
||||
Then the footer outside the card contains the language chip and the System theme chip aligned right with an 8 px gap
|
||||
And any existing footer slot content stays to the left of the chips
|
||||
And the chip shows the lucide languages icon at 14 px followed by "English"
|
||||
And the chip has a 1 px --ui-border-accented border, --ui-text-toned text, aria-haspopup "menu", aria-expanded "false" and aria-label "Language: English"
|
||||
And no language select is rendered in the card or the footer
|
||||
|
||||
Examples:
|
||||
| route |
|
||||
| /login |
|
||||
| /register |
|
||||
| /register/pending |
|
||||
| /register/validate |
|
||||
| /register/reset/request |
|
||||
| /register/reset/validate |
|
||||
| /invite/accept |
|
||||
|
||||
Scenario Outline: Auth footer is always rendered, on mobile too
|
||||
Given the viewport is <viewport>
|
||||
When an auth screen with no footer slot content renders
|
||||
Then the footer with the language chip and the theme chip is visible
|
||||
And the chip is <chip_height> high
|
||||
|
||||
Examples:
|
||||
| viewport | chip_height |
|
||||
| 1440 x 900 | 28 px |
|
||||
| 390 x 844 | 44 px |
|
||||
|
||||
Scenario: Chip reflects the current language
|
||||
Given the stored language is fr
|
||||
When /login renders
|
||||
Then the chip reads "Français" and its aria-label is "Langue : Français"
|
||||
|
||||
Scenario Outline: Auth language popover
|
||||
Given the user is signed out on /login in <locale_name>
|
||||
When the user activates the language chip
|
||||
Then the chip has aria-expanded "true" and --ui-bg-elevated
|
||||
And a popover with role "menu" named "Language" opens above the chip, right-aligned and 36 px above its bottom edge, 168 px wide, --ui-bg, 1 px --ui-border, --rc-shadow-pop and 4 px padding
|
||||
And it holds menuitemradio rows "English" (lang "en") and "Français" (lang "fr") that are 32 px high on desktop and 44 px on mobile
|
||||
And the current language row has aria-checked "true" and a 16 px check icon at the right edge
|
||||
|
||||
Examples:
|
||||
| locale_name |
|
||||
| English |
|
||||
| Français |
|
||||
|
||||
Scenario: Choosing a language in the auth popover closes it
|
||||
Given the auth language popover is open on /login with English current
|
||||
When the user chooses "Français"
|
||||
Then the whole screen is French at once, including the card, the footer and the document title
|
||||
And the document lang is "fr" and localStorage "renewcms-language" is "fr"
|
||||
And the popover closes and focus returns to the language chip
|
||||
And the chip reads "Français"
|
||||
And the form values already typed, the route and the theme are unchanged
|
||||
And no /v1 request occurs
|
||||
|
||||
Scenario: Dismiss the auth popover without changing language
|
||||
Given the auth language popover is open
|
||||
When the user presses Escape or clicks outside it
|
||||
Then it closes, aria-expanded is "false" and the language is unchanged
|
||||
And focus returns to the chip on Escape
|
||||
|
||||
Scenario: Auth popover keyboard
|
||||
Given the language chip has focus
|
||||
When the user presses Enter, Space or ArrowDown
|
||||
Then the popover opens with focus on the current language row
|
||||
And ArrowUp and ArrowDown move between the two rows and Enter or Space chooses one
|
||||
|
||||
Scenario: Language persists across public and signed-in screens
|
||||
Given the user chose Français on /login
|
||||
When they sign in, open the account menu and log out
|
||||
Then Français is checked in the account menu and the /login chip reads "Français" again
|
||||
And a storage failure still lets the choice apply for the current session, as in spa_internationalization
|
||||
|
||||
Scenario: Catalog parity for the new strings
|
||||
Then the en and fr catalogs contain "Theme" and "Language: {0}"
|
||||
And "Language: {0}" keeps its {0} parameter in French
|
||||
And the strings "English" and "Français" are not translated
|
||||
@@ -0,0 +1,35 @@
|
||||
# Language switcher conformance QA
|
||||
|
||||
Accepted by the user on 2026-10-04 together with the slice specification. Decisions folded in: spa_internationalization picker scenarios are amended; theme and language rows are menuitemradio and the account menu and sheet stay open after a choice; the auth popover is specified from docs/design/components.md because the boards draw only the chip.
|
||||
|
||||
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
||||
|
||||
Mock `/v1` per case and assert that a language change makes no `/v1` request. Reset the stored `renewcms-language` between tests. Do not freeze the system date.
|
||||
|
||||
1. UserMenu (desktop) and AccountMenuSheet (mobile): open the menu and assert the entry order Profile, separator, "Theme" label, System/Light/Dark, separator, "Language" label, English/Français, separator, Log out. Assert the label classes. LanguagePicker and any combobox must be absent.
|
||||
2. Roles and ARIA: theme rows and language rows are menuitemradio with aria-checked on the current one and a check icon. Language rows carry lang "en"/"fr" and native names. With locale fr the names stay "English"/"Français" while "Theme"/"Language" become "Thème"/"Langue".
|
||||
3. Account menu selection: choosing Français in each surface switches the visible copy, sets document lang and storage, keeps the menu open, and leaves route, theme and an unsaved display-name draft on /profile unchanged. Choosing English restores it. Choosing a theme keeps the mobile sheet open.
|
||||
4. Account menu keyboard: arrow order and wrap across all entries, Enter/Space applies and keeps open, Escape and outside click close with no language change.
|
||||
5. AuthShell: the footer is rendered with the language chip next to UColorModeSelect when belowSm is true and false, with no footer slot content, and slot content stays to the left. Assert aria-haspopup, aria-expanded, aria-label "Language: English" / "Langue : Français", the icon, the native name and the absence of a select.
|
||||
6. Auth popover: opens via click, Enter, Space and ArrowDown; role menu named "Language", two menuitemradio rows with lang and checked state; selection applies the language, closes it and returns focus to the chip; Escape and outside click dismiss with no change. Typed form values on /login survive the switch.
|
||||
7. Each auth screen (login, register, pending, verify, forgot-password, reset-password, accept-invite) mounts with the chip present.
|
||||
8. Persistence: stored fr gives chip "Français"; the choice survives log out and re-render of /login; a localStorage write failure still switches for the session.
|
||||
9. Catalog parity: en/fr keys include "Theme" and "Language: {0}" with matching parameters.
|
||||
10. Update web/src/i18n/spa.spec.ts, web/src/i18n/i18n.spec.ts and any AuthShell, UserMenu or AccountMenuSheet spec asserting menuitemcheckbox or the old picker. Remove LanguagePicker and its tests if the component is removed.
|
||||
11. Run task test:web and the type check; inspect the diff for introduced comments.
|
||||
|
||||
## Visual (`task visual:check -- <screen>`, hard gate at 10 %)
|
||||
|
||||
Desktop and mobile, light and dark, reusing the boards' sample data.
|
||||
|
||||
- profile, state "Account menu": board `deskMenu` and `mobMenu` with the Theme and Language labels, Light and English checked.
|
||||
- Every auth screen and state (log-in, register, pending, verify, forgot-password, reset-password, accept-invite): all captures change because of the language chip (`hasFooter: true`), including mobile where the footer is new. Clock-sensitive states stay `skip: 'clock-sensitive'`.
|
||||
- The boards draw no open auth language popover, so it has no visual gate. It is covered by the automated and manual checks.
|
||||
|
||||
## Manual (screenshots cannot cover)
|
||||
|
||||
- Keyboard focus order and visible focus ring in the account menu, the chip and the popover; focus return to the chip.
|
||||
- Hover, press and motion on the rows and the chip.
|
||||
- Popover placement above the chip and containment at 390 px width, including the 36 px offset next to the 44 px mobile chip. Touch targets at 44 px on mobile.
|
||||
- French readability of "Thème", "Langue" and "Langue : Français" in the labels, chip and popover.
|
||||
- Language retained after reload and logout.
|
||||
@@ -0,0 +1,75 @@
|
||||
Feature: English and French throughout the SPA
|
||||
|
||||
Background:
|
||||
Given all existing SPA interface text supports English and French
|
||||
And English preserves existing copy and French provides equivalent meaning
|
||||
And user content, API data and transactional emails remain unchanged
|
||||
And the language control follows features/language_switcher_conformance.feature
|
||||
|
||||
Scenario Outline: Resolve the language before rendering
|
||||
Given the browser-local stored language is <stored>
|
||||
When the SPA starts
|
||||
Then the interface language and document lang are <locale>
|
||||
And browser language does not override the choice
|
||||
|
||||
Examples:
|
||||
| stored | locale |
|
||||
| absent | en |
|
||||
| en | en |
|
||||
| fr | fr |
|
||||
| unsupported | en |
|
||||
| unreadable | en |
|
||||
|
||||
Scenario Outline: Offer the language choice in the account menu
|
||||
Given the user opens the <menu>
|
||||
Then a localized Language section offers English and Français as radio items
|
||||
And the selected language is visibly and accessibly identified
|
||||
|
||||
Examples:
|
||||
| menu |
|
||||
| desktop UserMenu |
|
||||
| mobile AccountMenuSheet |
|
||||
|
||||
Scenario: Switch language without losing work
|
||||
Given the user is editing an unsaved display name on /profile
|
||||
When they select Français
|
||||
Then all SPA interface text immediately uses French
|
||||
And the document lang is fr
|
||||
And the route, session, theme and unsaved work remain unchanged
|
||||
And no reload, navigation or API request is caused by switching
|
||||
When they select English
|
||||
Then the interface immediately restores English with the same preserved state
|
||||
|
||||
Scenario: Remember language on this browser
|
||||
Given the user selected Français
|
||||
When they navigate, reload, log out or return on this browser
|
||||
Then French remains selected including on public authentication screens
|
||||
And no language preference is sent to the server
|
||||
|
||||
Scenario: Storage failure does not prevent switching
|
||||
Given preference storage cannot be written
|
||||
When the user selects Français
|
||||
Then French is used for the current session without an error
|
||||
And a fresh load without a readable preference defaults to English
|
||||
|
||||
Scenario: Translate the entire interface
|
||||
Given French is selected
|
||||
When an existing SPA screen or shared component renders
|
||||
Then navigation, forms, validation, notifications, dialogs and accessibility labels use French
|
||||
And counts, human-readable dates and numbers use the selected locale
|
||||
And Nuxt UI controls use the selected locale
|
||||
And English and French catalogs have matching keys and interpolation parameters
|
||||
And an unavailable French message falls back to English
|
||||
And user content, account details, filenames, URLs, API data and emails remain unchanged
|
||||
|
||||
Scenario Outline: Operate the language choice accessibly
|
||||
Given the <menu> is open
|
||||
When the user navigates the language items with the keyboard and confirms a choice
|
||||
Then the language changes and the menu stays open
|
||||
When they press Escape or click outside
|
||||
Then the menu closes without changing language
|
||||
|
||||
Examples:
|
||||
| menu |
|
||||
| desktop UserMenu |
|
||||
| mobile AccountMenuSheet |
|
||||
@@ -0,0 +1,19 @@
|
||||
# SPA internationalization QA
|
||||
|
||||
Accepted by the user on 2026-10-03 together with the slice specification.
|
||||
|
||||
## Automated
|
||||
|
||||
1. Verify absent, English, French, unsupported and unreadable stored preferences; English defaults independently of browser language and document lang follows selection.
|
||||
2. Verify desktop UserMenu and mobile AccountMenuSheet offer a localized Language section with English and Français radio items, selected-state semantics, selection with the menu staying open, and dismissal. Preserve profile, theme and logout behavior. Details live in features/language_switcher_conformance.qa.md.
|
||||
3. Switch both ways while editing an unsaved profile display name. Verify translated UI and unchanged draft, route, session and theme without additional API requests.
|
||||
4. Verify browser-local persistence across reload initialization, navigation and logout/public authentication. Verify storage write failure allows switching for the current session.
|
||||
5. Preserve existing English tests and add French checks for login, validation, profile save failure, integration copy feedback, not-found, representative dialogs and notifications.
|
||||
6. Audit every existing view, shared component, composable and library producing interface text, including editor, media, users, invitations, settings and updates. Verify Nuxt UI controls use the active locale.
|
||||
7. Assert catalog key/interpolation parity, nonempty translations, pluralization, English fallback and locale-sensitive formatting. Use fixed input dates without freezing system time. Verify displayed alerts and dialogs react to language changes.
|
||||
8. Verify user content, account details, filenames, URLs, API fields, integration protocol examples, server release notes and transactional emails remain unchanged.
|
||||
9. Run task test:web, frontend type checks, applicable lint and final build checks. Inspect introduced comments and ensure application changes are SPA-only.
|
||||
|
||||
## Visual and manual
|
||||
|
||||
The language control now has an official design. Its visual and manual checks live in features/language_switcher_conformance.qa.md. For the rest of this slice, confirm French text readability and language retention after reload and logout. Do not freeze dates or investigate clock-sensitive states.
|
||||
@@ -0,0 +1,334 @@
|
||||
Feature: Updates part 2: the Update button (download, verify, stage)
|
||||
|
||||
As the owner of a RenewCMS site
|
||||
I want one button that downloads the new release, proves it is genuine, backs up the database and stages it
|
||||
So that the later Restart (slice 3) installs a file that was already checked, while the site stays online
|
||||
|
||||
Background:
|
||||
Given slices 1 to 3 of Updates ship in one release
|
||||
And this slice changes nothing that is running: it never replaces the running binary and never restarts the site
|
||||
And the domain package internal/domain/update (stdlib only) gains these interfaces, each faked in tests:
|
||||
AssetFetcher (downloads one asset to a path, reporting bytes done and total),
|
||||
SignatureVerifier (ed25519 check of checksums.txt against checksums.txt.sig with the embedded release.pub),
|
||||
StagedBinaryRunner (runs <path> --version and returns its output),
|
||||
DatabaseBackup (consistent copy of the SQLite file with VACUUM INTO, prune to the last 3),
|
||||
HelperDetector (reports whether the slice 3 helper is installed),
|
||||
JobStore (persists the update job record)
|
||||
And update.Release gains Assets (name, download URL, size) read by the Gitea adapter, and the stored CheckResult keeps
|
||||
them, so POST /v1/system/update/download never contacts the feed
|
||||
And the use cases depend only on domain interfaces; handlers in api/handlers/update receive them through NewHandler;
|
||||
only api/dependecyInjection.go builds the adapters
|
||||
And the job runs in one background goroutine owned by the use case; the HTTP handler returns as soon as it is started
|
||||
And POST /v1/system/update/download is mounted in NewSystemRouter behind jwtauth.Verifier, jwtauth.Authenticator,
|
||||
RequireCurrentToken, RequireVerifiedUser, RequireOwner and its own limiter of 5 starts per minute per user_id
|
||||
(constants, separate from the check limiter and the auth limiter) answering 429 with an integer Retry-After
|
||||
And the checks on POST run in this order: no cookie or stale token (401), unverified (403), not owner (403),
|
||||
limiter (429), can_apply false (409), a job running or already ready (409), available false (400),
|
||||
pre-flight refusal (422), then 202
|
||||
And errors are plain text from http.Error
|
||||
And the data directory is the directory that holds DB_FILE; no new env var is added
|
||||
And the job record is update-job.json in the data directory, shared by all owners and surviving a restart
|
||||
And a job record found as "downloading" or "verifying" at startup (no goroutine owns it) reads as failed with
|
||||
error "download"; a record "ready" whose staged binary is gone reads as idle
|
||||
And the staged files live in <data dir>/updates/<tag>/: the binary, checksums.txt and checksums.txt.sig
|
||||
And the asset to download is named renewcms_<tag>_<runtime.GOOS>_<runtime.GOARCH>, plus ".exe" on windows
|
||||
And the job runs these steps in order: download checksums.txt, checksums.txt.sig and the binary; verify the
|
||||
ed25519 signature of checksums.txt; verify the SHA-256 of the binary against its checksums.txt line; run the
|
||||
staged binary with --version and require the output to equal the tag; back up the database; mark "ready"
|
||||
And state is "downloading" during the downloads and "verifying" from the signature check until "ready"
|
||||
(the version run and the backup happen in "verifying")
|
||||
And the download policy, enforced in the production adapter: the URL must be https, its host (with port) must equal
|
||||
the host of UPDATE_FEED_URL, and every redirect must satisfy the same rule; there is a size cap per file
|
||||
(binary 200 MiB, checksums.txt 64 KiB, checksums.txt.sig 1 KiB) and an overall timeout of 10 minutes (named constants)
|
||||
And in tests the policy is relaxed only through the adapter constructor, which takes the allowed host, an
|
||||
"allow insecure scheme" option, a smaller cap and a shorter timeout; there is no env var or build flag that relaxes it
|
||||
And GET /v1/system/update keeps its 12 keys; state is one of idle, downloading, verifying, ready, failed;
|
||||
progress is {percent, downloaded_bytes, total_bytes} while downloading and null otherwise;
|
||||
error is null, "download" or "verification" (a kind only, never technical text); started_at is the job start
|
||||
And can_apply is true only for the owner when HelperDetector reports the helper installed; it is false for admins
|
||||
And the real HelperDetector reads <data dir>/update-helper.json (the status file the slice 3 helper writes); nothing
|
||||
writes it in this slice, so can_apply is false on real builds until slice 3
|
||||
And disk errors and database backup failures end the job as failed with error "download"
|
||||
And on any failure the staged files are deleted, the technical reason is logged server side, and no response carries it
|
||||
And a failed record stays until the next job starts; ready stays until slice 3 consumes it
|
||||
And the SPA shows the newer release without its leading "v" ("Version 2.3.0-beta") and the running version exactly as reported
|
||||
And the Restart button in "Ready to install" is rendered but disabled in this slice: the board frame draws it as the
|
||||
primary action, it has no handler, and slice 3 enables it; plain Restart (no update waiting) stays not rendered until slice 3
|
||||
|
||||
Scenario: Start the update, happy path
|
||||
Given the owner, can_apply true, a stored result with latest "v2.3.0-beta" (running "v2.2.0-beta", available true)
|
||||
and assets for the host platform, all served by the fake fetcher and signed with a throwaway key
|
||||
When the owner sends POST /v1/system/update/download
|
||||
Then the status is 202 and the body is the status JSON with state "downloading" and started_at set
|
||||
And GET /v1/system/update then reports downloading with progress.total_bytes equal to the asset size
|
||||
And when the job finishes GET reports state "ready", error null, progress null, latest "v2.3.0-beta"
|
||||
And the staged binary, checksums.txt and checksums.txt.sig are in <data dir>/updates/v2.3.0-beta/
|
||||
And a database backup exists in <data dir>/backups/ before state became "ready"
|
||||
And the running binary and the database are unchanged
|
||||
|
||||
Scenario Outline: The asset name follows the platform
|
||||
Given the runtime is <os>/<arch> and the release lists all six binaries
|
||||
When the update starts
|
||||
Then the fetcher is asked for "<asset>", "checksums.txt" and "checksums.txt.sig" only
|
||||
|
||||
Examples:
|
||||
| os | arch | asset |
|
||||
| linux | amd64 | renewcms_v2.3.0-beta_linux_amd64 |
|
||||
| linux | arm64 | renewcms_v2.3.0-beta_linux_arm64 |
|
||||
| darwin | arm64 | renewcms_v2.3.0-beta_darwin_arm64 |
|
||||
| windows | amd64 | renewcms_v2.3.0-beta_windows_amd64.exe |
|
||||
|
||||
Scenario: Progress is reported in bytes
|
||||
Given the fake fetcher has delivered 11 of 26 MiB
|
||||
When any verified user sends GET /v1/system/update
|
||||
Then state is "downloading" and progress is {percent: 42, downloaded_bytes: 11534336, total_bytes: 27262976}
|
||||
And percent is the floor of done * 100 / total
|
||||
|
||||
Scenario: Every owner sees the same job
|
||||
Given owner A started the job
|
||||
When owner B and an admin send GET /v1/system/update
|
||||
Then both read state "downloading" with the same progress and started_at
|
||||
And the owner's can_apply is true and the admin's can_apply is false
|
||||
|
||||
Scenario: The job record survives a restart
|
||||
Given the job is "ready" for "v2.3.0-beta" with its staged binary present
|
||||
When a new status use case is built over the same data directory
|
||||
Then GET reports state "ready"
|
||||
And a record "downloading" at startup reads as state "failed", error "download"
|
||||
And a record "ready" with the staged binary deleted reads as "idle"
|
||||
And a missing or corrupt job file reads as "idle" and is not fatal
|
||||
|
||||
Scenario: Only the owner
|
||||
When an admin sends POST /v1/system/update/download
|
||||
Then the status is 403 and the body is apperr.OwnerRequiredErrorMessage
|
||||
And no job starts and the fetcher is not called
|
||||
|
||||
Scenario Outline: POST is guarded like the other system routes
|
||||
When <caller> sends POST /v1/system/update/download
|
||||
Then the status is <status>
|
||||
And no job starts
|
||||
|
||||
Examples:
|
||||
| caller | status |
|
||||
| no jwt cookie | 401 |
|
||||
| a stale token version | 401 |
|
||||
| an unverified owner | 403 |
|
||||
|
||||
Scenario: Nothing to update
|
||||
Given a stored result with available false, or no stored result
|
||||
When the owner sends POST /v1/system/update/download
|
||||
Then the status is 400 and no job starts and the fetcher is not called
|
||||
|
||||
Scenario: The server is not prepared
|
||||
Given HelperDetector reports no helper
|
||||
When the owner sends POST /v1/system/update/download
|
||||
Then the status is 409 and no job starts
|
||||
And GET reports can_apply false
|
||||
And this holds even when available is false (409 before 400)
|
||||
|
||||
Scenario Outline: A second start while a job exists
|
||||
Given the job state is <state>
|
||||
When the owner sends POST /v1/system/update/download
|
||||
Then the status is 409 and the existing job is untouched
|
||||
|
||||
Examples:
|
||||
| state |
|
||||
| downloading |
|
||||
| verifying |
|
||||
| ready |
|
||||
|
||||
Scenario: Two starts at once run one job
|
||||
When two owners send POST /v1/system/update/download concurrently
|
||||
Then exactly one answers 202 and the other 409
|
||||
And the fetcher downloads each asset once
|
||||
|
||||
Scenario: Try again after a failure
|
||||
Given the job state is "failed"
|
||||
When the owner sends POST /v1/system/update/download
|
||||
Then the status is 202, error returns to null, started_at is new and the old staged files are replaced
|
||||
|
||||
Scenario: Start is rate limited per user
|
||||
When the owner sends 6 starts within one minute
|
||||
Then the first 5 are answered by the checks above and the 6th is 429 with apperr.TooManyRequestsErrorMessage
|
||||
and an integer Retry-After of at least 1
|
||||
And a different owner is not limited, and the check limiter and auth limiter counters are untouched
|
||||
|
||||
Scenario Outline: 422 is only a pre-flight refusal
|
||||
Given a stored result where <condition>
|
||||
When the owner sends POST /v1/system/update/download
|
||||
Then the status is 422 and the body is plain text without technical detail
|
||||
And no job starts, the fetcher is not called and the technical reason is logged
|
||||
|
||||
Examples:
|
||||
| condition |
|
||||
| no asset is named for the host platform |
|
||||
| checksums.txt or checksums.txt.sig is missing from the assets |
|
||||
| an asset URL is http, not https |
|
||||
| an asset URL is on a host other than UPDATE_FEED_URL's host |
|
||||
|
||||
Scenario Outline: Verification failures end the job as failed, kind "verification"
|
||||
Given a started job and <fault>
|
||||
When the job reaches the check
|
||||
Then GET reports state "failed", error "verification", progress null
|
||||
And <data dir>/updates/<tag>/ is deleted
|
||||
And the technical reason is logged and appears in no response body
|
||||
|
||||
Examples:
|
||||
| fault |
|
||||
| the binary was changed after signing (SHA-256 mismatch) |
|
||||
| checksums.txt was changed after signing |
|
||||
| the signature is from a different key |
|
||||
| checksums.txt has no line for the asset |
|
||||
| the staged binary prints "v2.2.9-beta" for --version |
|
||||
| the staged binary cannot be run |
|
||||
|
||||
Scenario Outline: Download and disk failures end the job as failed, kind "download"
|
||||
Given a started job and <fault>
|
||||
Then GET reports state "failed", error "download"
|
||||
And <data dir>/updates/<tag>/ is deleted and the technical reason is logged, not returned
|
||||
|
||||
Examples:
|
||||
| fault |
|
||||
| the connection drops after half the bytes (truncated download) |
|
||||
| the bytes received differ from the size the release declares |
|
||||
| a file exceeds its size cap |
|
||||
| the download passes the overall timeout |
|
||||
| the feed host answers 404 or 500 for an asset |
|
||||
| the updates directory cannot be created or written (disk error) |
|
||||
| the disk fills during the write |
|
||||
| the database backup fails |
|
||||
|
||||
Scenario: The backup comes before ready, and the last 3 are kept
|
||||
Given the backups directory holds 3 earlier backups
|
||||
When a job completes
|
||||
Then a new consistent copy exists (opened read-only it holds the same article rows as the live file)
|
||||
And only the 3 newest backups remain, the oldest being deleted
|
||||
And no job is "ready" until the new backup exists
|
||||
And a failed backup leaves state "failed", error "download" and does not prune the earlier backups
|
||||
|
||||
Scenario: The production download policy
|
||||
Given the production adapter with UPDATE_FEED_URL "https://git.example"
|
||||
Then an http:// asset URL, an https URL on another host, and a redirect to another host or to http are refused
|
||||
And an https URL on git.example is accepted
|
||||
|
||||
Scenario: A server --version flag
|
||||
When the server binary is run with --version
|
||||
Then it prints the build version and exits 0
|
||||
And it does not read .env, open the database or start listening
|
||||
And with no -ldflags version it prints "dev"
|
||||
|
||||
Scenario: Settings, owner, Update available with the helper detected (route /settings)
|
||||
Given the owner and GET /v1/system/update resolves available true, can_apply true, state "idle", latest "v2.3.0-beta"
|
||||
Then the block shows icon circle-arrow-up (info), "Version 2.3.0-beta is available" /
|
||||
"You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart."
|
||||
and the meta "Last checked ..."
|
||||
And the notes button "What's new in 2.3.0-beta" is collapsed, and when open shows "Released 24 Sep 2026" and the list
|
||||
And the one button is "Update" (download, primary) and the hint is "Takes about 2 minutes. Your site stays online."
|
||||
And no server command, no "How to update" link, no Restart and no "Check for updates" is rendered
|
||||
|
||||
Scenario: Settings, owner, Downloading
|
||||
When the owner presses "Update" and POST /v1/system/update/download answers 202
|
||||
Then the block shows icon download (info), "Downloading version 2.3.0-beta…" /
|
||||
"You can leave this page. The download continues and your site stays online."
|
||||
And a progressbar labelled "Downloading version 2.3.0-beta" has aria-valuenow equal to progress.percent
|
||||
and the text "42% · 11 of 26 MB"
|
||||
And the button reads "Updating…" (loader-circle, secondary) and is disabled
|
||||
And GET /v1/system/update is polled every second while state is downloading or verifying
|
||||
|
||||
Scenario: Settings, progress is announced at 25 percent steps only
|
||||
Given the polled percent goes 3, 9, 24, 25, 26, 49, 50, 74, 75, 99, 100
|
||||
Then the announcer text changes only at 25, 50, 75 and the step change, reading
|
||||
"Downloading version 2.3.0-beta, 25 percent" and so on
|
||||
And the visible text and aria-valuenow still update on every poll
|
||||
And the live region does not announce the per-tick text
|
||||
|
||||
Scenario: Settings, owner, Verifying
|
||||
Given the poll answers state "verifying"
|
||||
Then the block shows icon shield-check (info), "Checking the download…" /
|
||||
"Making sure the file is complete and safe to install. This takes a few seconds."
|
||||
And the progressbar is indeterminate (no aria-valuenow, a 35% wide moving bar) labelled "Checking the download"
|
||||
with the text "Almost there"
|
||||
And the button reads "Updating…" and is disabled
|
||||
And "Checking the download" is announced once, when the step changes
|
||||
|
||||
Scenario: Settings, owner, Ready to install
|
||||
Given the poll answers state "ready"
|
||||
Then polling stops
|
||||
And the block shows icon clock (warning tone) with a "Pending" tag after the title, "Version 2.3.0-beta is ready to install" /
|
||||
"The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds." /
|
||||
"Nothing has changed yet."
|
||||
And the notes button is shown collapsed
|
||||
And the Restart button (power, primary) is rendered with disabled set and 40% opacity, and activating it does nothing
|
||||
And the hint is "Not now? Leave this page. The update waits here, and the banner on Home reminds you."
|
||||
And no dialog, overlay or POST /v1/system/update/restart exists
|
||||
|
||||
Scenario: Settings, Download failed
|
||||
Given the poll answers state "failed" with error "download", or POST download answers 500 or never reaches the server
|
||||
Then focus moves to the "Updates" heading (id="updates-h")
|
||||
And the block shows icon circle-x (error), "The download didn't finish" /
|
||||
"The connection dropped before the file was complete. Nothing was changed and your site is running as before."
|
||||
And the one button is "Try again" (rotate-cw, primary), which sends POST /v1/system/update/download
|
||||
|
||||
Scenario: Settings, Verification failed
|
||||
Given the poll answers state "failed" with error "verification", or POST download answers 422
|
||||
Then the block shows icon triangle-alert (warning), "We didn't use this update" /
|
||||
"The file didn't pass our safety check, so it was not installed. Nothing was changed. Try downloading it again. If this keeps happening, contact RenewCMS support."
|
||||
And the one button is "Try again" (rotate-cw, primary), as the board frame draws it
|
||||
And focus does not move to the heading
|
||||
And no technical detail is on screen
|
||||
|
||||
Scenario: Settings, 409 already running
|
||||
Given POST /v1/system/update/download answers 409 and the reload answers state "downloading" or "verifying"
|
||||
Then an info toast "An update is already running" / "Another owner started it. Progress shows here." shows
|
||||
And the card switches to that run's progress and polls
|
||||
When the reload instead answers can_apply false
|
||||
Then the card shows the "Not prepared" state and no toast
|
||||
When the reload instead answers state "ready"
|
||||
Then the card shows "Ready to install" and no toast
|
||||
|
||||
Scenario: Settings, 400 nothing to update
|
||||
Given POST /v1/system/update/download answers 400
|
||||
Then an info toast "Nothing to update" / "You already have the latest version." shows
|
||||
And the card reloads GET /v1/system/update
|
||||
|
||||
Scenario: Settings, 403 role changed on Update
|
||||
Given POST /v1/system/update/download answers 403
|
||||
Then an error toast "Only the owner can do this" / "Ask the owner of this site to update RenewCMS." shows
|
||||
And the card reloads and renders the admin view
|
||||
|
||||
Scenario: Settings, 429 on Update
|
||||
Given POST /v1/system/update/download answers 429 with Retry-After 42
|
||||
Then the block shows icon info "Too many tries" / "Wait a moment before trying again."
|
||||
And the button reads "Try again in 0:42" (clock, disabled) and counts down each second through useRetryAfter
|
||||
And at zero it is re-enabled as "Try again" and pressing it sends POST /v1/system/update/download again
|
||||
|
||||
Scenario: Settings, reload keeps progress
|
||||
Given a job is downloading and the owner leaves /settings
|
||||
Then polling stops and the job continues on the server
|
||||
When the owner opens /settings again, from this or another device
|
||||
Then GET /v1/system/update is read on open and the card shows the job's current state and progress
|
||||
And polling resumes while state is downloading or verifying
|
||||
|
||||
Scenario: Settings, a poll that fails keeps the card
|
||||
Given a poll answers 500 or never reaches the server while downloading
|
||||
Then the card keeps its last progress, no failure card shows, and polling continues each second
|
||||
|
||||
Scenario: Settings, admin view during a job
|
||||
Given the session role is "admin" and state is "downloading"
|
||||
Then the admin view of slice 1 shows ("Version 2.3.0-beta is available" / "You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site.")
|
||||
And no button, progressbar or poll is rendered
|
||||
|
||||
Scenario: Home banner, ready to install (owner)
|
||||
Given the owner is on /home and state is "ready"
|
||||
Then a region labelled "Update available" shows above the content in info tone (as the board frame draws it)
|
||||
with icon circle-check, title "Version 2.3.0-beta is ready to install",
|
||||
text "Restart from Settings to finish. The site is unavailable for about 10 seconds.",
|
||||
a "Go to Settings" button that navigates to /settings, and a Dismiss button
|
||||
And it shows although the "available" banner for this version was dismissed earlier
|
||||
When the owner dismisses it
|
||||
Then it hides for this visit only and shows again on the next visit, and nothing is written to localStorage
|
||||
And an admin sees no banner; with state "downloading" or "verifying" the "available" banner shows as before
|
||||
|
||||
Scenario: Pending states for slice 3
|
||||
Then these remain pending in the visual gate, never passing: Restart confirm, Restart request failed, Restarting to install,
|
||||
Restarting taking longer, Update done, Rolled back, Plain restart (confirm, restarting, done)
|
||||
@@ -0,0 +1,113 @@
|
||||
# QA: Updates part 2 (download, verify, stage)
|
||||
|
||||
## Automated Go (`task test`, package `test`, black-box, no live network, no real SMTP)
|
||||
|
||||
Files: `test/update_download_test.go` (domain, use case), `test/update_download_http_test.go` (HTTP),
|
||||
`test/update_assets_test.go` (production download adapter against a local server). Fakes with unique names:
|
||||
`fakeAssetFetcher` (serves bytes, can truncate, stall, fail, counts calls), `fakeHelperDetector`, `fakeJobStore`,
|
||||
`fakeStagedRunner` (returns a configured --version output or error), `fakeDatabaseBackup`; reuse `fakeReleaseFeed`,
|
||||
`fakeUpdateStore` and `mockUserRepo` from the slice 1 tests.
|
||||
|
||||
HTTP setup: `validator.InitValidator()`; `token := jwtauth.New("HS256", []byte("test-secret"), nil)`; a fresh `chi.NewRouter()` at
|
||||
`/v1/system` mirroring `NewSystemRouter` (Verifier, Authenticator, RequireCurrentToken, RequireVerifiedUser; the download
|
||||
route also RequireOwner and its limiter, 5 per minute); cookies as in `test/stale_token_invalidation_http_test.go`.
|
||||
Job state, staged files and backups go in `t.TempDir()`. Wait for the job with a poll loop on GET (deadline 5 s), never a bare
|
||||
`time.Sleep`. Use a throwaway ed25519 key generated in the test and sign `checksums.txt` with it; never read the committed
|
||||
`release.pub`.
|
||||
|
||||
Local asset server: `httptest.NewServer` (plain HTTP) and `httptest.NewTLSServer` for the policy cases. The production adapter is
|
||||
built through its constructor with the test's allowed host, allow-insecure true for the plain server, the TLS server's client for
|
||||
the TLS cases, a small size cap and a short timeout. Never relax the policy by env var or build flag.
|
||||
|
||||
1. Happy path: owner POST gives 202 with state "downloading"; poll GET until "ready"; files in `updates/<tag>/`, one backup in
|
||||
`backups/`; running binary unchanged; the fetcher was asked for exactly the three asset names.
|
||||
2. Asset naming table over GOOS/GOARCH (including the `.exe` case). Inject the platform into the use case; never assert on the
|
||||
test machine's own platform.
|
||||
3. Progress: a fetcher paused at 11 of 26 MiB gives `{percent:42, downloaded_bytes, total_bytes}` on GET; `progress` is null in
|
||||
verifying, ready and failed; `error` is null until a failure.
|
||||
4. Shared state: GET as owner A, owner B and admin agree; admin `can_apply` false, owner true with the fake detector on.
|
||||
5. Persistence: JSON job store round trip in a temp dir; "downloading" at startup reads failed/"download"; "ready" with the staged
|
||||
binary deleted reads idle; a missing or corrupt file reads idle without error. The real helper detector reads
|
||||
`<data dir>/update-helper.json`: absent file gives false, a present valid file gives true.
|
||||
6. Guards: admin 403 with `apperr.OwnerRequiredErrorMessage+"\n"`; no cookie 401; stale token 401; unverified 403; none start a job.
|
||||
7. Status codes: available false or nothing stored gives 400; detector off gives 409; state downloading, verifying, ready each give
|
||||
409; after "failed" a new POST gives 202 with a new started_at. Order check: detector off and available false gives 409.
|
||||
8. Concurrency: two simultaneous POSTs (goroutines) give one 202 and one 409; each asset fetched once (run with `-race`).
|
||||
9. Rate limit: owner A sends 6 POSTs within a minute; the 6th is 429 with `apperr.TooManyRequestsErrorMessage+"\n"` and an integer
|
||||
Retry-After >= 1; owner B is unaffected; the check limiter and a login limiter built in the test are untouched.
|
||||
10. 422 pre-flight: each of the four conditions in the feature gives 422, the body is plain text with no URL, host or file name from
|
||||
the fixture, no job record is created, fetcher count is 0, and the reason is captured from an injected logger.
|
||||
11. Verification failures, one subtest per row, each ending with GET `state` "failed", `error` "verification", `updates/<tag>/`
|
||||
removed, a body free of the fault text, and the fault text present in the injected logger: tampered binary, tampered
|
||||
checksums.txt, signature from another key, no checksum line for the asset, wrong `--version` output, runner error.
|
||||
12. Download failures, one subtest per row, each ending "failed", `error` "download", directory removed: truncated body, size
|
||||
mismatch with the release, over the size cap, timeout (server stalls; adapter timeout shortened), 404/500, unwritable updates
|
||||
directory (a file placed where the directory should be), disk full (a writer fake returning an error mid-write), backup failure
|
||||
(earlier backups not pruned).
|
||||
13. Backup: with the real SQLite backup adapter against a SQLite file created in `t.TempDir()` (pure-Go driver, `CGO_ENABLED=0`):
|
||||
the copy opens and holds the same rows, four jobs leave only the 3 newest files, and a job is not "ready" before the copy exists.
|
||||
14. Production policy: http URL, another host, redirect to another host and redirect to http are refused (no request reaches the
|
||||
second server); the TLS server on the allowed host is accepted.
|
||||
15. `--version`: build with `go build -tags nofrontend -ldflags "-X main.version=v9.9.9" ./cmd/server` into `t.TempDir()` and run
|
||||
it with `--version` and an empty environment: stdout `v9.9.9`, exit 0, no `data/` created; without ldflags it prints `dev`.
|
||||
16. Review items, not Go tests: `internal/domain/update` imports only the stdlib; use cases import no `net/http`, `os/exec`, `gorm`
|
||||
or adapter; the handler imports no adapter; no secret value is in the repo; the helper detector reads only its status file.
|
||||
|
||||
## Automated SPA (Vitest + Vue Test Utils, `task test:web`)
|
||||
|
||||
Mock `useApi.request` for `GET /v1/system/update`, `POST /v1/system/update/check` and `POST /v1/system/update/download`. Fake timers
|
||||
drive the 1 s poll and the countdown. No test freezes the system date and none asserts a relative date. Reuse the board's data:
|
||||
running `v2.2.0-beta`, latest `v2.3.0-beta`, 26 MB total, 11 MB done (42 %), released 24 Sep 2026.
|
||||
|
||||
One test per state:
|
||||
1. Update available, can_apply true: copy, notes collapsed, only "Update", hint; no command, no link, no Restart.
|
||||
2. Update available, notes open (`aria-expanded`, "Released 24 Sep 2026").
|
||||
3. Downloading: 202 then the card copy, progressbar label, `aria-valuenow` 42, "42% · 11 of 26 MB", "Updating…" disabled; GET called once per second.
|
||||
4. Announcements: percents 3, 24, 25, 26, 49, 50, 75, 100; the announcer text changes only at 25, 50, 75 and the step change;
|
||||
`aria-valuenow` changes on each tick.
|
||||
5. Verifying: indeterminate bar (no `aria-valuenow`), "Almost there", announced once.
|
||||
6. Ready: copy, meta, hint, Restart present with `disabled` and no request on click, notes button, polling stopped.
|
||||
7. Download failed (state failed/download; a 500; a `NetworkError`): copy, focus on `#updates-h`, "Try again" posts download again.
|
||||
8. Verification failed (state failed/verification; a 422): copy, "Try again", focus not moved, no technical text.
|
||||
9. 409: reload downloading gives the info toast and progress; reload ready gives no toast and the Ready card; reload can_apply false
|
||||
gives the Not prepared card.
|
||||
10. 400: info toast "Nothing to update" and one GET.
|
||||
11. 403: error toast and the admin view after reload.
|
||||
12. 429: "Too many tries", "Try again in 0:42" counting down through `useRetryAfter`, re-enabled as "Try again" and it re-posts
|
||||
download (not check).
|
||||
13. Reload: unmount stops the poll; mount reads GET and resumes the poll for a running state; no poll for idle, ready or failed.
|
||||
14. A failed poll keeps the last progress and keeps polling.
|
||||
15. Admin with state downloading: admin copy, no button, no progressbar, no poll.
|
||||
16. Home banner ready: info tone, copy, `role="region"` labelled "Update available", "Go to Settings" navigates, shows although the
|
||||
available banner was dismissed, Dismiss hides until remount and writes nothing to localStorage; admin sees none.
|
||||
17. Sidebar pill and mobile dot stay for ready, downloading and verifying (owner only, `available` true).
|
||||
|
||||
## Visual (`task visual:check -- settings` and `-- home`; desktop and mobile, light and dark; every capture within 10 %)
|
||||
|
||||
Add the setups to `web/visual/states.ts` with the board's sample data (v2.2.0-beta, v2.3.0-beta, 42 % / "11 of 26 MB"). Exact values
|
||||
from `docs/design/source/AppFrame.dc.html` and the "Settings" and "Home" groups of the Screens board; layout as drawn.
|
||||
|
||||
- [ ] Settings: Update available, Update available (notes open), Downloading (42 %), Verifying, Ready to install,
|
||||
Download failed, Verification failed. The frame draws an enabled Restart; the disabled one (40 % opacity) must still be
|
||||
within budget. If it is not, stop and report; do not widen the budget or add an exception without the user's approval.
|
||||
- [ ] Home: Update ready to install (owner), with the sidebar pill and the mobile dot as drawn.
|
||||
- [ ] Settings: Update already running (409): the frame shows the card in progress; set up with the mocked 409 then the
|
||||
downloading reload (the toast only if the frame draws it; check the markup).
|
||||
- [ ] `skip: 'clock-sensitive'`: any state whose meta line is relative ("Last checked today at 09:41"), as in slice 1.
|
||||
- [ ] Pending, never passing (slice 3): Restart confirm, Restart request failed, Restarting, Restarting taking longer,
|
||||
Update done, Rolled back, Plain restart (confirm, restarting, done).
|
||||
- [ ] Not covered by screenshots: keyboard and focus order, the focus ring on `#updates-h` after Download failed, the 25 %
|
||||
announcements (screen reader), hover and motion of the indeterminate bar.
|
||||
|
||||
## Manual verification
|
||||
|
||||
- `can_apply` stays false on real builds until slice 3 writes `<data dir>/update-helper.json`: use the fake in tests, or place the
|
||||
file by hand to see the Update button.
|
||||
- Against a real signed release on the real feed host (needs `release.pub` replaced and `task release` signing): press Update, watch
|
||||
progress, the Verifying step and the Ready card; check `<data dir>/updates/<tag>/` and one file in `<data dir>/backups/`.
|
||||
- The real staged binary on the target OS runs `--version` and prints the tag.
|
||||
- Flip one byte of a asset on a test mirror: the card shows "We didn't use this update" and the folder is gone.
|
||||
- Kill the server mid-download and restart it: the card shows "The download didn't finish".
|
||||
- Open the card in two browsers (two owners) and confirm the same progress; the second press shows the 409 toast.
|
||||
- Embedded SPA build (no `-tags nofrontend`) serves /settings and /home with the new states.
|
||||
- Confirm no secret or feed credential appears in logs, and that technical failure reasons are in the log only.
|
||||
@@ -0,0 +1,292 @@
|
||||
Feature: Updates part 1: signed releases, release feed and read-only update notification
|
||||
|
||||
As the owner of a RenewCMS site
|
||||
I want to see when a newer signed release exists, and have admins see the same status read-only
|
||||
So that I know when to update, while downloading and restarting arrive in later slices
|
||||
|
||||
Background:
|
||||
Given slices 1 to 3 of Updates ship in one release, so no released build shows the command
|
||||
"renewcms enable-browser-updates" before it exists (it is implemented in slice 3)
|
||||
And every release is published as a Gitea prerelease with the six binaries, checksums.txt and checksums.txt.sig
|
||||
And cmd/releasesign is a stdlib-only tool (crypto/ed25519, no new dependency) with the commands
|
||||
keygen <private-key-path> [--pub-out <path>], sign <file> [--key <path>] [--pub <path>],
|
||||
verify <file> [--pub <path>]
|
||||
And keygen writes the private key to the path given and refuses a path inside the repository work tree
|
||||
And sign and verify use the embedded public key unless --pub is given; tests always pass --pub with a throwaway key
|
||||
And sign refuses to sign when the private key does not match the public key, naming the mismatch
|
||||
And the public key is internal/infrastructure/update/release.pub, embedded with go:embed
|
||||
And until the user runs task release:keygen and commits the real public key, release.pub holds the placeholder:
|
||||
the base64 of 32 zero bytes (AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=); an all-zero key is recognised
|
||||
as the placeholder, and sign and verify refuse it with a clear message
|
||||
And the real private key is generated by the user outside the repo; the coder never generates or commits it
|
||||
And task release writes checksums.txt (SHA-256 of every binary) next to the binaries and signs it into
|
||||
checksums.txt.sig with the private key at the path in the env var RELEASE_SIGNING_KEY
|
||||
And task release fails clearly, before building anything, when RELEASE_SIGNING_KEY is unset, the file is missing,
|
||||
the embedded key is the placeholder, or the private key does not match the embedded public key
|
||||
And task release:keygen creates the one-time key pair and prints where to commit the public key
|
||||
And docs/release-notes.md gains the publish step (attach checksums.txt and checksums.txt.sig with the six binaries),
|
||||
docs/deployment.md and docs/configuration.md are updated, and nothing is published
|
||||
And the domain package internal/domain/update (stdlib only) holds Release, ReleaseNotes, version comparison,
|
||||
UpdateStatus, the ReleaseFeed interface, the StatusStore interface and the Err sentinels
|
||||
And the Gitea adapter lives under internal/infrastructure/update and implements update.ReleaseFeed with
|
||||
var _ update.ReleaseFeed = &X{}; it requests GET {UPDATE_FEED_URL}/api/v1/repos/fsylvain/RenewCMS/releases
|
||||
(the list, not "latest")
|
||||
And UPDATE_FEED_URL is in requiredEnvVars/envDefaults, .env.example and docs/configuration.md, defaulting to the repo base URL
|
||||
And a JSON file store implements update.StatusStore and keeps the last result and checked_at in update-status.json
|
||||
beside DB_FILE, shared by all owners and surviving a restart; no new env var is added
|
||||
And GetUpdateStatusUseCase and CheckForUpdateUseCase depend only on the domain interfaces; handlers in
|
||||
api/handlers/update receive them through NewHandler; api/dependecyInjection.go builds the adapters
|
||||
And NewSystemRouter is mounted at /v1/system behind jwtauth.Verifier, jwtauth.Authenticator, RequireCurrentToken
|
||||
and RequireVerifiedUser; POST /update/check also sits behind RequireOwner and a limiter of 5 checks per minute
|
||||
per user_id (constants, not env vars, separate from the auth limiter) that answers 429 with an integer Retry-After
|
||||
And GET /v1/system/update returns 200 with JSON of exactly these snake_case keys: current, latest, available,
|
||||
release_url, notes {version, released_at, items}, checked_at, can_apply, state, progress, error, started_at
|
||||
And release_url is the release's html_url, null when never checked; in slice 3 the "How to update" link is
|
||||
repointed at the "Browser updates" section of docs/deployment.md
|
||||
And in this slice can_apply is always false and state is always "idle"; never-checked values are latest "",
|
||||
available false, release_url null, notes null, checked_at null, progress null, error null, started_at null
|
||||
And versions compare numerically per segment, a final release beats a beta of the same number, and the
|
||||
running build "dev" never reports an update
|
||||
And release notes are the release body converted to a plain-text list of items
|
||||
And the API returns raw tags; the SPA shows the newer release without its leading "v" ("Version 2.3.0-beta")
|
||||
and the running version exactly as reported
|
||||
And the download and restart endpoints are not mounted; ReleaseFeed, StatusStore and UpdateStatus are shaped so
|
||||
slices 2 and 3 only add use cases
|
||||
And errors are plain text from http.Error
|
||||
|
||||
Scenario Outline: Version comparison
|
||||
Given the running version is "<current>" and the newest feed release is "<latest>"
|
||||
When the versions are compared
|
||||
Then available is <available>
|
||||
|
||||
Examples:
|
||||
| current | latest | available |
|
||||
| v2.2.0-beta | v2.3.0-beta | true |
|
||||
| v2.5.0-beta | v2.5.0 | true |
|
||||
| v2.5.0 | v2.5.0-beta | false |
|
||||
| v2.9.0 | v2.10.0 | true |
|
||||
| v2.5.0-beta | v2.5.0-beta | false |
|
||||
| v2.5.0 | v2.4.9 | false |
|
||||
| dev | v9.9.9 | false |
|
||||
|
||||
Scenario: The newest release is chosen from the list regardless of feed order
|
||||
Given the feed list holds v2.4.0-beta, v2.5.0-beta and v2.3.0-beta, all marked prerelease
|
||||
When the feed is read
|
||||
Then the latest release is v2.5.0-beta
|
||||
|
||||
Scenario: Drafts are ignored
|
||||
Given the feed list holds a draft release v9.0.0 and a published v2.5.0-beta
|
||||
When the feed is read
|
||||
Then the latest release is v2.5.0-beta
|
||||
|
||||
Scenario: Release notes become a plain-text list
|
||||
Given a release body "## What's new\n- **Media** library\n- Fixed [caching](http://x) bug\n\n* Faster start"
|
||||
When the notes are built
|
||||
Then notes.items is ["Media library","Fixed caching bug","Faster start"]
|
||||
And notes.released_at is the release's published date
|
||||
|
||||
Scenario: GET returns the idle shape, never applicable
|
||||
Given a verified user, running version "v2.2.0-beta", and a stored result with latest "v2.3.0-beta",
|
||||
html_url "https://git.example/fsylvain/RenewCMS/releases/tag/v2.3.0-beta" and checked_at 2026-09-30T09:41:00Z
|
||||
When the client sends GET /v1/system/update
|
||||
Then the status is 200 and the body has exactly the 12 keys
|
||||
And current is "v2.2.0-beta", latest is "v2.3.0-beta", available is true, can_apply is false, state is "idle"
|
||||
And release_url is the stored html_url and checked_at is "2026-09-30T09:41:00Z"
|
||||
And the feed is not contacted
|
||||
|
||||
Scenario: GET before any check
|
||||
Given no stored result
|
||||
When a verified user sends GET /v1/system/update
|
||||
Then the status is 200, available is false, latest is "", release_url, notes and checked_at are null, state is "idle"
|
||||
|
||||
Scenario Outline: GET is open to any verified user
|
||||
Given the caller is <role> with a valid jwt cookie
|
||||
When the client sends GET /v1/system/update
|
||||
Then the status is 200
|
||||
|
||||
Examples:
|
||||
| role |
|
||||
| owner |
|
||||
| admin |
|
||||
|
||||
Scenario: GET without a cookie
|
||||
When the client sends GET /v1/system/update with no jwt cookie
|
||||
Then the status is 401
|
||||
|
||||
Scenario: GET with a stale token
|
||||
Given the jwt cookie was minted with a token version older than the account's
|
||||
When the client sends GET /v1/system/update
|
||||
Then the status is 401 and the body is apperr.UnauthorizedErrorMessage
|
||||
|
||||
Scenario: GET by an unverified account
|
||||
When an unverified user with a valid cookie sends GET /v1/system/update
|
||||
Then the status is 403 and the body is apperr.VerificationRequiredErrorMessage
|
||||
|
||||
Scenario: The owner checks and the result is stored
|
||||
Given the fake feed returns v2.3.0-beta and the running version is "v2.2.0-beta"
|
||||
When the owner sends POST /v1/system/update/check
|
||||
Then the status is 200 with the same body shape as GET and available true
|
||||
And the fake store holds latest "v2.3.0-beta" and checked_at at the check time
|
||||
And a later GET returns the same result without contacting the feed
|
||||
|
||||
Scenario: A check with nothing newer
|
||||
Given the feed returns v2.2.0-beta and the running version is "v2.2.0-beta"
|
||||
When the owner sends POST /v1/system/update/check
|
||||
Then the status is 200 and available is false
|
||||
|
||||
Scenario: A dev build never reports an update
|
||||
Given the running version is "dev" and the feed returns v9.9.9
|
||||
When the owner sends POST /v1/system/update/check
|
||||
Then the status is 200 and available is false
|
||||
|
||||
Scenario: An admin cannot check
|
||||
Given the caller is an admin
|
||||
When the client sends POST /v1/system/update/check
|
||||
Then the status is 403 and the body is apperr.OwnerRequiredErrorMessage
|
||||
And the feed is not contacted
|
||||
|
||||
Scenario: Feed failure keeps the last result
|
||||
Given the store holds latest "v2.3.0-beta" checked at 2026-09-30T09:41:00Z and the feed returns an error
|
||||
When the owner sends POST /v1/system/update/check
|
||||
Then the status is 500
|
||||
And the store still holds the previous result and checked_at
|
||||
And no feed error detail appears in the body
|
||||
|
||||
Scenario: Check is rate limited per user
|
||||
When the owner sends 6 checks within one minute
|
||||
Then the first 5 answer 200 and the 6th answers 429 with apperr.TooManyRequestsErrorMessage and an integer Retry-After
|
||||
And the feed is contacted 5 times
|
||||
And a different owner is not limited by the first owner's checks
|
||||
And the auth limiter's counters are untouched
|
||||
|
||||
Scenario: The stored result survives a restart
|
||||
Given the JSON file store saved a result
|
||||
When a new store is opened on the same file
|
||||
Then the same latest, release_url and checked_at are returned
|
||||
And a missing or corrupt file reads as "no result" and is not fatal
|
||||
|
||||
Scenario: Release signing round trip with a throwaway key
|
||||
Given a key pair made by keygen at a path outside the repo
|
||||
When sign is run on checksums.txt with that key and verify with its public key
|
||||
Then verify exits 0
|
||||
And after one byte of checksums.txt changes, verify exits non-zero with a clear message
|
||||
And verify with a different public key exits non-zero
|
||||
|
||||
Scenario: keygen refuses a path inside the repository
|
||||
When keygen is given a path inside the work tree
|
||||
Then it exits non-zero, writes nothing and says why
|
||||
|
||||
Scenario: The placeholder public key is refused
|
||||
Given release.pub holds the placeholder (32 zero bytes, base64)
|
||||
When sign or verify uses the embedded key
|
||||
Then it exits non-zero with a message that the placeholder key has not been replaced
|
||||
|
||||
Scenario: sign refuses a private key that does not match the public key
|
||||
Given a private key whose public half differs from the public key in use
|
||||
When sign is run
|
||||
Then it exits non-zero naming the mismatch and writes no .sig file
|
||||
|
||||
Scenario Outline: task release refuses to sign
|
||||
Given <condition>
|
||||
When task release is run
|
||||
Then it fails before building any binary with a message naming <what>
|
||||
And nothing is published
|
||||
|
||||
Examples:
|
||||
| condition | what |
|
||||
| RELEASE_SIGNING_KEY is unset | RELEASE_SIGNING_KEY |
|
||||
| RELEASE_SIGNING_KEY points to a missing file | the missing path |
|
||||
| the embedded public key is the placeholder | the placeholder key |
|
||||
| the private key does not match the public key | the key mismatch |
|
||||
|
||||
Scenario: Settings, owner, Up to date (route /settings)
|
||||
Given the session role is "owner" and GET /v1/system/update resolves available false with checked_at set
|
||||
When the owner opens /settings
|
||||
Then the Updates card shows the status block with icon circle-check (success), title "You're up to date",
|
||||
text "You have the latest version of RenewCMS." and a meta line "Last checked ..." built from checked_at
|
||||
And the only button is "Check for updates" (refresh-cw, secondary)
|
||||
And no Restart button, hint or progress is rendered
|
||||
|
||||
Scenario: Settings, owner, Checking
|
||||
When the owner presses "Check for updates"
|
||||
Then the block shows icon loader-circle, "Checking for updates…" / "This usually takes a few seconds."
|
||||
in a polite live region
|
||||
And the button reads "Checking…" and is disabled
|
||||
And POST /v1/system/update/check is sent once
|
||||
|
||||
Scenario: Settings, owner, Check failed
|
||||
Given POST /v1/system/update/check answers 500 or never reaches the server
|
||||
Then the block shows icon wifi-off (warning), "Couldn't check for updates" /
|
||||
"RenewCMS couldn't reach the update server. Check your connection and try again. Your site isn't affected."
|
||||
and the meta "Last checked ..." from the kept result
|
||||
And the only button is "Try again" (rotate-cw, primary)
|
||||
|
||||
Scenario: Settings, owner, newer version, not prepared
|
||||
Given the session role is "owner" and GET /v1/system/update resolves available true, can_apply false, latest "v2.3.0-beta"
|
||||
When the owner opens /settings
|
||||
Then the block shows icon info, "Version 2.3.0-beta is available" /
|
||||
"This site can't update itself from the browser yet. Whoever manages your server can set it up once, or update RenewCMS for you."
|
||||
And "For whoever manages the server" shows the one-line code "renewcms enable-browser-updates" with a Copy button
|
||||
And the note "They run this once on the server. After that, Update and Restart appear here." shows
|
||||
And the link "How to update" (arrow-up-right) opens release_url in a new tab
|
||||
And no button other than Copy is rendered: not Update, not Restart, not even Check for updates
|
||||
|
||||
Scenario: Settings, owner, newer version, notes open
|
||||
Given the same state with notes.items and notes.released_at 2026-09-24
|
||||
When the owner activates "What's new in 2.3.0-beta" (a button with aria-expanded false then true)
|
||||
Then "Released 24 Sep 2026" and the plain-text list show, and activating it again collapses them
|
||||
And the notes are collapsed by default
|
||||
|
||||
Scenario: Settings, command copied
|
||||
When the owner presses Copy
|
||||
Then the button reads "Copied" with a check for 2 s, is announced, then reads "Copy" again
|
||||
|
||||
Scenario: Settings, admin view
|
||||
Given the session role is "admin"
|
||||
When GET /v1/system/update resolves available true with latest "v2.3.0-beta"
|
||||
Then the card shows "Version 2.3.0-beta is available" /
|
||||
"You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site." and no button
|
||||
When it resolves available false
|
||||
Then the card shows "You're up to date" / "Only the owner can update or restart the site." and no button
|
||||
|
||||
Scenario: Settings, Role changed (403)
|
||||
Given an owner is on /settings and POST /v1/system/update/check answers 403
|
||||
Then an error toast "Only the owner can do this" / "Ask the owner of this site to update RenewCMS." shows
|
||||
And the card reloads GET /v1/system/update and renders the admin view
|
||||
|
||||
Scenario: Settings, Too many requests (429)
|
||||
Given POST /v1/system/update/check answers 429 with Retry-After 42
|
||||
Then the block shows icon info "Too many tries" / "Wait a moment before trying again."
|
||||
And the button reads "Try again in 0:42", counts down each second and is re-enabled at zero
|
||||
|
||||
Scenario: A check runs on the first open after 24 hours, for the owner only
|
||||
Given the owner opens /settings and checked_at is null or older than 24 hours
|
||||
Then POST /v1/system/update/check is sent once automatically and the Checking state shows
|
||||
When checked_at is under 24 hours old
|
||||
Then no automatic check is sent
|
||||
And an admin never sends one
|
||||
|
||||
Scenario: Home banner for the owner, update available
|
||||
Given the owner is on /home and available is true with latest "v2.3.0-beta"
|
||||
Then a region labelled "Update available" shows above the content in info tone with icon circle-arrow-up,
|
||||
title "Version 2.3.0-beta is available",
|
||||
text "Update it from Settings. It takes about 2 minutes and the site stays online.",
|
||||
a "Go to Settings" button and a dismiss button
|
||||
When the owner dismisses it
|
||||
Then the banner is hidden and localStorage remembers the dismissed version
|
||||
And it shows again when latest changes to a newer version
|
||||
|
||||
Scenario: Settings sidebar pill and mobile dot
|
||||
Given the owner and available is true
|
||||
Then the Settings sidebar item shows an "Update" pill, and on mobile the menu icon shows a dot read as "Update available"
|
||||
And the pill stays after the banner is dismissed
|
||||
|
||||
Scenario: Admins and an up-to-date owner see no banner, pill or dot
|
||||
Then an admin, or an owner with available false, sees no banner, pill or dot
|
||||
|
||||
Scenario: Pending states of slices 2 and 3
|
||||
Then these states are listed as pending in the visual gate, never passing: Update available with its Update button
|
||||
(and its notes-open frame), Downloading, Verifying, Ready to install, Restart confirm, Restart request failed,
|
||||
Restarting, Restarting taking longer, Update done, Rolled back, Download failed, Verification failed,
|
||||
Plain restart confirm, restarting and done, Update already running (409), and the Home "ready to install" banner
|
||||
And the Update, Restart and progress elements are not rendered in any state of this slice
|
||||
@@ -0,0 +1,105 @@
|
||||
# QA: Updates part 1 (signed releases, release feed, notification)
|
||||
|
||||
## Automated Go (`task test`, package `test`, black-box)
|
||||
|
||||
Files: `test/update_test.go` (domain, use cases), `test/update_http_test.go` (HTTP), `test/update_feed_test.go`
|
||||
(Gitea adapter, JSON store), `test/releasesign_test.go` (signing tool). Fakes with unique names: `fakeReleaseFeed`
|
||||
(returns a list or an error, counts calls), `fakeUpdateStore`; reuse `mockUserRepo` from `test/user_test.go`.
|
||||
|
||||
HTTP setup: `validator.InitValidator()`; `token := jwtauth.New("HS256", []byte("test-secret"), nil)`; mount a fresh
|
||||
`chi.NewRouter()` at `/v1/system` mirroring `NewSystemRouter` (Verifier, Authenticator, RequireCurrentToken,
|
||||
RequireVerifiedUser; the check route also RequireOwner and the per-user limiter, 5 per minute); cookies via
|
||||
`token.Encode({"user_id","token_version"})` as in `test/stale_token_invalidation_http_test.go`. `httptest` only: no live
|
||||
server, no SQLite, no SMTP.
|
||||
|
||||
1. Version comparison, table-driven over the Examples in the feature (domain; `errors.Is` for sentinels).
|
||||
2. Feed adapter against `httptest.NewServer` serving a Gitea JSON list: path is
|
||||
`/api/v1/repos/fsylvain/RenewCMS/releases`; newest by numeric order regardless of order; drafts skipped; final beats
|
||||
beta; notes markdown converted to items; `html_url` carried; a 500 and invalid JSON return an error.
|
||||
3. `GET /v1/system/update` as owner and as admin: 200, exactly the 12 keys, `can_apply` false, `state` "idle", values
|
||||
from the stored result, `release_url` from the stored `html_url`; the fake feed call count is 0.
|
||||
4. GET before any check: `latest` "", `available` false, `release_url`, `notes`, `checked_at`, `progress`, `error`,
|
||||
`started_at` null.
|
||||
5. GET: no cookie 401; stale token 401 with `apperr.UnauthorizedErrorMessage`; unverified 403 with
|
||||
`apperr.VerificationRequiredErrorMessage`.
|
||||
6. `POST /v1/system/update/check` as owner: 200, store updated with latest, `release_url` and `checked_at`, feed called
|
||||
once, a later GET equals it. Nothing newer: `available` false. Running version "dev": `available` false.
|
||||
7. POST check as admin: 403, body `apperr.OwnerRequiredErrorMessage+"\n"`, feed not called.
|
||||
8. Feed error: 500, store unchanged (latest and `checked_at` as before), body contains no feed error text.
|
||||
9. Rate limit: owner A sends 6 checks: first 5 are 200, the 6th is 429 with `apperr.TooManyRequestsErrorMessage+"\n"`
|
||||
and an integer `Retry-After` of at least 1; feed called 5 times; owner B's first check still 200; a login-limiter
|
||||
instance built in the same test is unaffected.
|
||||
10. JSON file store in `t.TempDir()`: save, reopen, same values; missing file and corrupt file read as empty without error.
|
||||
11. Signing tool, run through `go run ./cmd/releasesign` (or its exported package) with a throwaway key pair generated
|
||||
in `t.TempDir()` at test time, always with `--pub`; never read the committed `release.pub` key except in case 13:
|
||||
keygen creates the key; sign then verify passes; one flipped byte fails verify; a different public key fails verify;
|
||||
keygen into a path inside the repo tree is refused and writes nothing; sign with a private key that does not match
|
||||
`--pub` fails, naming the mismatch, and writes no `.sig`.
|
||||
12. Placeholder: a `--pub` file holding base64 of 32 zero bytes makes sign and verify fail with the placeholder message.
|
||||
13. The committed `internal/infrastructure/update/release.pub` is checked only for shape: a valid base64 string that
|
||||
decodes to 32 bytes. Do not assert that it is or is not the placeholder, since the user replaces it later.
|
||||
14. Review items, not Go tests: `internal/domain/update` imports only the stdlib; use cases import no `net/http`,
|
||||
`gorm`, adapter or `config`; the handler imports no adapter; `UPDATE_FEED_URL` is in `requiredEnvVars`/`envDefaults`,
|
||||
`.env.example` and `docs/configuration.md`; no private key or secret value is in the repo.
|
||||
|
||||
## Automated SPA (Vitest + Vue Test Utils, `task test:web`)
|
||||
|
||||
Mock `useApi.request` for `GET /v1/system/update` and `POST /v1/system/update/check`. Fake timers for the countdown and
|
||||
the 2 s "Copied". No test freezes the system date and none asserts a relative date or "Last checked today". Reuse the
|
||||
board's sample data: running `v2.2.0-beta`, latest `v2.3.0-beta`, released 24 Sep 2026, items from the frame's script.
|
||||
|
||||
One test per state:
|
||||
1. Up to date (owner): "You're up to date", only "Check for updates" rendered.
|
||||
2. Checking: text, polite live region, "Checking…" disabled, one POST.
|
||||
3. Check failed (500, then `NetworkError`): copy, only "Try again", last result kept.
|
||||
4. Not prepared (available, `can_apply` false): copy, command line, note, "How to update" link with `href` equal to
|
||||
`release_url` and an external target; no button other than Copy.
|
||||
5. Notes open: collapsed by default, `aria-expanded` toggles, "Released 24 Sep 2026" and the plain-text list.
|
||||
6. Command copied: Copy writes the command to the clipboard mock, reads "Copied" for 2 s, then "Copy".
|
||||
7. Admin view: both texts, no button; no auto check.
|
||||
8. Role changed (403): toast "Only the owner can do this" / "Ask the owner of this site to update RenewCMS.", then a
|
||||
reload of the GET and the admin view.
|
||||
9. 429: "Too many tries", button "Try again in 0:42" counting down to enabled.
|
||||
10. Auto check: sent once when `checked_at` is null or older than 24 h, not when fresh, never for admin.
|
||||
11. Home banner: shown for the owner when available, copy and "Go to Settings" navigates to /settings, dismiss writes
|
||||
the version to localStorage and hides it, same version stays hidden after remount, a newer `latest` shows it again,
|
||||
absent for admin and when not available.
|
||||
12. Sidebar pill and mobile dot: owner and available only, pill remains after the banner is dismissed; absent for admin.
|
||||
13. No Update, Restart or progressbar element exists in any of the states above; the shown version drops the leading
|
||||
"v" ("Version 2.3.0-beta") while the Version card keeps `v2.2.0-beta`.
|
||||
|
||||
## Visual (`task visual:check -- settings` and `-- home`; desktop and mobile, light and dark; every capture within 10 %)
|
||||
|
||||
Add the setups to `web/visual/states.ts` using the board's own sample data. Exact values from
|
||||
`docs/design/source/AppFrame.dc.html` (Settings and Home blocks); layout as drawn, not from the prose.
|
||||
|
||||
- [ ] Settings: Checking (mock a never-resolving check after the click setup), Not prepared, Admin view (available),
|
||||
Too many requests (429, Retry-After 42).
|
||||
- [ ] Settings, `skip: 'clock-sensitive'` (the meta line is relative: "Last checked today at 09:41", "yesterday at 18:12"):
|
||||
Up to date, Check failed, Admin view (up to date).
|
||||
- [ ] Settings, Not prepared: command copied (the "Copied" state is time-bound; Vitest only), listed as not visual.
|
||||
- [ ] Home: Update available (owner), with the sidebar pill and the mobile dot as drawn.
|
||||
- [ ] Pending, never passing (slices 2 and 3): Update available with its Update button, Update available with notes
|
||||
open (its frame draws the Update button), Downloading, Verifying, Ready to install, Restart confirm, Restart
|
||||
request failed, Restarting, Restarting taking longer, Update done, Rolled back, Download failed, Verification
|
||||
failed, Plain restart (confirm, restarting, done), Update already running (409), Home "ready to install" banner.
|
||||
- [ ] Not covered by screenshots: keyboard and focus order, focus ring on the "Updates" heading (`id="updates-h"`),
|
||||
hover and motion, the Copy announcement, the dismiss button focus.
|
||||
|
||||
## Manual verification
|
||||
|
||||
- Replace the placeholder key: run `task release:keygen`, store the private key outside the repo, set
|
||||
`RELEASE_SIGNING_KEY` to its path, commit the printed public key as `internal/infrastructure/update/release.pub`, and
|
||||
rebuild. Never commit or paste the private key. Until this is done, `task release` must fail with the placeholder message.
|
||||
- Run `task release` with `RELEASE_SIGNING_KEY` unset, pointing to a missing file, and pointing to a key that does not
|
||||
match `release.pub`: each fails before any binary is built, with a message naming the cause. With the correct key,
|
||||
`checksums.txt` and `checksums.txt.sig` appear next to the six binaries and `cmd/releasesign verify` passes on them.
|
||||
- Against the real Gitea feed (default `UPDATE_FEED_URL`), run a dev API with a lower fake version and press "Check for
|
||||
updates" in the SPA: it reports the newest release; the "How to update" link opens that release's page.
|
||||
- Real release notes (the markdown body) render as a sensible plain-text list.
|
||||
- Restart the API and confirm the last result and `checked_at` survive, in `update-status.json` beside `DB_FILE`.
|
||||
- Embedded SPA build (no `-tags nofrontend`) serves /settings and /home with the card, banner and pill.
|
||||
- Confirm `docs/release-notes.md` (publish step: attach `checksums.txt` and `checksums.txt.sig` with the six binaries),
|
||||
`docs/deployment.md` and `docs/configuration.md` are updated, and that nothing was published.
|
||||
- Release gate: slices 1 to 3 ship together, so no released build shows `renewcms enable-browser-updates` before slice 3
|
||||
implements it.
|
||||
@@ -0,0 +1,508 @@
|
||||
Feature: Updates part 3: Restart, the privileged helper and rollback
|
||||
|
||||
As the owner of a RenewCMS site
|
||||
I want one Restart button that installs the staged release, or just restarts the site, and puts the old version back if the new one does not come up
|
||||
So that I can update from the browser while the app itself stays unprivileged and sandboxed
|
||||
|
||||
Background:
|
||||
Given slices 1 to 3 of Updates ship in one release
|
||||
And the app never gains privileges: the documented systemd unit keeps ProtectSystem=strict and only the data directory writable
|
||||
And only the helper runs as root; it is the same binary, started as "renewcms apply-update" by a oneshot systemd service
|
||||
And the data directory is the directory that holds DB_FILE; no new env var is added
|
||||
And the files in the data directory are:
|
||||
update-restart-request.json (marker, written by the app):
|
||||
{"kind":"update"|"restart","tag" (update only),"requested_at" RFC3339 UTC,"requested_by" user_id};
|
||||
update-result.json (written by the helper):
|
||||
{"outcome":"running"|"succeeded"|"rolled_back"|"failed","kind","tag","from_version","started_at","finished_at"};
|
||||
update-helper.json (status file, written by enable-browser-updates):
|
||||
{"version":1,"service","binary","data_dir","installed_at"};
|
||||
update-running.json (written by the server at every startup):
|
||||
{"version","pid","started_at"}
|
||||
And the marker is written atomically (temp file in the data directory, then rename) and deleted by the helper after reading it
|
||||
And the technical reason of a failure goes to the log or journal only, never into a file the app serves or a response
|
||||
And the domain package internal/domain/update (stdlib only) gains these interfaces, each faked in tests:
|
||||
RestartRequestStore (write, read, delete the marker),
|
||||
ResultStore (read, write and delete the result),
|
||||
RunningInfoStore (the server writes update-running.json; the helper reads it),
|
||||
HelperFilesystem (lstat, open with no-follow, read, create-exclusive, copy, rename, remove, chmod, make a fresh private
|
||||
temp directory, all of them symlink-aware),
|
||||
ServiceControl (restart and status of the systemd service),
|
||||
HealthChecker (GET http://127.0.0.1:<port>/healthz, true on 200),
|
||||
Clock
|
||||
And the helper logic depends only on those interfaces and on update.SignatureVerifier from slice 2 with the embedded release.pub
|
||||
And O_NOFOLLOW and lstat behaviour sit behind HelperFilesystem so the logic is tested on any OS; the real adapter is Linux-only
|
||||
(build-tagged) and is covered by the manual systemd checklist
|
||||
And RequestRestartUseCase and the extended GetUpdateStatusUseCase depend only on domain interfaces; handlers in
|
||||
api/handlers/update receive them through NewHandler; only api/dependecyInjection.go builds the adapters
|
||||
And POST /v1/system/update/restart is mounted in NewSystemRouter behind jwtauth.Verifier, jwtauth.Authenticator,
|
||||
RequireCurrentToken, RequireVerifiedUser and RequireOwner; there is no limiter
|
||||
And its optional JSON body is {"kind":"update"|"restart"}, bound to a request struct with
|
||||
validate:"omitempty,oneof=update restart" and checked by validator.Validate.Struct; an empty body is allowed
|
||||
And the checks on POST run in this order: no cookie or stale token (401), unverified (403), not owner (403),
|
||||
malformed body or invalid kind (400), can_apply false (409), job downloading or verifying (409), a restart already pending
|
||||
or running (409), kind that does not match the state (409), marker write error (500), then 202
|
||||
And with no body the server picks by state: job "ready" gives kind "update", anything else kind "restart"
|
||||
And the kind given must match: "update" needs a job "ready"; "restart" needs no job "ready"; otherwise 409 and nothing is written
|
||||
And POST download and POST restart delete update-result.json before they start a new job or write a marker
|
||||
And the 202 body is the status JSON with state "restarting" and started_at equal to the marker's requested_at (server clock)
|
||||
And errors are plain text from http.Error and carry no path or technical detail
|
||||
And GET /v1/system/update has no side effects; it keeps the 12 keys of slice 1 and gains exactly one key, "finished_at":
|
||||
the result's finished_at (RFC3339 UTC) whenever a result file exists, otherwise null, whatever the state
|
||||
And state is one of idle, downloading, verifying, ready, restarting, succeeded, failed, derived from the files by one rule:
|
||||
marker present, or result "running" younger than 5 minutes: "restarting";
|
||||
result "running" older than 5 minutes and no marker: "failed", error "install";
|
||||
result "succeeded", kind "update", tag equal to the running version: "succeeded";
|
||||
result "succeeded" for kind "restart", or kind "update" whose tag is no longer the running version: "idle";
|
||||
result "rolled_back": "failed", error "rolled_back";
|
||||
result "failed": "failed", error "install";
|
||||
otherwise the slice 2 job state; a missing or corrupt result file counts as no result
|
||||
And a result persists and is read the same on every GET until POST download or POST restart deletes it
|
||||
And error is null, "download", "verification", "rolled_back" or "install"
|
||||
And GET /healthz is unchanged: body "ok", no version header
|
||||
And the server writes update-running.json at every startup, after the listener is bound and before it serves, atomically; a write error
|
||||
is logged and is not fatal
|
||||
And the helper judges a restart by two things: GET /healthz answers 200 AND update-running.json holds the expected version AND it is
|
||||
NEW: its pid differs from the pid read before the restart, or its started_at is later than the instant the restart command
|
||||
was issued; a stale file with the old pid or started_at never counts
|
||||
And main gains a minimal dispatcher before the normal start: the subcommands enable-browser-updates, disable-browser-updates and
|
||||
apply-update run their own code and never read .env, open the database or listen; "--version" and the normal start are unchanged
|
||||
And the new subcommands never write a secret value or an env value into a unit file
|
||||
|
||||
Scenario: Request an update restart, happy path
|
||||
Given the owner, can_apply true and a job "ready" for "v2.3.0-beta"
|
||||
When the owner sends POST /v1/system/update/restart with no body, or with {"kind":"update"}
|
||||
Then the status is 202 and the body is the status JSON with state "restarting"
|
||||
And the marker holds kind "update", tag "v2.3.0-beta", requested_by the owner's user_id and requested_at
|
||||
And update-result.json was deleted first
|
||||
And the running binary, the staged files and the database are unchanged by the app
|
||||
And GET reports state "restarting" for any verified user
|
||||
|
||||
Scenario: Request a plain restart
|
||||
Given the owner, can_apply true and no job "ready"
|
||||
When the owner sends POST /v1/system/update/restart with no body, or with {"kind":"restart"}
|
||||
Then the status is 202, the marker holds kind "restart" and no tag, and GET reports state "restarting"
|
||||
|
||||
Scenario Outline: The kind must match the state
|
||||
Given the owner, can_apply true and <state>
|
||||
When the owner sends POST /v1/system/update/restart with {"kind":"<kind>"}
|
||||
Then the status is 409, no marker is written, the result file and the job are untouched
|
||||
|
||||
Examples:
|
||||
| state | kind |
|
||||
| no job "ready" (idle) | update |
|
||||
| a job "failed" | update |
|
||||
| a job "ready" | restart |
|
||||
|
||||
Scenario: Restart site never installs an update another owner just made ready
|
||||
Given owner A opened the Plain restart dialog while the job was idle
|
||||
And owner B then made a job "ready"
|
||||
When owner A confirms and the SPA sends {"kind":"restart"}
|
||||
Then the status is 409, nothing is installed and the staged files are untouched
|
||||
And the SPA reloads the card and shows "Ready to install"
|
||||
|
||||
Scenario Outline: A bad body is a 400
|
||||
Given the owner and can_apply true
|
||||
When the owner sends POST /v1/system/update/restart with <body>
|
||||
Then the status is 400 with a plain text body and no marker is written
|
||||
|
||||
Examples:
|
||||
| body |
|
||||
| {"kind":"upgrade"} |
|
||||
| {"kind":""} |
|
||||
| {"kind":7} |
|
||||
| {"kind":"update" |
|
||||
| not json |
|
||||
|
||||
Scenario Outline: POST is guarded like the other system routes
|
||||
When <caller> sends POST /v1/system/update/restart
|
||||
Then the status is <status> and no marker is written and no result is deleted
|
||||
|
||||
Examples:
|
||||
| caller | status | body |
|
||||
| no jwt cookie | 401 | the existing 401 text |
|
||||
| a stale token version | 401 | the existing 401 text |
|
||||
| an unverified owner | 403 | the existing unverified text |
|
||||
| an admin | 403 | apperr.OwnerRequiredErrorMessage |
|
||||
|
||||
Scenario Outline: Restart is refused with 409
|
||||
Given the owner and <condition>
|
||||
When the owner sends POST /v1/system/update/restart
|
||||
Then the status is 409, the existing marker, result and job are untouched and no new marker is written
|
||||
|
||||
Examples:
|
||||
| condition |
|
||||
| can_apply is false (no update-helper.json) |
|
||||
| the job state is downloading |
|
||||
| the job state is verifying |
|
||||
| a marker is already pending |
|
||||
| the result file reads "running" (helper at work) |
|
||||
|
||||
Scenario: Two restarts at once write one marker
|
||||
When two owners send POST /v1/system/update/restart concurrently
|
||||
Then exactly one answers 202 and the other 409 and one marker exists
|
||||
|
||||
Scenario: The marker cannot be written
|
||||
Given the data directory is not writable, or a directory sits where the marker file goes
|
||||
When the owner sends POST /v1/system/update/restart
|
||||
Then the status is 500 with a plain text body without paths, no marker exists and the job record is untouched
|
||||
|
||||
Scenario Outline: GET derives the state from the files and never changes them
|
||||
Given <files>
|
||||
When any verified user sends GET /v1/system/update twice
|
||||
Then both answers are identical, state is <state>, error is <error> and finished_at is <finished>
|
||||
And no file in the data directory changed
|
||||
|
||||
Examples:
|
||||
| files | state | error | finished |
|
||||
| a marker is present | restarting | null | null |
|
||||
| result "running" written 30 s ago | restarting | null | null |
|
||||
| result "running" written 6 minutes ago, no marker | failed | "install" | its value |
|
||||
| result "succeeded", kind "update", tag equal to the running version | succeeded | null | its value |
|
||||
| result "succeeded", kind "update", tag older than the running one | idle | null | its value |
|
||||
| result "succeeded", kind "restart" | idle | null | its value |
|
||||
| result "rolled_back" | failed | "rolled_back" | its value |
|
||||
| result "failed" | failed | "install" | its value |
|
||||
| no marker, no result | idle | null | null |
|
||||
| a corrupt result file | idle | null | null |
|
||||
|
||||
Scenario: The result lives until the next job
|
||||
Given a result "rolled_back"
|
||||
When the owner sends POST /v1/system/update/download and the job reaches "ready"
|
||||
Then the result file was deleted by the POST, GET reports state "ready", error null and finished_at null
|
||||
And GET /v1/system/update still has exactly the 12 keys of slice 1 plus finished_at
|
||||
|
||||
Scenario: After a successful update the status is consistent
|
||||
Given a result "succeeded" for "v2.3.0-beta" and the running version "v2.3.0-beta"
|
||||
Then GET reports state "succeeded", available false, current "v2.3.0-beta" and finished_at set
|
||||
|
||||
Scenario: The server writes update-running.json at startup
|
||||
When the server starts with version "v2.3.0-beta"
|
||||
Then update-running.json holds {"version":"v2.3.0-beta","pid":<its pid>,"started_at":<now>} written atomically
|
||||
And it is written after the listener is bound and before requests are served
|
||||
And a write error is logged and the server still starts
|
||||
And a second start replaces the file with the new pid and started_at
|
||||
And the file is not served by any route
|
||||
|
||||
Scenario: Healthz is unchanged
|
||||
When a client sends GET /healthz
|
||||
Then the status is 200, the body is "ok" and there is no version header, and the route stays public
|
||||
|
||||
Scenario Outline: The command dispatcher
|
||||
When the binary is run with "<args>" and an empty environment
|
||||
Then <outcome>
|
||||
|
||||
Examples:
|
||||
| args | outcome |
|
||||
| --version | it prints the version, exits 0 (unchanged from slice 2) |
|
||||
| enable-browser-updates | it runs the installer, never reads .env or opens the database |
|
||||
| disable-browser-updates | it runs the uninstaller, never reads .env or opens the database |
|
||||
| apply-update | it runs the helper, never reads .env or opens the database |
|
||||
| no arguments | the normal server start |
|
||||
| an unknown subcommand | a usage message on stderr and a non-zero exit, the server is not started |
|
||||
|
||||
Scenario Outline: enable-browser-updates refuses when it cannot work
|
||||
Given <situation>
|
||||
When "renewcms enable-browser-updates" runs
|
||||
Then it exits non-zero with the clear message "<message>" and writes nothing
|
||||
|
||||
Examples:
|
||||
| situation | message |
|
||||
| the OS is not Linux | Browser updates need Linux with systemd. |
|
||||
| Linux without systemd (no /run/systemd/system) | Browser updates need systemd, which this machine is not running. |
|
||||
| not run as root | Run this command as root, for example with sudo. |
|
||||
| no unit for the service and no flags | Could not find the RenewCMS service. Pass --service, --binary and --data-dir. |
|
||||
| the data directory cannot be resolved | Could not find the data directory. Pass --data-dir. |
|
||||
|
||||
Scenario: enable-browser-updates installs the units
|
||||
Given systemd on Linux, root, and an existing renewcms.service with ExecStart=/opt/renewcms/renewcms and ReadWritePaths=/var/lib/renewcms
|
||||
When "renewcms enable-browser-updates" runs
|
||||
Then it reads the service name, binary path and data directory from the unit, with --service, --binary and --data-dir overriding them
|
||||
And it writes renewcms-update.path (PathExists= the marker) and renewcms-update.service (Type=oneshot, User=root,
|
||||
ExecStart=<binary> apply-update with the service, binary, data directory and port as flags)
|
||||
And the port comes from --port, else from PORT in the service's environment file, else 8080
|
||||
And it runs daemon-reload and enables and starts the path unit
|
||||
And it writes update-helper.json last, so can_apply becomes true only when everything else worked
|
||||
And no secret and no environment value is written into either unit
|
||||
And it prints what it installed and how to undo it
|
||||
|
||||
Scenario: enable-browser-updates is idempotent
|
||||
Given it ran once
|
||||
When it runs again, including after the binary path or service name changed
|
||||
Then the units and the status file are rewritten to the current values, no duplicate unit exists and the exit is 0
|
||||
|
||||
Scenario: enable-browser-updates undoes its own partial work
|
||||
Given writing the second unit, daemon-reload or enable fails
|
||||
Then the first unit is removed, update-helper.json is not written and the exit is non-zero with the reason
|
||||
|
||||
Scenario: disable-browser-updates
|
||||
Given browser updates are enabled
|
||||
When "renewcms disable-browser-updates" runs
|
||||
Then the path unit is stopped and disabled, both unit files and update-helper.json are removed, daemon-reload runs
|
||||
And the marker and result files, the staged files and backups are left in place
|
||||
And running it again, or where it was never enabled, exits 0 with a message
|
||||
And can_apply reads false afterwards
|
||||
|
||||
Scenario: apply-update, a plain restart
|
||||
Given a marker of kind "restart" and update-running.json with pid 100 and started_at T0
|
||||
When the helper runs
|
||||
Then it reads the marker without following symlinks, deletes it, and writes the result "running" with started_at
|
||||
And it records the current update-running.json, restarts the service once and polls until /healthz answers 200
|
||||
and update-running.json is new (pid differs from 100, or started_at is later than the restart instant)
|
||||
And it then writes "succeeded" with kind "restart" and finished_at
|
||||
And the binary and the staged files are untouched
|
||||
|
||||
Scenario Outline: A stale running file never counts as success
|
||||
Given a marker and update-running.json that <staleness> while /healthz answers 200
|
||||
When the helper polls
|
||||
Then it keeps polling and it is not declared succeeded or rolled back until a new file appears or 60 s pass
|
||||
|
||||
Examples:
|
||||
| staleness |
|
||||
| still holds the old pid and old started_at |
|
||||
| holds the target version but the old pid and an old started_at |
|
||||
| is missing |
|
||||
| is corrupt |
|
||||
| holds the old version with a new pid (for an update) |
|
||||
|
||||
Scenario: apply-update, an update, happy path
|
||||
Given a marker of kind "update" for "v2.3.0-beta" and a staged binary, checksums.txt and checksums.txt.sig under updates/v2.3.0-beta/
|
||||
When the helper runs
|
||||
Then it creates a fresh root-owned temp directory with mode 0700 and copies the staged files into it, opening each original with no-follow
|
||||
And it verifies the signature of the COPIED checksums.txt with the embedded public key
|
||||
And it verifies the SHA-256 of the COPIED binary against its checksums.txt line, ignoring the earlier job record
|
||||
And it copies the current binary to <name>.previous, replacing an older .previous
|
||||
And it writes the verified copy to a temp file in the binary's directory (mode 0755), checks that it still hashes to the verified value,
|
||||
and installs it with an atomic rename; the original staged path is never installed
|
||||
And it restarts the service and polls /healthz and update-running.json for up to 60 s
|
||||
And when /healthz answers 200 and update-running.json is new and holds "v2.3.0-beta" it writes "succeeded", success being declared on the
|
||||
first matching poll
|
||||
And it removes the temp directory and updates/v2.3.0-beta/
|
||||
And the marker was deleted before any other step ran
|
||||
|
||||
Scenario Outline: apply-update refuses an untrusted staged binary
|
||||
Given a marker of kind "update" and <fault>
|
||||
When the helper runs
|
||||
Then the current binary is not touched, no .previous is written and the service is not restarted
|
||||
And it writes "failed", logs the technical reason only, and removes the temp directory and updates/<tag>/
|
||||
|
||||
Examples:
|
||||
| fault |
|
||||
| the binary was changed after the job verified it |
|
||||
| checksums.txt was changed |
|
||||
| the signature is from a different key or is missing |
|
||||
| checksums.txt has no line for the asset |
|
||||
| the staged binary is missing |
|
||||
|
||||
Scenario Outline: apply-update refuses symlinks
|
||||
Given a marker of kind "update" and <symlink>
|
||||
When the helper runs
|
||||
Then it never reads through the link, the current binary is untouched, there is no .previous and no restart
|
||||
And it writes "failed" and logs which path was a symlink
|
||||
And whatever the link pointed to is not read, copied, written or removed
|
||||
|
||||
Examples:
|
||||
| symlink |
|
||||
| the marker itself is a symlink |
|
||||
| <data>/updates is a symlink to another directory |
|
||||
| <data>/updates/<tag> is a symlink to another directory |
|
||||
| the staged binary is a symlink to /usr/bin/something |
|
||||
| checksums.txt is a symlink |
|
||||
| checksums.txt.sig is a symlink |
|
||||
| a symlink is placed at the result path or at a temp file name |
|
||||
|
||||
Scenario: A symlinked marker is removed, not followed
|
||||
Given the marker is a symlink to a file outside the data directory
|
||||
When the helper runs
|
||||
Then the link itself is unlinked, the target is untouched, and the result is "failed"
|
||||
|
||||
Scenario: A file swapped after verification is not installed
|
||||
Given the staged binary is verified and a fake attacker replaces the original staged path with other bytes right after the copy step
|
||||
When the helper installs
|
||||
Then the installed bytes equal the verified copy's bytes and not the swapped bytes
|
||||
And the same holds for a swap during the .previous copy and the final rename
|
||||
And a swap of the temp file in the binary's directory before the rename is caught by the re-hash and ends as "failed" with the binary untouched
|
||||
|
||||
Scenario: Result and temp files are written without following links
|
||||
Given the service user placed a symlink at update-result.json or at a predictable temp name in the data directory
|
||||
When the helper writes its result
|
||||
Then it creates a temp file with create-exclusive and no-follow, then renames it over the result, and the link target is untouched
|
||||
|
||||
Scenario Outline: apply-update distrusts the marker
|
||||
Given a marker whose tag is <tag>
|
||||
When the helper runs
|
||||
Then it writes "failed", the binary is untouched, the service is not restarted and nothing outside <data>/updates is read
|
||||
|
||||
Examples:
|
||||
| tag |
|
||||
| ../../etc/passwd |
|
||||
| v2.3.0-beta/../../x |
|
||||
| an empty string |
|
||||
| v2.1.0-beta (older than the running version) |
|
||||
| not-a-version |
|
||||
|
||||
Scenario Outline: apply-update rolls back when the new version does not come up
|
||||
Given an update marker and <fault> after the new binary was installed and the service restarted
|
||||
When the helper runs
|
||||
Then within the 60 s window it restores <name>.previous over the binary atomically and restarts the service again
|
||||
And it polls until /healthz answers 200 and a NEW update-running.json holds the old version
|
||||
And it writes "rolled_back" with from_version and tag and removes the temp directory and the staged files
|
||||
|
||||
Examples:
|
||||
| fault |
|
||||
| /healthz never answers within 60 s |
|
||||
| /healthz answers but update-running.json stays old |
|
||||
| update-running.json holds another version |
|
||||
| the service restart command fails |
|
||||
|
||||
Scenario Outline: apply-update failures around the swap
|
||||
Given an update marker and <fault>
|
||||
Then <outcome>
|
||||
|
||||
Examples:
|
||||
| fault | outcome |
|
||||
| copying to .previous fails | the binary is untouched, the service not restarted, result "failed" |
|
||||
| the atomic install fails | .previous and the old binary are intact, no restart, result "failed" |
|
||||
| the rollback restore itself fails | result "failed", logged loudly, exit non-zero |
|
||||
| the old version never returns after rollback | result "failed" (not "rolled_back"), exit non-zero |
|
||||
|
||||
Scenario: The result is always written
|
||||
Given any marker and any outcome, including a panic in the helper
|
||||
Then update-result.json holds outcome, kind, tag, from_version, started_at and finished_at, written atomically
|
||||
And a "running" record exists from the moment the marker was read until the outcome replaces it
|
||||
|
||||
Scenario: Only the helper runs with privilege
|
||||
Then the app has no code that execs systemctl, writes outside the data directory or reads the units
|
||||
And the oneshot service and path unit contain no environment secrets
|
||||
|
||||
Scenario: Settings, owner, Restart buttons (route /settings)
|
||||
Given the owner and can_apply true
|
||||
Then with state "ready" the Restart button (power, primary) is enabled and opens the Install dialog
|
||||
And with state "idle" (Up to date or Check failed) the Restart button (power, secondary) is enabled and opens the Plain restart dialog
|
||||
And with state "downloading", "verifying" or "restarting" Restart is disabled or absent as the card draws it
|
||||
And with can_apply false (Not prepared) or the admin view no Restart is rendered
|
||||
And the slice 2 disabled Restart in Ready to install is now enabled and has a handler
|
||||
And the SPA sends {"kind":"update"} from the Install dialog and {"kind":"restart"} from the Plain restart dialog, always
|
||||
|
||||
Scenario: Settings, Restart: confirm (Install dialog)
|
||||
When the owner presses Restart in Ready to install
|
||||
Then a dialog titled "Restart to finish the update?" shows "RenewCMS will install version 2.3.0-beta and restart. Your site will be unavailable for about 10 seconds. This page reloads on its own when the site is back. Save anything you're editing first."
|
||||
And its buttons are "Restart later" and "Restart now", the confirm is neutral, not red
|
||||
And focus moves to the first button, Escape and "Restart later" close it and focus returns to Restart
|
||||
And no request is sent until "Restart now"
|
||||
|
||||
Scenario: Settings, Plain restart: confirm
|
||||
When the owner presses Restart with no update waiting
|
||||
Then a dialog titled "Restart the site?" shows "Your site will be unavailable for about 10 seconds. This page reloads on its own when the site is back. Save anything you're editing first."
|
||||
And its buttons are "Cancel" and "Restart site", with the same focus and Escape behaviour
|
||||
|
||||
Scenario: Settings, Restart: request failed
|
||||
Given the confirm button is pressed and POST /v1/system/update/restart answers 500 or never reaches the server
|
||||
Then the dialog stays open (install or plain) with the error "Couldn't start the restart. Nothing was changed and your site is still running. Try again in a moment."
|
||||
And the confirm button is enabled again, no overlay shows and nothing is stored in sessionStorage
|
||||
|
||||
Scenario: Settings, this tab remembers that it started the restart
|
||||
Given POST /v1/system/update/restart answers 202 with started_at "S"
|
||||
Then sessionStorage holds one entry with the kind and "S" (the server's started_at), and no other storage is written
|
||||
And the overlay shows
|
||||
|
||||
Scenario: Settings, Restarting to install
|
||||
Given POST /v1/system/update/restart answers 202 for an update
|
||||
Then a full-page region with role "status" shows, titled "Installing version 2.3.0-beta" with
|
||||
"Your site is restarting with the new version. This takes about 10 seconds. This page reloads on its own when the site is back." and a moving bar
|
||||
And it is announced once as "Installing version 2.3.0-beta. Your site is restarting."
|
||||
And the overlay survives failing requests and the Offline banner state is ignored while it shows
|
||||
And it polls GET /healthz and GET /v1/system/update every second, tolerating network errors and non-200 answers
|
||||
|
||||
Scenario: Settings, Plain restart: restarting
|
||||
Given POST /v1/system/update/restart answers 202 for a plain restart
|
||||
Then the overlay shows "Restarting your site" / "This takes about 10 seconds. This page reloads on its own when the site is back."
|
||||
And it polls the same way
|
||||
|
||||
Scenario: Settings, Restarting, taking longer
|
||||
Given 60 seconds pass with no answer from /healthz or from GET /v1/system/update
|
||||
Then the overlay shows "Still restarting" / "This is taking longer than usual. Keep this page open. It reloads on its own when the site is back, or you can reload it now." and a "Reload page" button
|
||||
And the meta reads "Started at 09:51 · 1 minute ago" (clock-sensitive)
|
||||
And "Reload page" reloads the page, the overlay stays until the site answers, and the polling continues
|
||||
|
||||
Scenario: Settings, the overlay ends when the site answers
|
||||
Given the overlay shows and /healthz answers and GET /v1/system/update answers with a state other than "restarting"
|
||||
and finished_at later than the stored started_at
|
||||
Then the page reloads once
|
||||
And a GET answering "restarting", a GET whose finished_at is null or not later than the stored started_at, a /healthz answer without a GET
|
||||
answer, and a rejected GET all keep the overlay and do not reload
|
||||
|
||||
Scenario: Settings, Update done (the tab that started it)
|
||||
Given the page reloaded, sessionStorage holds {kind "update", started_at "S"} and GET answers state "succeeded" with finished_at later than "S"
|
||||
Then the entry is cleared, focus lands on the "Updates" heading (id="updates-h") with the ring shown
|
||||
And a success toast "Update installed" / "RenewCMS is now on version 2.3.0-beta." is announced
|
||||
And the Version card shows the new running version and the card reads "You're on version 2.3.0-beta" /
|
||||
"The update is installed and your site is running again." / "Updated today at 09:52" with a "Read the release notes" link (arrow-up-right)
|
||||
|
||||
Scenario: Settings, Update failed, rolled back (the tab that started it)
|
||||
Given the page reloaded, sessionStorage holds {kind "update", started_at "S"} and GET answers state "failed", error "rolled_back", finished_at later than "S", running "v2.2.0-beta"
|
||||
Then the entry is cleared and focus lands on "Updates"
|
||||
And an error toast (stays until dismissed) with icon circle-x "The update didn't install" / "Your site is back on v2.2.0-beta." shows
|
||||
And the card shows icon triangle-alert (warning) "The update didn't install" /
|
||||
"RenewCMS put the previous version back, so your site is running as before. Nothing was lost." /
|
||||
"What to do next: try again in a few minutes. If it fails again, ask whoever manages your server to check the update." and a "Try again" button that sends POST /v1/system/update/download
|
||||
And error "install" renders the same card and toast
|
||||
|
||||
Scenario: Settings, Plain restart: done (the tab that started it)
|
||||
Given the page reloaded, sessionStorage holds {kind "restart", started_at "S"} and GET answers state "idle" with finished_at later than "S"
|
||||
Then the entry is cleared, focus lands on "Updates" and a success toast "Site restarted" / "Your site is running again." is announced
|
||||
And the card is the normal Up to date card
|
||||
|
||||
Scenario Outline: A later visit shows the card with no toast and no focus move
|
||||
Given sessionStorage has no entry, or an entry whose started_at is not earlier than finished_at, and GET answers <result>
|
||||
Then the card renders for that state, no toast shows and focus does not move to "Updates"
|
||||
And nothing is written to sessionStorage
|
||||
|
||||
Examples:
|
||||
| result |
|
||||
| state "succeeded", finished_at set |
|
||||
| state "failed", error "rolled_back" |
|
||||
| state "failed", error "install" |
|
||||
| state "idle", finished_at set (plain restart) |
|
||||
|
||||
Scenario: Settings, another owner's tab never takes the toast
|
||||
Given owner B has /settings open, with no sessionStorage entry, while GET answers "restarting" and later "succeeded"
|
||||
Then owner B's page shows the overlay while "restarting" and the card afterwards, with no toast and no focus move
|
||||
And owner A's tab, which holds the entry, still gets the toast and the focus
|
||||
And an admin sees the admin view and no overlay
|
||||
|
||||
Scenario: Settings, a stale sessionStorage entry
|
||||
Given an entry left behind by a restart that never finished in this tab (the tab was closed and reopened by hand)
|
||||
When the page loads and GET answers a finished_at that is not later than the entry's started_at, or null
|
||||
Then no toast shows, focus does not move, the entry stays until a later finished_at consumes it, and a new restart overwrites it
|
||||
|
||||
Scenario: Settings, 409 on Restart
|
||||
Given POST /v1/system/update/restart answers 409
|
||||
Then the dialog closes, nothing is stored in sessionStorage and the card reloads
|
||||
And when the reload shows downloading, verifying or restarting an info toast "An update is already running" / "Another owner started it. Progress shows here." shows and the card or overlay switches to that run
|
||||
And when the reload shows can_apply false the card shows "Not prepared" and no toast
|
||||
And when the reload shows a different "Ready to install" or "idle" (the kind did not match) the card shows that state and no toast
|
||||
|
||||
Scenario: Settings, 400 on Restart
|
||||
Given POST /v1/system/update/restart answers 400
|
||||
Then the dialog shows the "Couldn't start the restart" text and nothing is stored in sessionStorage
|
||||
|
||||
Scenario: Settings, 403 role changed on Restart
|
||||
Given POST /v1/system/update/restart answers 403
|
||||
Then the dialog closes, an error toast "Only the owner can do this" / "Ask the owner of this site to update RenewCMS." shows and the card reloads in the admin view
|
||||
|
||||
Scenario: Settings, 401 on Restart
|
||||
Given POST /v1/system/update/restart answers 401
|
||||
Then the global handler goes to /login?redirect=/settings&reason=expired and no local copy shows
|
||||
|
||||
Scenario: Home banner while restarting
|
||||
Given state "restarting"
|
||||
Then Home shows no update banner and does not poll
|
||||
|
||||
Scenario: The docs gain a "Browser updates" section
|
||||
Then docs/deployment.md has "Browser updates" with the one-time command "sudo renewcms enable-browser-updates", what it installs
|
||||
(two units, update-helper.json), how to undo it ("sudo renewcms disable-browser-updates"), and what is and is not supported
|
||||
And it lists: Linux with systemd only; not Windows, macOS, Docker or other init systems; the previous binary is kept as <name>.previous
|
||||
and a database backup in backups/; an update whose new version does not come up within 60 s is rolled back automatically
|
||||
And it names the files update-restart-request.json, update-result.json, update-helper.json and update-running.json
|
||||
And the "How to update" link of the Not prepared card points at that section
|
||||
And the sentence "the site does not update itself" in the "Update checks" section is replaced
|
||||
@@ -0,0 +1,187 @@
|
||||
# QA: Updates part 3 (restart, helper, rollback)
|
||||
|
||||
## Automated Go (`task test`, package `test`, black-box, no live systemd, no real SMTP, no network)
|
||||
|
||||
Files: `test/update_restart_http_test.go` (HTTP), `test/update_restart_usecase_test.go` (request and status use cases),
|
||||
`test/update_helper_test.go` (helper logic over fakes, including rollback and hardening), `test/update_helper_install_test.go`
|
||||
(enable and disable over fakes), `test/update_helper_files_test.go` (real file adapters in `t.TempDir()`),
|
||||
`test/update_dispatch_test.go` (built binary).
|
||||
|
||||
Fakes with unique names: `fakeRestartRequestStore`, `fakeResultStore`, `fakeRunningInfoStore` (scripted per poll: absent, corrupt, stale,
|
||||
new), `fakeHelperFS`, `fakeServiceControl` (records restart calls with the clock instant; can fail), `fakeHealthChecker` (scripted per poll),
|
||||
`fakeClock` (advances without sleeping), `fakeUnitWriter` (records unit contents, can fail the Nth write). Reuse `fakeJobStore`,
|
||||
`fakeHelperDetector`, `fakeUpdateStore`, `mockUserRepo` and the throwaway ed25519 signer from slices 1 and 2. Never read the committed `release.pub`.
|
||||
|
||||
`fakeHelperFS`: an in-memory tree of files, directories and symlinks with owners and modes; `lstat`, no-follow open, create-exclusive, copy,
|
||||
rename, remove and a fresh private temp directory are the only operations; every call is recorded in order with its path; an operation that
|
||||
would traverse a symlink without the no-follow flag follows it (so a test fails if the code forgets to refuse); it can fail the Nth
|
||||
call of an operation, and it has a hook `after(op, n, mutate)` that mutates the tree after a chosen call (used to swap the original
|
||||
staged file after the copy step). Tests assert the paths the helper touched stay inside the data directory, the binary directory and
|
||||
its own temp directory.
|
||||
|
||||
HTTP setup: `validator.InitValidator()`; `jwtauth.New("HS256", []byte("test-secret"), nil)`; a fresh `chi.NewRouter()` at `/v1/system`
|
||||
mirroring `NewSystemRouter` (Verifier, Authenticator, RequireCurrentToken, RequireVerifiedUser; the restart route also RequireOwner);
|
||||
cookies as in `test/stale_token_invalidation_http_test.go`. Marker, result and job files go in `t.TempDir()` through the real JSON adapters,
|
||||
plus the fakes where noted. Helper time is driven by `fakeClock`: no `time.Sleep`, so the 60 s window runs instantly.
|
||||
|
||||
### Tests the coder must update (they exist from slices 1 and 2 and will break)
|
||||
- Slice 1 tests that assert GET /v1/system/update has exactly 12 keys: now 13, with `finished_at` (null when no result file).
|
||||
- Slice 2 tests and Vitest specs that assert the Restart button in "Ready to install" is disabled and has no handler, that no restart
|
||||
endpoint, dialog or overlay exists, and that plain Restart is not rendered: replace them with the enabled behaviour below.
|
||||
- Slice 2 "Pending states for slice 3" visual entries: they become real setups.
|
||||
- Any slice 2 test that builds the status use case with a result store must accept the new `ResultStore` dependency.
|
||||
|
||||
### HTTP and use case (Go-testable)
|
||||
1. Restart, update: ready job, can_apply on. POST with no body and POST `{"kind":"update"}` give 202 with state "restarting" and
|
||||
`started_at` equal to the marker's `requested_at`; the marker has kind "update", the tag, requested_by equal to the owner id; the result file
|
||||
was deleted first; no other file changed; GET as an admin also reads "restarting".
|
||||
2. Plain restart: idle job. No body and `{"kind":"restart"}` give 202, marker kind "restart", empty tag. Also after a failed job and after a
|
||||
rolled-back result.
|
||||
3. Kind mismatch: `{"kind":"update"}` with no ready job (idle, failed) and `{"kind":"restart"}` with a ready job give 409; no marker, result and job untouched.
|
||||
"Restart site never installs": owner A's body `{"kind":"restart"}` after the fake job store turned "ready" gives 409, no marker, staged files untouched.
|
||||
4. Bad body: `{"kind":"upgrade"}`, `{"kind":""}`, `{"kind":7}`, truncated JSON, `not json` give 400 plain text, no marker. The struct uses
|
||||
`validate:"omitempty,oneof=update restart"` and goes through `validator.Validate.Struct`; an empty body and `{}` are accepted.
|
||||
5. Guards: admin 403 with `apperr.OwnerRequiredErrorMessage+"\n"`; no cookie 401; stale token 401; unverified 403; none writes a marker or deletes the result.
|
||||
Order: an admin with a bad body gets 403, an owner with a bad body and can_apply off gets 400, can_apply off and a kind mismatch gives 409.
|
||||
6. 409 table: can_apply off, downloading, verifying, marker pending, result "running": no second marker, existing files untouched.
|
||||
7. Concurrency (`-race`): two simultaneous POSTs give one 202, one 409, one marker.
|
||||
8. 500: a directory where the marker goes, and a read-only temp directory (`t.Skip` that one on Windows): 500, plain text without the path, no marker,
|
||||
job record unchanged.
|
||||
9. State derivation, one subtest per row of the feature table. Each row calls GET twice: the two bodies are byte-identical, `state`, `error` and
|
||||
`finished_at` match, and a snapshot of every file in the data directory (names, bytes, mtimes) is unchanged by the GETs (GET has no side effects).
|
||||
The 5-minute boundary uses `fakeClock`. Assert exactly the 12 slice 1 keys plus `finished_at`.
|
||||
10. The result lives until the next job: a "rolled_back" result, then POST download and a job reaching "ready": the result is gone,
|
||||
state "ready", error null, `finished_at` null. POST restart also deletes it before writing the marker.
|
||||
11. After success: result "succeeded" for the running tag gives `available` false, `current` the new version, `finished_at` set.
|
||||
12. Server startup file: with the real running-info adapter in `t.TempDir()` write twice; the file has `version`, `pid` and `started_at`, the second
|
||||
write replaces the first, it is written by a temp file plus rename, and a write into a missing directory returns an error that the startup code logs
|
||||
(use case or startup function returns it; it does not panic). The built binary (item 15) writes it before it answers `/healthz`.
|
||||
13. `/healthz` is unchanged: body "ok", no `X-RenewCMS-Version` header, public.
|
||||
14. A new download after "rolled_back" gives 202 and later a "ready" with error null.
|
||||
15. Dispatcher: build with `go build -tags nofrontend -ldflags "-X main.version=v9.9.9" ./cmd/server` into `t.TempDir()`; with an empty environment
|
||||
`--version` prints `v9.9.9`; an unknown subcommand exits non-zero with usage and does not listen; `apply-update` and `enable-browser-updates`
|
||||
run without `.env` and create no `data/` (on a non-Linux machine the latter exits non-zero with the Linux/systemd message, which covers the Windows refusal).
|
||||
|
||||
### Helper logic over fakes (Go-testable, no systemd)
|
||||
Fixture: fake FS with the binary `/opt/renewcms/renewcms` ("old"), staged `updates/v2.3.0-beta/` binary, `checksums.txt` and `checksums.txt.sig`
|
||||
signed with a throwaway key injected through the verifier constructor, a marker, running version v2.2.0-beta, `update-running.json` with pid 100 and
|
||||
started_at T0.
|
||||
|
||||
16. Plain restart: the marker is opened no-follow and deleted first, result "running" then "succeeded", one service restart, no write to the binary.
|
||||
Success needs `/healthz` 200 AND a running file that is NEW.
|
||||
17. Stale running info, one subtest per row: old pid and old started_at; target version but old pid and old started_at; absent; corrupt; old version with a new pid
|
||||
(for an update). Health answers 200 throughout. The helper keeps polling and is not declared succeeded or rolled back until the file turns new or the
|
||||
fake clock passes 60 s. Also: a file whose started_at is later than the restart instant counts as new even with the same pid.
|
||||
18. Update happy path, asserting the ORDER of fake calls: no-follow read and delete of the marker, "running", fresh 0700 temp directory, no-follow copy of the
|
||||
three staged files into it, signature check on the copy, SHA-256 of the copied binary, copy of the current binary to `.previous`, temp file in the
|
||||
binary's directory written from the verified copy, re-hash of that temp file, atomic rename, mode 0755, record running info, restart, polls,
|
||||
"succeeded", removal of the temp directory and `updates/<tag>/`. Final FS: binary equals the new bytes, `.previous` equals the old bytes.
|
||||
Success is declared on the first matching poll, not at 60 s.
|
||||
19. Re-verification, one subtest each: tampered binary, tampered checksums.txt, other-key signature, missing signature, no line for the asset, missing
|
||||
binary. Each: binary unchanged, no `.previous`, zero restarts, result "failed", staged dir and temp dir removed, reason in the injected logger only.
|
||||
20. Symlinks, one subtest each: marker; `updates`; `updates/<tag>`; the binary; checksums.txt; checksums.txt.sig; a link at the result path; a link at a
|
||||
predictable temp file name. Each: the FS records no read, write, copy or removal through the link (the targets, placed outside the allowed
|
||||
directories with sentinel bytes, are unchanged), binary untouched, no `.previous`, zero restarts, result "failed", the log names the link path.
|
||||
The symlinked marker case: the link itself is unlinked and the target is intact.
|
||||
21. TOCTOU: with the `after` hook, replace the original staged binary with other bytes immediately after the copy step; the installed bytes equal the
|
||||
verified copy's bytes. Repeat with the swap after the signature check, after the hash check, and after the `.previous` copy. A swap of the temp file
|
||||
in the binary's directory between write and rename is caught by the re-hash: result "failed", binary untouched.
|
||||
22. Result and temp writes: create-exclusive and no-follow, then rename; a pre-planted symlink at the result path or a temp name leaves the target intact.
|
||||
23. Hostile marker tags (traversal, traversal with valid prefix, empty, older version, malformed): result "failed", zero restarts, every touched path
|
||||
under the allowed directories.
|
||||
24. Rollback table: health never answers (60 s of fake clock, about 60 polls at 1 s), healthy but running file stays old, other version in the running file,
|
||||
restart error. Each: binary restored to "old" through an atomic rename, second restart issued, polled until a NEW running file holds the old version,
|
||||
result "rolled_back" with from_version and tag, temp directory and staged dir removed.
|
||||
25. Swap failures: `.previous` copy fails (binary untouched, no restart, "failed"); atomic install fails (old binary and `.previous` intact, "failed");
|
||||
restore fails ("failed", error returned, loud log); old version never returns after rollback ("failed", not "rolled_back").
|
||||
26. Result always written: a panic in the fake service control still leaves outcome "failed" with `finished_at`; the "running" record exists before the
|
||||
first service call; writes are atomic.
|
||||
27. Timestamps come from `fakeClock`; finished is not before started.
|
||||
28. Enable, over fake FS, unit writer and service control: refuses non-Linux, no systemd, not root, no unit and no flags, no data directory (exact
|
||||
messages); on success writes both units containing the service, binary and data directory from the parsed unit, the `PathExists=` marker line and
|
||||
the port flag (`--port` over `PORT` from the env file over 8080); the units never contain `JWT_SECRET` or any value from the env file (seed the
|
||||
fixture env file with `JWT_SECRET=sentinel-secret` and search both units); flags override the unit; the status file is written LAST; running it
|
||||
twice gives identical files and one unit pair; each failing step leaves no status file and removes the first unit.
|
||||
29. Disable: removes units and the status file, keeps marker, result, staged files and backups; idempotent; a no-op where it was never enabled;
|
||||
`can_apply` reads false afterwards through the real file detector.
|
||||
30. Real adapters on `t.TempDir()`: the JSON marker, result, status and running-info stores round trip; the atomic write replaces an existing file.
|
||||
The Linux-only no-follow adapter has a test file with `//go:build linux` (it runs on Linux CI machines and the user's WSL2, and is skipped on Windows).
|
||||
31. Review items, not Go tests: the app (handlers, use cases, `api/`) execs no `systemctl` and writes only inside the data directory;
|
||||
`internal/domain/update` imports only the stdlib; use cases import no `os/exec`, `net/http`, `gorm` or adapter; the handler imports no adapter;
|
||||
the real filesystem adapter is the only code that calls `syscall.O_NOFOLLOW`; no secret in the repo; no new env var; `go vet -tags nofrontend`
|
||||
and `gofmt` clean; no comments.
|
||||
|
||||
## Automated SPA (Vitest + Vue Test Utils, `task test:web`)
|
||||
|
||||
Mock `useApi.request` for `GET /v1/system/update`, `POST .../restart` and `POST .../download`; mock `fetch` for `GET /healthz`. Fake timers drive the
|
||||
1 s polls and the 60 s switch. Stub `window.location.reload` and use a fresh `sessionStorage` per test. No test freezes the system date and none asserts a
|
||||
relative date or "09:51". Sample data: running `v2.2.0-beta`, latest `v2.3.0-beta`, `started_at` and `finished_at` as plain strings.
|
||||
|
||||
One test per state:
|
||||
1. Restart button: ready gives primary enabled; idle gives secondary enabled; downloading, verifying, restarting give disabled; can_apply false and admin give none.
|
||||
2. Install dialog: exact title, text, buttons; focus on the first button; Escape and "Restart later" close it; focus returns to Restart; no request until
|
||||
"Restart now"; the confirm is neutral; the request body is `{"kind":"update"}`.
|
||||
3. Plain restart dialog: exact copy, "Cancel" / "Restart site", same behaviour; the request body is `{"kind":"restart"}`.
|
||||
4. Restart request failed: 500 and `NetworkError`, in both dialogs: dialog stays, the exact error text, confirm enabled again, no overlay, nothing in sessionStorage. A 400 gives the same.
|
||||
5. After 202, sessionStorage holds one entry with the kind and the response's `started_at`; no localStorage write.
|
||||
6. Restarting to install: overlay `role="status"`, title and text, announced once; stays mounted when `fetch` rejects; the offline banner state is ignored; polls
|
||||
/healthz and GET every second.
|
||||
7. Plain restart: restarting: "Restarting your site" copy.
|
||||
8. Taking longer: at 60 s "Still restarting", the text, "Reload page" present; pressing it calls reload; the overlay stays.
|
||||
9. Overlay end: reload once when /healthz is ok and GET gives a non-"restarting" state with `finished_at` later than the stored `started_at`; no reload on
|
||||
"restarting", on `finished_at` null, on `finished_at` not later, on a rejected GET, or without a GET answer; reload is not called twice.
|
||||
10. Update done (entry present, state "succeeded", later `finished_at`): entry cleared, focus on `#updates-h`, success toast "Update installed" / "RenewCMS is now on version 2.3.0-beta.", card text and the "Read the release notes" link.
|
||||
11. Rolled back (error "rolled_back" and "install"): entry cleared, focus on `#updates-h`, sticky error toast, card copy, "Try again" posts download.
|
||||
12. Plain restart done (state "idle", later `finished_at`, kind "restart"): toast "Site restarted" / "Your site is running again.", focus, Up to date card, entry cleared.
|
||||
13. No entry, or an entry not earlier than `finished_at`: for each of succeeded, rolled_back, install and plain-restart-idle results the card renders with no toast, no
|
||||
focus move and no sessionStorage write.
|
||||
14. Another owner's tab: no entry, GET "restarting" then "succeeded": overlay then card, no toast, no focus move. An owner tab with an entry still gets the toast. An admin sees the
|
||||
admin view, no overlay and no poll.
|
||||
15. Stale entry: `finished_at` null or earlier than the entry's `started_at` gives no toast and keeps the entry; a new restart overwrites it.
|
||||
16. 409: reload downloading gives the info toast and progress; reload restarting gives the toast and overlay; reload can_apply false gives Not prepared and no toast; reload "ready"
|
||||
or "idle" after a kind mismatch gives that card, no toast, nothing in sessionStorage.
|
||||
17. 403: error toast and the admin view; 401 shows no local copy (the global handler is mocked).
|
||||
18. Home: no banner or poll while "restarting".
|
||||
19. Regression: slice 2's disabled-Restart assertions are replaced; Not prepared and the admin view still have no Restart.
|
||||
|
||||
## Visual (`task visual:check -- settings`; desktop and mobile, light and dark; every capture within 10 %)
|
||||
|
||||
`web/visual/states.ts` setups are added later by the coder, with the board's sample data (v2.2.0-beta, v2.3.0-beta). Exact values come from
|
||||
`docs/design/source/AppFrame.dc.html` and the "Settings" group of the Screens board; describe layout as drawn (open the frame markup for the dialog, the overlay card
|
||||
and its 440 px width before judging).
|
||||
- [ ] Restart: confirm (install dialog)
|
||||
- [ ] Plain restart: confirm
|
||||
- [ ] Restart: request failed
|
||||
- [ ] Restarting to install
|
||||
- [ ] Plain restart: restarting
|
||||
- [ ] Update failed, rolled back (the toast only if the frame draws it)
|
||||
- [ ] `skip: 'clock-sensitive'`: Update done and Plain restart: done (meta "Updated today at 09:52"), Restarting, taking longer (meta "Started at 09:51 · 1 minute ago"); their copy is covered by Vitest
|
||||
- [ ] Slice 2 pending states are now real: re-run the other Settings states and confirm Ready to install with an enabled Restart is within budget
|
||||
- [ ] If a capture exceeds 10 %, stop and report; do not widen the budget or add an exception without the user's approval
|
||||
- [ ] Not covered by screenshots: keyboard and focus order in both dialogs, the ring on `#updates-h` after the result states, the one-time overlay announcement, the motion of the bar, the Offline banner being ignored
|
||||
|
||||
## Manual only (real systemd Linux: WSL2 with systemd enabled, or a VPS): CANNOT be verified automatically
|
||||
The user will run these. The helper's decision logic, ordering, symlink refusal, TOCTOU defence and rollback are unit-tested over fakes (items 16 to 27), but none of the following is covered:
|
||||
- [ ] On Windows or macOS `renewcms enable-browser-updates` refuses with the clear message.
|
||||
- [ ] On a VPS following docs/deployment.md (service user `renewcms`, `ProtectSystem=strict`, only `/var/lib/renewcms` writable): `sudo renewcms enable-browser-updates` reads the real unit, writes
|
||||
`renewcms-update.path` and `renewcms-update.service`, enables the path unit (`systemctl status` active) and writes `update-helper.json`; a second run changes nothing.
|
||||
- [ ] The Settings page shows the Update button (can_apply true) after a reload.
|
||||
- [ ] The path unit fires when the sandboxed app writes the marker, and the app (as `renewcms`) can write the marker and cannot write the binary, the units or anything outside the data directory.
|
||||
- [ ] The server writes `update-running.json` at startup (`cat` it: version, pid, started_at) and a restart replaces it.
|
||||
- [ ] Real update from a real signed release (real `release.pub` committed, `task release` signing): Update, Ready, Restart, overlay, reload on the new version, toast on the tab that started it,
|
||||
`.previous` next to the binary, `renewcms --version` equals the new tag, `journalctl -u renewcms-update` shows the helper log.
|
||||
- [ ] Real rollback: stage a signed release whose binary prints the right `--version` but crashes at boot; the old binary is restored within about 60 s, the card reads "The update didn't install", the toast stays.
|
||||
- [ ] Plain restart: overlay, about 10 s of downtime, reload with "Site restarted".
|
||||
- [ ] The real no-follow adapter on Linux: as the service user, replace `updates/<tag>` with a symlink to `/etc`, replace the staged binary with a symlink, replace the marker with a symlink, and swap the staged file during
|
||||
an update (a loop that rewrites it); the helper refuses or installs only verified bytes, and nothing outside the data directory is read or changed.
|
||||
- [ ] Planted symlink at `update-result.json` pointing at a root-only file: the helper does not write through it.
|
||||
- [ ] Binary directory ownership, SELinux and AppArmor do not block the atomic rename, and the temp file is on the same filesystem as the binary; the helper's private temp directory is root-owned 0700 and is removed.
|
||||
- [ ] A hand-written marker with another tag, as the service user: refused, binary untouched.
|
||||
- [ ] `sudo renewcms disable-browser-updates` removes the units and status file; the card returns to "Not prepared"; nothing else is deleted.
|
||||
- [ ] A reverse proxy (nginx or Caddy) returns 502 during the restart and the overlay survives it; `/healthz` is not cached.
|
||||
- [ ] Two owners in two browsers during a restart: both show the overlay; only the tab that started it gets the toast and focus.
|
||||
- [ ] Embedded SPA build (no `-tags nofrontend`) serves `/settings` with the new dialogs and overlay.
|
||||
- [ ] Journal and files contain no secret, and technical reasons are only in the journal.
|
||||
|
||||
## Final note
|
||||
Not verifiable automatically: the whole privileged path on a real systemd Linux machine (generated units, path-unit trigger from the sandboxed app, real service restart, atomic swap on a real filesystem, real rollback, O_NOFOLLOW behaviour, permissions, SELinux or AppArmor, reverse-proxy behaviour). It needs the manual test on WSL2 with systemd or a VPS, which the user will do.
|
||||
@@ -11,8 +11,9 @@ require (
|
||||
github.com/go-playground/validator/v10 v10.28.0
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/joho/godotenv v1.5.1
|
||||
golang.org/x/crypto v0.44.0
|
||||
golang.org/x/crypto v0.57.0
|
||||
golang.org/x/image v0.46.0
|
||||
golang.org/x/net v0.59.0
|
||||
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
|
||||
gorm.io/gorm v1.31.1
|
||||
)
|
||||
|
||||
@@ -78,14 +78,16 @@ github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
golang.org/x/crypto v0.44.0 h1:A97SsFvM3AIwEEmTBiaxPPTYpDC47w720rdiiUvgoAU=
|
||||
golang.org/x/crypto v0.44.0/go.mod h1:013i+Nw79BMiQiMsOPcVCB5ZIJbYkerPrGnOa00tvmc=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 h1:zfMcR1Cs4KNuomFFgGefv5N0czO2XZpUbxGUy8i8ug0=
|
||||
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6/go.mod h1:46edojNIoXTNOhySWIWdix628clX9ODXwPsQuG6hsK0=
|
||||
golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ=
|
||||
golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew=
|
||||
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
|
||||
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
|
||||
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
|
||||
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package apikey
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrAPIKeyNotFound = errors.New("api key not found")
|
||||
var ErrAPIKeyInvalid = errors.New("api key invalid")
|
||||
var ErrExpiryNotInFuture = errors.New("api key expiry not in the future")
|
||||
|
||||
const RawKeyPrefix = "rcms_"
|
||||
|
||||
type Status string
|
||||
|
||||
const (
|
||||
StatusActive Status = "active"
|
||||
StatusExpired Status = "expired"
|
||||
StatusRevoked Status = "revoked"
|
||||
)
|
||||
|
||||
type APIKey struct {
|
||||
ID uint32 `json:"id"`
|
||||
UserID uint32 `json:"user_id"`
|
||||
Name string `json:"name"`
|
||||
Prefix string `json:"prefix"`
|
||||
HashedKey string `json:"hashed_key"`
|
||||
ExpiresAt *time.Time `json:"expires_at"`
|
||||
RevokedAt *time.Time `json:"revoked_at"`
|
||||
LastUsedAt *time.Time `json:"last_used_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func (k APIKey) StatusAt(now time.Time) Status {
|
||||
if k.RevokedAt != nil {
|
||||
return StatusRevoked
|
||||
}
|
||||
if k.ExpiresAt != nil && !now.Before(*k.ExpiresAt) {
|
||||
return StatusExpired
|
||||
}
|
||||
return StatusActive
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package apikey
|
||||
|
||||
type KeyGenerator interface {
|
||||
Generate() (rawKey string, prefix string, hashedKey string)
|
||||
Hash(rawKey string) string
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package apikey
|
||||
|
||||
import "time"
|
||||
|
||||
type Repository interface {
|
||||
Create(key APIKey) (APIKey, error)
|
||||
Get(id uint32) (APIKey, error)
|
||||
GetByHashedKey(hashedKey string) (APIKey, error)
|
||||
ListByUser(userId uint32) ([]APIKey, error)
|
||||
ListAll() ([]APIKey, error)
|
||||
Revoke(id uint32, at time.Time) error
|
||||
RevokeAllByUser(userId uint32, at time.Time) error
|
||||
TouchLastUsed(id uint32, at time.Time) error
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package article
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var ErrUnsupportedBodyFormat = errors.New("unsupported body format")
|
||||
|
||||
type BodyFormat string
|
||||
|
||||
const (
|
||||
BodyFormatMarkdown BodyFormat = "markdown"
|
||||
BodyFormatHTML BodyFormat = "html"
|
||||
BodyFormatJSON BodyFormat = "json"
|
||||
)
|
||||
|
||||
func ParseBodyFormat(value string) (BodyFormat, error) {
|
||||
switch strings.ToLower(value) {
|
||||
case "", string(BodyFormatMarkdown):
|
||||
return BodyFormatMarkdown, nil
|
||||
case string(BodyFormatHTML):
|
||||
return BodyFormatHTML, nil
|
||||
case string(BodyFormatJSON):
|
||||
return BodyFormatJSON, nil
|
||||
}
|
||||
return "", ErrUnsupportedBodyFormat
|
||||
}
|
||||
|
||||
type BodyRenderer interface {
|
||||
Render(html string, format BodyFormat) (string, error)
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
const StateIdle = "idle"
|
||||
|
||||
var (
|
||||
ErrNoRelease = errors.New("no release found")
|
||||
ErrInvalidVersion = errors.New("invalid version")
|
||||
ErrFeedUnavailable = errors.New("release feed unavailable")
|
||||
)
|
||||
|
||||
type ReleaseNotes struct {
|
||||
Version string `json:"version"`
|
||||
ReleasedAt time.Time `json:"released_at"`
|
||||
Items []string `json:"items"`
|
||||
}
|
||||
|
||||
type Asset struct {
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url"`
|
||||
Size int64 `json:"size"`
|
||||
}
|
||||
|
||||
type Release struct {
|
||||
Tag string
|
||||
URL string
|
||||
PublishedAt time.Time
|
||||
Notes ReleaseNotes
|
||||
Assets []Asset
|
||||
}
|
||||
|
||||
type CheckResult struct {
|
||||
Latest string `json:"latest"`
|
||||
ReleaseURL string `json:"release_url"`
|
||||
Notes ReleaseNotes `json:"notes"`
|
||||
Assets []Asset `json:"assets"`
|
||||
CheckedAt time.Time `json:"checked_at"`
|
||||
}
|
||||
|
||||
type Progress struct {
|
||||
Percent int `json:"percent"`
|
||||
DownloadedBytes int64 `json:"downloaded_bytes"`
|
||||
TotalBytes int64 `json:"total_bytes"`
|
||||
}
|
||||
|
||||
type UpdateStatus struct {
|
||||
Current string `json:"current"`
|
||||
Latest string `json:"latest"`
|
||||
Available bool `json:"available"`
|
||||
ReleaseURL *string `json:"release_url"`
|
||||
Notes *ReleaseNotes `json:"notes"`
|
||||
CheckedAt *time.Time `json:"checked_at"`
|
||||
CanApply bool `json:"can_apply"`
|
||||
State string `json:"state"`
|
||||
Progress *Progress `json:"progress"`
|
||||
Error *string `json:"error"`
|
||||
StartedAt *time.Time `json:"started_at"`
|
||||
FinishedAt *time.Time `json:"finished_at"`
|
||||
}
|
||||
|
||||
func NewResult(release Release, checkedAt time.Time) CheckResult {
|
||||
return CheckResult{
|
||||
Latest: release.Tag,
|
||||
ReleaseURL: release.URL,
|
||||
Notes: release.Notes,
|
||||
Assets: release.Assets,
|
||||
CheckedAt: checkedAt.UTC(),
|
||||
}
|
||||
}
|
||||
|
||||
func NewStatus(current string, result *CheckResult) UpdateStatus {
|
||||
status := UpdateStatus{Current: current, State: StateIdle}
|
||||
if result == nil {
|
||||
return status
|
||||
}
|
||||
releaseURL := result.ReleaseURL
|
||||
notes := result.Notes
|
||||
notes.Items = nonNilItems(notes.Items)
|
||||
checkedAt := result.CheckedAt
|
||||
status.Latest = result.Latest
|
||||
status.Available = IsNewer(current, result.Latest)
|
||||
status.ReleaseURL = &releaseURL
|
||||
status.Notes = ¬es
|
||||
status.CheckedAt = &checkedAt
|
||||
return status
|
||||
}
|
||||
|
||||
func nonNilItems(items []string) []string {
|
||||
if items == nil {
|
||||
return []string{}
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func Newest(releases []Release) (Release, error) {
|
||||
var newest Release
|
||||
found := false
|
||||
for _, release := range releases {
|
||||
if _, err := ParseVersion(release.Tag); err != nil {
|
||||
continue
|
||||
}
|
||||
if !found || IsNewer(newest.Tag, release.Tag) {
|
||||
newest = release
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return Release{}, ErrNoRelease
|
||||
}
|
||||
return newest, nil
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNeedsLinux = errors.New("Browser updates need Linux with systemd.")
|
||||
ErrNeedsSystemd = errors.New("Browser updates need systemd, which this machine is not running.")
|
||||
ErrNeedsRoot = errors.New("Run this command as root, for example with sudo.")
|
||||
ErrServiceNotFound = errors.New("Could not find the RenewCMS service. Pass --service, --binary and --data-dir.")
|
||||
ErrDataDirNotFound = errors.New("Could not find the data directory. Pass --data-dir.")
|
||||
ErrInvalidPort = errors.New("The port must be a number between 1 and 65535.")
|
||||
)
|
||||
|
||||
const (
|
||||
OSLinux = "linux"
|
||||
pathUnitDescription = "Watch for a RenewCMS restart request"
|
||||
)
|
||||
|
||||
type ServiceDescription struct {
|
||||
Name string
|
||||
BinaryPath string
|
||||
DataDir string
|
||||
EnvironmentFile string
|
||||
}
|
||||
|
||||
type InstallOptions struct {
|
||||
Service string
|
||||
Binary string
|
||||
DataDir string
|
||||
Port string
|
||||
}
|
||||
|
||||
type MachineProbe interface {
|
||||
OS() string
|
||||
SystemdRunning() bool
|
||||
IsRoot() bool
|
||||
}
|
||||
|
||||
type ServiceLocator interface {
|
||||
Locate(name string) (ServiceDescription, bool)
|
||||
PortFromEnvironmentFile(path string) (string, bool)
|
||||
}
|
||||
|
||||
type UnitWriter interface {
|
||||
Write(name string, content string) error
|
||||
Remove(name string) (bool, error)
|
||||
}
|
||||
|
||||
type UnitManager interface {
|
||||
DaemonReload() error
|
||||
EnableNow(unit string) error
|
||||
DisableNow(unit string) error
|
||||
}
|
||||
|
||||
type HelperStatusWriter interface {
|
||||
Write(dataDir string, status HelperStatus) error
|
||||
Remove(dataDir string) (bool, error)
|
||||
}
|
||||
|
||||
func CheckInstallEnvironment(probe MachineProbe) error {
|
||||
if probe.OS() != OSLinux {
|
||||
return ErrNeedsLinux
|
||||
}
|
||||
if !probe.SystemdRunning() {
|
||||
return ErrNeedsSystemd
|
||||
}
|
||||
if !probe.IsRoot() {
|
||||
return ErrNeedsRoot
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidatePort(port string) error {
|
||||
number, err := strconv.Atoi(port)
|
||||
if err != nil || number < 1 || number > 65535 {
|
||||
return ErrInvalidPort
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func RenderPathUnit(layout HelperLayout) string {
|
||||
lines := []string{
|
||||
"[Unit]",
|
||||
"Description=" + pathUnitDescription,
|
||||
"",
|
||||
"[Path]",
|
||||
"PathExists=" + layout.RestartRequestPath(),
|
||||
"Unit=" + ServiceUnitName,
|
||||
"",
|
||||
"[Install]",
|
||||
"WantedBy=multi-user.target",
|
||||
"",
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
func RenderServiceUnit(options InstallOptions) string {
|
||||
command := []string{
|
||||
quoteUnitArgument(options.Binary),
|
||||
"apply-update",
|
||||
"--service", quoteUnitArgument(options.Service),
|
||||
"--binary", quoteUnitArgument(options.Binary),
|
||||
"--data-dir", quoteUnitArgument(options.DataDir),
|
||||
"--port", options.Port,
|
||||
}
|
||||
lines := []string{
|
||||
"[Unit]",
|
||||
"Description=RenewCMS update helper",
|
||||
"",
|
||||
"[Service]",
|
||||
"Type=oneshot",
|
||||
"User=root",
|
||||
"ExecStart=" + strings.Join(command, " "),
|
||||
"",
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
var unitArgumentEscaper = strings.NewReplacer(
|
||||
`\`, `\\`,
|
||||
`"`, `\"`,
|
||||
`%`, `%%`,
|
||||
`$`, `$$`,
|
||||
"\n", `\n`,
|
||||
"\r", `\r`,
|
||||
"\t", `\t`,
|
||||
)
|
||||
|
||||
func quoteUnitArgument(value string) string {
|
||||
if !strings.ContainsAny(value, " \t\r\n\"'\\%$;") {
|
||||
return value
|
||||
}
|
||||
return `"` + unitArgumentEscaper.Replace(value) + `"`
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
StateDownloading = "downloading"
|
||||
StateVerifying = "verifying"
|
||||
StateReady = "ready"
|
||||
StateFailed = "failed"
|
||||
|
||||
ErrorKindDownload = "download"
|
||||
ErrorKindVerification = "verification"
|
||||
|
||||
ChecksumsAssetName = "checksums.txt"
|
||||
SignatureAssetName = "checksums.txt.sig"
|
||||
|
||||
windowsOS = "windows"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotPrepared = errors.New("this server cannot apply updates")
|
||||
ErrJobInProgress = errors.New("an update job is already running or ready")
|
||||
ErrNothingToUpdate = errors.New("there is nothing to update")
|
||||
ErrPreflightRefused = errors.New("the update cannot be downloaded")
|
||||
)
|
||||
|
||||
type Platform struct {
|
||||
OS string
|
||||
Arch string
|
||||
}
|
||||
|
||||
type Job struct {
|
||||
Tag string `json:"tag"`
|
||||
State string `json:"state"`
|
||||
Error string `json:"error"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
DownloadedBytes int64 `json:"downloaded_bytes"`
|
||||
TotalBytes int64 `json:"total_bytes"`
|
||||
StagedBinary string `json:"staged_binary"`
|
||||
}
|
||||
|
||||
type ProgressFunc func(done int64, total int64)
|
||||
|
||||
type AssetFetcher interface {
|
||||
Fetch(asset Asset, destination string, report ProgressFunc) error
|
||||
}
|
||||
|
||||
type SignatureVerifier interface {
|
||||
Verify(checksumsPath string, signaturePath string) error
|
||||
}
|
||||
|
||||
type StagedBinaryRunner interface {
|
||||
Version(binaryPath string) (string, error)
|
||||
}
|
||||
|
||||
type DatabaseBackup interface {
|
||||
Backup() (string, error)
|
||||
}
|
||||
|
||||
type StagingArea interface {
|
||||
Prepare(tag string) error
|
||||
PathFor(tag string, name string) string
|
||||
Size(path string) (int64, error)
|
||||
ReadChecksums(path string) (string, error)
|
||||
MakeExecutable(path string) error
|
||||
Remove(tag string) error
|
||||
}
|
||||
|
||||
type HelperDetector interface {
|
||||
Installed() bool
|
||||
}
|
||||
|
||||
type JobStore interface {
|
||||
Load() (Job, bool)
|
||||
Save(job Job) error
|
||||
}
|
||||
|
||||
type Logger interface {
|
||||
Printf(format string, args ...any)
|
||||
}
|
||||
|
||||
func (j Job) IsRunning() bool {
|
||||
return j.State == StateDownloading || j.State == StateVerifying
|
||||
}
|
||||
|
||||
func (j Job) Occupies() bool {
|
||||
return j.IsRunning() || j.State == StateReady
|
||||
}
|
||||
|
||||
func (j Job) Progress() *Progress {
|
||||
if j.State != StateDownloading || j.TotalBytes <= 0 {
|
||||
return nil
|
||||
}
|
||||
return &Progress{
|
||||
Percent: int(j.DownloadedBytes * 100 / j.TotalBytes),
|
||||
DownloadedBytes: j.DownloadedBytes,
|
||||
TotalBytes: j.TotalBytes,
|
||||
}
|
||||
}
|
||||
|
||||
func (s UpdateStatus) WithJob(job Job) UpdateStatus {
|
||||
s.State = job.State
|
||||
s.Progress = job.Progress()
|
||||
s.Error = nil
|
||||
if job.Error != "" {
|
||||
kind := job.Error
|
||||
s.Error = &kind
|
||||
}
|
||||
startedAt := job.StartedAt
|
||||
s.StartedAt = &startedAt
|
||||
return s
|
||||
}
|
||||
|
||||
func AssetName(tag string, platform Platform) string {
|
||||
name := "renewcms_" + tag + "_" + platform.OS + "_" + platform.Arch
|
||||
if platform.OS == windowsOS {
|
||||
name += ".exe"
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
func FindAsset(assets []Asset, name string) (Asset, bool) {
|
||||
for _, asset := range assets {
|
||||
if asset.Name == name {
|
||||
return asset, true
|
||||
}
|
||||
}
|
||||
return Asset{}, false
|
||||
}
|
||||
|
||||
func HostOf(rawURL string) string {
|
||||
parsed, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return parsed.Host
|
||||
}
|
||||
|
||||
func IsAllowedAssetURL(rawURL string, allowedHost string) bool {
|
||||
parsed, err := url.Parse(rawURL)
|
||||
if err != nil || parsed.Scheme != "https" {
|
||||
return false
|
||||
}
|
||||
return allowedHost != "" && parsed.Host == allowedHost
|
||||
}
|
||||
|
||||
func ChecksumFor(checksums string, assetName string) (string, bool) {
|
||||
for _, line := range strings.Split(checksums, "\n") {
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) == 2 && strings.TrimPrefix(fields[1], "*") == assetName {
|
||||
return strings.ToLower(fields[0]), true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func FileSHA256(path string) (string, error) {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer file.Close()
|
||||
hash := sha256.New()
|
||||
if _, err := io.Copy(hash, file); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(hash.Sum(nil)), nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"path"
|
||||
)
|
||||
|
||||
const (
|
||||
RestartRequestFileName = "update-restart-request.json"
|
||||
ResultFileName = "update-result.json"
|
||||
HelperStatusFileName = "update-helper.json"
|
||||
RunningInfoFileName = "update-running.json"
|
||||
UpdatesDirName = "updates"
|
||||
HelperStatusVersion = 1
|
||||
|
||||
PathUnitName = "renewcms-update.path"
|
||||
ServiceUnitName = "renewcms-update.service"
|
||||
DefaultService = "renewcms"
|
||||
DefaultPort = "8080"
|
||||
|
||||
PreviousSuffix = ".previous"
|
||||
PreviousTempSuffix = ".previous.tmp"
|
||||
InstallTempSuffix = ".new"
|
||||
RestoreTempSuffix = ".restore"
|
||||
ResultTempSuffix = ".tmp"
|
||||
ExecutableMode = 0o755
|
||||
PrivateFileMode = 0o600
|
||||
)
|
||||
|
||||
type HelperLayout struct {
|
||||
DataDir string
|
||||
BinaryPath string
|
||||
}
|
||||
|
||||
func (l HelperLayout) UpdatesDir() string {
|
||||
return path.Join(l.DataDir, UpdatesDirName)
|
||||
}
|
||||
|
||||
func (l HelperLayout) StagedDir(tag string) string {
|
||||
return path.Join(l.UpdatesDir(), tag)
|
||||
}
|
||||
|
||||
func (l HelperLayout) ResultPath() string {
|
||||
return path.Join(l.DataDir, ResultFileName)
|
||||
}
|
||||
|
||||
func (l HelperLayout) ResultTempPath() string {
|
||||
return l.ResultPath() + ResultTempSuffix
|
||||
}
|
||||
|
||||
func (l HelperLayout) RestartRequestPath() string {
|
||||
return path.Join(l.DataDir, RestartRequestFileName)
|
||||
}
|
||||
|
||||
func (l HelperLayout) PreviousPath() string {
|
||||
return l.BinaryPath + PreviousSuffix
|
||||
}
|
||||
|
||||
func SHA256Hex(content []byte) string {
|
||||
sum := sha256.Sum256(content)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
bulletLine = regexp.MustCompile(`^[-*+]\s+(.+)$`)
|
||||
markdownLink = regexp.MustCompile(`!?\[([^\]]*)\]\([^)]*\)`)
|
||||
boldText = regexp.MustCompile(`\*\*([^*]+)\*\*|__([^_]+)__`)
|
||||
italicText = regexp.MustCompile(`\*([^*\s][^*]*)\*`)
|
||||
inlineCode = regexp.MustCompile("`([^`]*)`")
|
||||
)
|
||||
|
||||
func BuildNotes(tag string, publishedAt time.Time, body string) ReleaseNotes {
|
||||
items := []string{}
|
||||
for _, line := range strings.Split(body, "\n") {
|
||||
match := bulletLine.FindStringSubmatch(strings.TrimSpace(line))
|
||||
if match == nil {
|
||||
continue
|
||||
}
|
||||
if item := plainText(match[1]); item != "" {
|
||||
items = append(items, item)
|
||||
}
|
||||
}
|
||||
return ReleaseNotes{Version: tag, ReleasedAt: publishedAt, Items: items}
|
||||
}
|
||||
|
||||
func plainText(markdown string) string {
|
||||
text := markdownLink.ReplaceAllString(markdown, "$1")
|
||||
text = boldText.ReplaceAllString(text, "$1$2")
|
||||
text = italicText.ReplaceAllString(text, "$1")
|
||||
text = inlineCode.ReplaceAllString(text, "$1")
|
||||
return strings.TrimSpace(text)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package update
|
||||
|
||||
type ReleaseFeed interface {
|
||||
Latest() (Release, error)
|
||||
}
|
||||
|
||||
type StatusStore interface {
|
||||
Load() (CheckResult, bool)
|
||||
Save(result CheckResult) error
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"regexp"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
StateRestarting = "restarting"
|
||||
StateSucceeded = "succeeded"
|
||||
|
||||
ErrorKindRolledBack = "rolled_back"
|
||||
ErrorKindInstall = "install"
|
||||
|
||||
RestartKindUpdate = "update"
|
||||
RestartKindRestart = "restart"
|
||||
|
||||
OutcomeRunning = "running"
|
||||
OutcomeSucceeded = "succeeded"
|
||||
OutcomeRolledBack = "rolled_back"
|
||||
OutcomeFailed = "failed"
|
||||
|
||||
RunningResultMaxAge = 5 * time.Minute
|
||||
)
|
||||
|
||||
var (
|
||||
ErrRestartPending = errors.New("a restart is already pending or running")
|
||||
ErrRestartKindMismatch = errors.New("the requested restart does not match the current state")
|
||||
ErrNoRestartRequest = errors.New("there is no restart request")
|
||||
ErrSymlinkRefused = errors.New("a symbolic link was found where a regular file is required")
|
||||
ErrInvalidRestartTag = errors.New("the restart request names an invalid version")
|
||||
ErrHelperUnsupported = errors.New("the privileged helper needs Linux")
|
||||
)
|
||||
|
||||
var restartTagPattern = regexp.MustCompile(`^v[0-9]+(\.[0-9]+)*(-[0-9A-Za-z.]+)?$`)
|
||||
|
||||
type RestartRequest struct {
|
||||
Kind string `json:"kind"`
|
||||
Tag string `json:"tag,omitempty"`
|
||||
RequestedAt time.Time `json:"requested_at"`
|
||||
RequestedBy uint32 `json:"requested_by"`
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
Outcome string `json:"outcome"`
|
||||
Kind string `json:"kind"`
|
||||
Tag string `json:"tag"`
|
||||
FromVersion string `json:"from_version"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
FinishedAt *time.Time `json:"finished_at"`
|
||||
}
|
||||
|
||||
type RunningInfo struct {
|
||||
Version string `json:"version"`
|
||||
Pid int `json:"pid"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
}
|
||||
|
||||
type HelperStatus struct {
|
||||
Version int `json:"version"`
|
||||
Service string `json:"service"`
|
||||
Binary string `json:"binary"`
|
||||
DataDir string `json:"data_dir"`
|
||||
InstalledAt time.Time `json:"installed_at"`
|
||||
}
|
||||
|
||||
type FileInfo struct {
|
||||
IsSymlink bool
|
||||
IsDir bool
|
||||
IsRegular bool
|
||||
}
|
||||
|
||||
type RestartRequestStore interface {
|
||||
Write(request RestartRequest) error
|
||||
Read() (RestartRequest, error)
|
||||
Delete() error
|
||||
}
|
||||
|
||||
type ResultStore interface {
|
||||
Read() (Result, bool)
|
||||
Write(result Result) error
|
||||
Delete() error
|
||||
}
|
||||
|
||||
type RunningInfoStore interface {
|
||||
Write(info RunningInfo) error
|
||||
Read() (RunningInfo, bool)
|
||||
}
|
||||
|
||||
type HelperFilesystem interface {
|
||||
Lstat(path string) (FileInfo, error)
|
||||
ReadFile(path string) ([]byte, error)
|
||||
CreateExclusive(path string, content []byte, mode uint32) error
|
||||
Copy(source string, destination string, mode uint32) error
|
||||
Rename(oldPath string, newPath string) error
|
||||
Remove(path string) error
|
||||
RemoveAll(path string) error
|
||||
Chmod(path string, mode uint32) error
|
||||
MakePrivateTempDir() (string, error)
|
||||
}
|
||||
|
||||
type ServiceControl interface {
|
||||
Restart() error
|
||||
Status() (bool, error)
|
||||
}
|
||||
|
||||
type HealthChecker interface {
|
||||
Healthy() bool
|
||||
}
|
||||
|
||||
type Clock interface {
|
||||
Now() time.Time
|
||||
Sleep(duration time.Duration)
|
||||
}
|
||||
|
||||
func ValidateRestartTag(tag string, runningVersion string) error {
|
||||
if !restartTagPattern.MatchString(tag) {
|
||||
return ErrInvalidRestartTag
|
||||
}
|
||||
if _, err := ParseVersion(tag); err != nil || !IsNewer(runningVersion, tag) {
|
||||
return ErrInvalidRestartTag
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r Result) IsRunning() bool {
|
||||
return r.Outcome == OutcomeRunning
|
||||
}
|
||||
|
||||
func (r Result) IsKnown() bool {
|
||||
switch r.Outcome {
|
||||
case OutcomeRunning, OutcomeSucceeded, OutcomeRolledBack, OutcomeFailed:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (i RunningInfo) IsNewerThan(previous RunningInfo, restartedAt time.Time) bool {
|
||||
return i.Pid != previous.Pid || i.StartedAt.After(restartedAt)
|
||||
}
|
||||
|
||||
const (
|
||||
RestartWindow = 60 * time.Second
|
||||
PollInterval = time.Second
|
||||
)
|
||||
|
||||
type SymlinkError struct {
|
||||
Path string
|
||||
}
|
||||
|
||||
func (e SymlinkError) Error() string {
|
||||
return e.Path + " is a symbolic link"
|
||||
}
|
||||
|
||||
func (e SymlinkError) Is(target error) bool {
|
||||
return target == ErrSymlinkRefused
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package update
|
||||
|
||||
import "time"
|
||||
|
||||
func (s UpdateStatus) WithRestartRequest(request RestartRequest) UpdateStatus {
|
||||
return s.settled(StateRestarting, "", request.RequestedAt)
|
||||
}
|
||||
|
||||
func (s UpdateStatus) WithResult(result Result, currentVersion string, now time.Time) UpdateStatus {
|
||||
if result.IsRunning() && now.Sub(result.StartedAt) < RunningResultMaxAge {
|
||||
return s.settled(StateRestarting, "", result.StartedAt)
|
||||
}
|
||||
if result.IsRunning() || result.Outcome == OutcomeFailed {
|
||||
return s.settled(StateFailed, ErrorKindInstall, result.StartedAt)
|
||||
}
|
||||
if result.Outcome == OutcomeRolledBack {
|
||||
return s.settled(StateFailed, ErrorKindRolledBack, result.StartedAt)
|
||||
}
|
||||
if result.Kind == RestartKindUpdate && result.Tag == currentVersion {
|
||||
return s.settled(StateSucceeded, "", result.StartedAt)
|
||||
}
|
||||
s.State = StateIdle
|
||||
s.Progress = nil
|
||||
s.Error = nil
|
||||
s.StartedAt = nil
|
||||
return s
|
||||
}
|
||||
|
||||
func (s UpdateStatus) settled(state string, errorKind string, startedAt time.Time) UpdateStatus {
|
||||
s.State = state
|
||||
s.Progress = nil
|
||||
s.Error = nil
|
||||
if errorKind != "" {
|
||||
s.Error = &errorKind
|
||||
}
|
||||
s.StartedAt = &startedAt
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Version struct {
|
||||
numbers []int
|
||||
pre []string
|
||||
}
|
||||
|
||||
func ParseVersion(raw string) (Version, error) {
|
||||
trimmed := strings.TrimPrefix(strings.TrimSpace(raw), "v")
|
||||
core, pre, hasPre := strings.Cut(trimmed, "-")
|
||||
if core == "" || (hasPre && pre == "") {
|
||||
return Version{}, ErrInvalidVersion
|
||||
}
|
||||
var version Version
|
||||
for _, segment := range strings.Split(core, ".") {
|
||||
number, err := strconv.Atoi(segment)
|
||||
if err != nil || number < 0 {
|
||||
return Version{}, ErrInvalidVersion
|
||||
}
|
||||
version.numbers = append(version.numbers, number)
|
||||
}
|
||||
if hasPre {
|
||||
version.pre = strings.Split(pre, ".")
|
||||
}
|
||||
return version, nil
|
||||
}
|
||||
|
||||
func IsNewer(current, latest string) bool {
|
||||
currentVersion, err := ParseVersion(current)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
latestVersion, err := ParseVersion(latest)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return compareVersions(latestVersion, currentVersion) > 0
|
||||
}
|
||||
|
||||
func compareVersions(a, b Version) int {
|
||||
if order := compareNumbers(a.numbers, b.numbers); order != 0 {
|
||||
return order
|
||||
}
|
||||
return comparePreRelease(a.pre, b.pre)
|
||||
}
|
||||
|
||||
func compareNumbers(a, b []int) int {
|
||||
for i := range max(len(a), len(b)) {
|
||||
if order := cmp.Compare(segmentAt(a, i), segmentAt(b, i)); order != 0 {
|
||||
return order
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func segmentAt(numbers []int, index int) int {
|
||||
if index < len(numbers) {
|
||||
return numbers[index]
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func comparePreRelease(a, b []string) int {
|
||||
if len(a) == 0 && len(b) == 0 {
|
||||
return 0
|
||||
}
|
||||
if len(a) == 0 {
|
||||
return 1
|
||||
}
|
||||
if len(b) == 0 {
|
||||
return -1
|
||||
}
|
||||
length := min(len(a), len(b))
|
||||
for i := 0; i < length; i++ {
|
||||
if order := compareIdentifiers(a[i], b[i]); order != 0 {
|
||||
return order
|
||||
}
|
||||
}
|
||||
return cmp.Compare(len(a), len(b))
|
||||
}
|
||||
|
||||
func compareIdentifiers(a, b string) int {
|
||||
numberA, errA := strconv.Atoi(a)
|
||||
numberB, errB := strconv.Atoi(b)
|
||||
if errA == nil && errB == nil {
|
||||
return cmp.Compare(numberA, numberB)
|
||||
}
|
||||
if errA == nil {
|
||||
return -1
|
||||
}
|
||||
if errB == nil {
|
||||
return 1
|
||||
}
|
||||
return strings.Compare(a, b)
|
||||
}
|
||||
@@ -32,6 +32,7 @@ type Settings struct {
|
||||
AuthRateLimit AuthRateLimitSettings
|
||||
TrustedProxies []string
|
||||
Version string
|
||||
UpdateFeedURL string
|
||||
}
|
||||
|
||||
func (s Settings) IsProduction() bool {
|
||||
@@ -74,6 +75,7 @@ func NewSettingsFromEnv() (Settings, error) {
|
||||
Window: time.Duration(authRateLimitWindowSeconds) * time.Second,
|
||||
},
|
||||
TrustedProxies: parseSemicolonSeparatedList(os.Getenv("TRUSTED_PROXIES")),
|
||||
UpdateFeedURL: os.Getenv("UPDATE_FEED_URL"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package hashing
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/apikey"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
)
|
||||
|
||||
const (
|
||||
apiKeyRandomBytes = 32
|
||||
apiKeyPrefixLen = 12
|
||||
)
|
||||
|
||||
type SHA256KeyGenerator struct{}
|
||||
|
||||
func NewSHA256KeyGenerator() *SHA256KeyGenerator {
|
||||
return &SHA256KeyGenerator{}
|
||||
}
|
||||
|
||||
func (g *SHA256KeyGenerator) Generate() (string, string, string) {
|
||||
random := make([]byte, apiKeyRandomBytes)
|
||||
_, _ = rand.Read(random)
|
||||
rawKey := apikey.RawKeyPrefix + base64.RawURLEncoding.EncodeToString(random)
|
||||
return rawKey, rawKey[:apiKeyPrefixLen], g.Hash(rawKey)
|
||||
}
|
||||
|
||||
func (g *SHA256KeyGenerator) Hash(rawKey string) string {
|
||||
sum := sha256.Sum256([]byte(rawKey))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
var _ apikey.KeyGenerator = &SHA256KeyGenerator{}
|
||||
@@ -0,0 +1,365 @@
|
||||
package markdown
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/net/html"
|
||||
"golang.org/x/net/html/atom"
|
||||
)
|
||||
|
||||
const (
|
||||
markBold = "bold"
|
||||
markItalic = "italic"
|
||||
markLink = "link"
|
||||
markCode = "code"
|
||||
|
||||
codeLanguagePrefix = "language-"
|
||||
)
|
||||
|
||||
type mark struct {
|
||||
kind string
|
||||
href string
|
||||
}
|
||||
|
||||
type inline struct {
|
||||
text string
|
||||
marks []mark
|
||||
}
|
||||
|
||||
type blockKind int
|
||||
|
||||
const (
|
||||
kindHeading blockKind = iota
|
||||
kindParagraph
|
||||
kindList
|
||||
kindBlockquote
|
||||
kindCode
|
||||
kindRule
|
||||
kindImage
|
||||
)
|
||||
|
||||
type block struct {
|
||||
kind blockKind
|
||||
level int
|
||||
inlines []inline
|
||||
ordered bool
|
||||
items [][]block
|
||||
children []block
|
||||
language string
|
||||
text string
|
||||
src string
|
||||
alt string
|
||||
align string
|
||||
}
|
||||
|
||||
var transparentBlocks = map[string]bool{
|
||||
"div": true, "section": true, "article": true, "header": true, "footer": true,
|
||||
"main": true, "aside": true, "nav": true, "figure": true, "figcaption": true,
|
||||
"table": true, "thead": true, "tbody": true, "tfoot": true, "tr": true,
|
||||
"td": true, "th": true, "dl": true, "dt": true, "dd": true, "details": true,
|
||||
"summary": true, "li": true,
|
||||
}
|
||||
|
||||
var skippedElements = map[string]bool{
|
||||
"script": true, "style": true, "template": true, "head": true,
|
||||
"noscript": true, "iframe": true, "object": true, "embed": true,
|
||||
}
|
||||
|
||||
var alignments = map[string]bool{"center": true, "right": true, "justify": true}
|
||||
|
||||
var allowedLinkSchemes = map[string]bool{
|
||||
"": true, "http": true, "https": true, "mailto": true, "tel": true,
|
||||
}
|
||||
|
||||
func parseBlocks(source string) ([]block, error) {
|
||||
context := &html.Node{Type: html.ElementNode, DataAtom: atom.Body, Data: "body"}
|
||||
nodes, err := html.ParseFragment(strings.NewReader(source), context)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
collector := newCollector(false, paragraphBlock)
|
||||
collector.walkAll(nodes, nil)
|
||||
return collector.finish(false), nil
|
||||
}
|
||||
|
||||
func paragraphBlock(inlines []inline) block {
|
||||
return block{kind: kindParagraph, inlines: inlines}
|
||||
}
|
||||
|
||||
func headingBlock(level int) func([]inline) block {
|
||||
return func(inlines []inline) block {
|
||||
return block{kind: kindHeading, level: level, inlines: inlines}
|
||||
}
|
||||
}
|
||||
|
||||
type collector struct {
|
||||
out []block
|
||||
current []inline
|
||||
keepBlank bool
|
||||
build func([]inline) block
|
||||
}
|
||||
|
||||
func newCollector(keepBlank bool, build func([]inline) block) *collector {
|
||||
return &collector{keepBlank: keepBlank, build: build}
|
||||
}
|
||||
|
||||
func (c *collector) walkAll(nodes []*html.Node, marks []mark) {
|
||||
for _, node := range nodes {
|
||||
c.walk(node, marks)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *collector) walkChildren(parent *html.Node, marks []mark) {
|
||||
for child := parent.FirstChild; child != nil; child = child.NextSibling {
|
||||
c.walk(child, marks)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *collector) addText(text string, marks []mark) {
|
||||
if text == "" {
|
||||
return
|
||||
}
|
||||
c.current = appendInline(c.current, inline{text: text, marks: marks})
|
||||
}
|
||||
|
||||
func (c *collector) flush() {
|
||||
if len(c.current) == 0 {
|
||||
return
|
||||
}
|
||||
if c.keepBlank || hasVisibleText(c.current) {
|
||||
c.out = append(c.out, c.build(c.current))
|
||||
}
|
||||
c.current = nil
|
||||
}
|
||||
|
||||
func (c *collector) finish(emitEmpty bool) []block {
|
||||
hadBlocks := len(c.out) > 0
|
||||
c.flush()
|
||||
if emitEmpty && !hadBlocks && len(c.out) == 0 {
|
||||
c.out = append(c.out, c.build(nil))
|
||||
}
|
||||
return c.out
|
||||
}
|
||||
|
||||
func (c *collector) walk(node *html.Node, marks []mark) {
|
||||
switch node.Type {
|
||||
case html.TextNode:
|
||||
c.addText(node.Data, marks)
|
||||
return
|
||||
case html.ElementNode:
|
||||
default:
|
||||
return
|
||||
}
|
||||
|
||||
tag := node.Data
|
||||
if skippedElements[tag] {
|
||||
return
|
||||
}
|
||||
|
||||
switch tag {
|
||||
case "br":
|
||||
c.addText("\n", marks)
|
||||
case "strong", "b":
|
||||
c.walkChildren(node, withMark(marks, mark{kind: markBold}))
|
||||
case "em", "i":
|
||||
c.walkChildren(node, withMark(marks, mark{kind: markItalic}))
|
||||
case "code":
|
||||
c.walkChildren(node, withMark(marks, mark{kind: markCode}))
|
||||
case "a":
|
||||
href := safeHref(attr(node, "href"))
|
||||
if href == "" {
|
||||
c.walkChildren(node, marks)
|
||||
return
|
||||
}
|
||||
c.walkChildren(node, withMark(marks, mark{kind: markLink, href: href}))
|
||||
case "img":
|
||||
c.flush()
|
||||
if src := attr(node, "src"); src != "" {
|
||||
c.out = append(c.out, block{kind: kindImage, src: src, alt: attr(node, "alt")})
|
||||
}
|
||||
case "hr":
|
||||
c.flush()
|
||||
c.out = append(c.out, block{kind: kindRule})
|
||||
case "p":
|
||||
c.flush()
|
||||
c.out = append(c.out, parseTextBlock(node, paragraphBlock)...)
|
||||
case "h1", "h2", "h3", "h4", "h5", "h6":
|
||||
c.flush()
|
||||
level, _ := strconv.Atoi(tag[1:])
|
||||
c.out = append(c.out, parseTextBlock(node, headingBlock(level))...)
|
||||
case "ul", "ol":
|
||||
c.flush()
|
||||
c.out = append(c.out, parseList(node))
|
||||
case "blockquote":
|
||||
c.flush()
|
||||
c.out = append(c.out, block{kind: kindBlockquote, children: parseContainer(node)})
|
||||
case "pre":
|
||||
c.flush()
|
||||
c.out = append(c.out, parseCodeBlock(node))
|
||||
default:
|
||||
if transparentBlocks[tag] {
|
||||
c.flush()
|
||||
c.walkChildren(node, marks)
|
||||
c.flush()
|
||||
return
|
||||
}
|
||||
c.walkChildren(node, marks)
|
||||
}
|
||||
}
|
||||
|
||||
func parseTextBlock(node *html.Node, build func([]inline) block) []block {
|
||||
inner := newCollector(true, build)
|
||||
inner.walkChildren(node, nil)
|
||||
blocks := inner.finish(true)
|
||||
if align := alignFromStyle(attr(node, "style")); align != "" {
|
||||
for index := range blocks {
|
||||
if blocks[index].kind == kindParagraph || blocks[index].kind == kindHeading {
|
||||
blocks[index].align = align
|
||||
}
|
||||
}
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
|
||||
func alignFromStyle(style string) string {
|
||||
for _, declaration := range strings.Split(style, ";") {
|
||||
name, value, found := strings.Cut(declaration, ":")
|
||||
if !found || strings.ToLower(strings.TrimSpace(name)) != "text-align" {
|
||||
continue
|
||||
}
|
||||
if align := strings.ToLower(strings.TrimSpace(value)); alignments[align] {
|
||||
return align
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func parseContainer(node *html.Node) []block {
|
||||
inner := newCollector(false, paragraphBlock)
|
||||
inner.walkChildren(node, nil)
|
||||
return inner.finish(false)
|
||||
}
|
||||
|
||||
func parseList(node *html.Node) block {
|
||||
list := block{kind: kindList, ordered: node.Data == "ol"}
|
||||
for child := node.FirstChild; child != nil; child = child.NextSibling {
|
||||
if child.Type == html.ElementNode && child.Data == "li" {
|
||||
list.items = append(list.items, parseContainer(child))
|
||||
}
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
func parseCodeBlock(node *html.Node) block {
|
||||
code := block{kind: kindCode, text: strings.TrimSuffix(textContent(node), "\n")}
|
||||
for child := node.FirstChild; child != nil; child = child.NextSibling {
|
||||
if child.Type == html.ElementNode && child.Data == "code" {
|
||||
code.language = languageFromClass(attr(child, "class"))
|
||||
break
|
||||
}
|
||||
}
|
||||
return code
|
||||
}
|
||||
|
||||
func languageFromClass(class string) string {
|
||||
for _, name := range strings.Fields(class) {
|
||||
if strings.HasPrefix(name, codeLanguagePrefix) {
|
||||
return strings.TrimPrefix(name, codeLanguagePrefix)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func textContent(node *html.Node) string {
|
||||
var builder strings.Builder
|
||||
var visit func(*html.Node)
|
||||
visit = func(n *html.Node) {
|
||||
switch {
|
||||
case n.Type == html.TextNode:
|
||||
builder.WriteString(n.Data)
|
||||
case n.Type == html.ElementNode && skippedElements[n.Data]:
|
||||
return
|
||||
case n.Type == html.ElementNode && n.Data == "br":
|
||||
builder.WriteString("\n")
|
||||
}
|
||||
for child := n.FirstChild; child != nil; child = child.NextSibling {
|
||||
visit(child)
|
||||
}
|
||||
}
|
||||
visit(node)
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
func attr(node *html.Node, name string) string {
|
||||
for _, a := range node.Attr {
|
||||
if a.Key == name {
|
||||
return a.Val
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func safeHref(href string) string {
|
||||
trimmed := strings.TrimSpace(href)
|
||||
parsed, err := url.Parse(trimmed)
|
||||
if err != nil || !allowedLinkSchemes[strings.ToLower(parsed.Scheme)] {
|
||||
return ""
|
||||
}
|
||||
return trimmed
|
||||
}
|
||||
|
||||
func withMark(marks []mark, added mark) []mark {
|
||||
for _, existing := range marks {
|
||||
if existing.kind == added.kind {
|
||||
return marks
|
||||
}
|
||||
}
|
||||
next := make([]mark, 0, len(marks)+1)
|
||||
next = append(next, marks...)
|
||||
return append(next, added)
|
||||
}
|
||||
|
||||
func hasVisibleText(inlines []inline) bool {
|
||||
for _, item := range inlines {
|
||||
if strings.TrimSpace(item.text) != "" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func sameMarks(a, b []mark) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for index := range a {
|
||||
if a[index] != b[index] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func appendInline(inlines []inline, next inline) []inline {
|
||||
if last := len(inlines) - 1; last >= 0 && sameMarks(inlines[last].marks, next.marks) {
|
||||
inlines[last].text += next.text
|
||||
return inlines
|
||||
}
|
||||
return append(inlines, next)
|
||||
}
|
||||
|
||||
func withoutCodeMarks(inlines []inline) []inline {
|
||||
merged := make([]inline, 0, len(inlines))
|
||||
for _, item := range inlines {
|
||||
kept := make([]mark, 0, len(item.marks))
|
||||
for _, m := range item.marks {
|
||||
if m.kind != markCode {
|
||||
kept = append(kept, m)
|
||||
}
|
||||
}
|
||||
merged = appendInline(merged, inline{text: item.text, marks: kept})
|
||||
}
|
||||
return merged
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package markdown
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/article"
|
||||
)
|
||||
|
||||
type Converter struct{}
|
||||
|
||||
var _ domain.BodyRenderer = &Converter{}
|
||||
|
||||
func NewConverter() *Converter {
|
||||
return &Converter{}
|
||||
}
|
||||
|
||||
func (c *Converter) Render(html string, format domain.BodyFormat) (string, error) {
|
||||
switch format {
|
||||
case domain.BodyFormatHTML:
|
||||
return html, nil
|
||||
case domain.BodyFormatMarkdown:
|
||||
blocks, err := parseBlocks(html)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return renderMarkdown(blocks), nil
|
||||
case domain.BodyFormatJSON:
|
||||
blocks, err := parseBlocks(html)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return renderJSON(blocks)
|
||||
}
|
||||
return "", domain.ErrUnsupportedBodyFormat
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package markdown
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type jsonMark struct {
|
||||
Type string `json:"type"`
|
||||
Href string `json:"href,omitempty"`
|
||||
}
|
||||
|
||||
type jsonText struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
Marks []jsonMark `json:"marks"`
|
||||
}
|
||||
|
||||
type jsonHeading struct {
|
||||
Type string `json:"type"`
|
||||
Level int `json:"level"`
|
||||
Align string `json:"align,omitempty"`
|
||||
Children []jsonText `json:"children"`
|
||||
}
|
||||
|
||||
type jsonParagraph struct {
|
||||
Type string `json:"type"`
|
||||
Align string `json:"align,omitempty"`
|
||||
Children []jsonText `json:"children"`
|
||||
}
|
||||
|
||||
type jsonList struct {
|
||||
Type string `json:"type"`
|
||||
Ordered bool `json:"ordered"`
|
||||
Items [][]any `json:"items"`
|
||||
}
|
||||
|
||||
type jsonBlockquote struct {
|
||||
Type string `json:"type"`
|
||||
Children []any `json:"children"`
|
||||
}
|
||||
|
||||
type jsonCode struct {
|
||||
Type string `json:"type"`
|
||||
Language string `json:"language"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
type jsonRule struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
type jsonImage struct {
|
||||
Type string `json:"type"`
|
||||
Src string `json:"src"`
|
||||
Alt string `json:"alt"`
|
||||
}
|
||||
|
||||
func renderJSON(blocks []block) (string, error) {
|
||||
var buffer bytes.Buffer
|
||||
encoder := json.NewEncoder(&buffer)
|
||||
encoder.SetEscapeHTML(false)
|
||||
if err := encoder.Encode(toJSONBlocks(blocks)); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSuffix(buffer.String(), "\n"), nil
|
||||
}
|
||||
|
||||
func toJSONBlocks(blocks []block) []any {
|
||||
result := make([]any, 0, len(blocks))
|
||||
for _, b := range blocks {
|
||||
result = append(result, toJSONBlock(b))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func toJSONBlock(b block) any {
|
||||
switch b.kind {
|
||||
case kindHeading:
|
||||
return jsonHeading{Type: "heading", Level: b.level, Align: b.align, Children: toJSONTexts(b.inlines)}
|
||||
case kindParagraph:
|
||||
return jsonParagraph{Type: "paragraph", Align: b.align, Children: toJSONTexts(b.inlines)}
|
||||
case kindList:
|
||||
items := make([][]any, 0, len(b.items))
|
||||
for _, item := range b.items {
|
||||
items = append(items, toJSONBlocks(item))
|
||||
}
|
||||
return jsonList{Type: "list", Ordered: b.ordered, Items: items}
|
||||
case kindBlockquote:
|
||||
return jsonBlockquote{Type: "blockquote", Children: toJSONBlocks(b.children)}
|
||||
case kindCode:
|
||||
return jsonCode{Type: "code", Language: b.language, Text: b.text}
|
||||
case kindImage:
|
||||
return jsonImage{Type: "image", Src: b.src, Alt: b.alt}
|
||||
}
|
||||
return jsonRule{Type: "hr"}
|
||||
}
|
||||
|
||||
func toJSONTexts(inlines []inline) []jsonText {
|
||||
plain := withoutCodeMarks(inlines)
|
||||
texts := make([]jsonText, 0, len(plain))
|
||||
for _, item := range plain {
|
||||
marks := make([]jsonMark, 0, len(item.marks))
|
||||
for _, m := range item.marks {
|
||||
marks = append(marks, jsonMark{Type: m.kind, Href: m.href})
|
||||
}
|
||||
texts = append(texts, jsonText{Type: "text", Text: item.text, Marks: marks})
|
||||
}
|
||||
return texts
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package markdown
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
blockSeparator = "\n\n"
|
||||
hardBreak = "\\\n"
|
||||
bulletMarker = "- "
|
||||
codeFence = "```"
|
||||
alignOpen = `<div style="text-align: `
|
||||
alignOpenEnd = `">`
|
||||
alignClose = "</div>"
|
||||
)
|
||||
|
||||
var textEscaper = strings.NewReplacer(
|
||||
"\\", "\\\\", "*", "\\*", "_", "\\_", "`", "\\`", "[", "\\[", "]", "\\]", "<", "\\<",
|
||||
)
|
||||
|
||||
var (
|
||||
numberedLineStart = regexp.MustCompile(`^(\d+)([.)])(\s|$)`)
|
||||
markerLineStart = regexp.MustCompile(`^(>|#{1,6}(\s|$)|[+-](\s|$|-)|=+\s*$)`)
|
||||
)
|
||||
|
||||
var hrefEscaper = strings.NewReplacer(" ", "%20", "(", "%28", ")", "%29", "<", "%3C", ">", "%3E")
|
||||
|
||||
func renderMarkdown(blocks []block) string {
|
||||
return renderBlocks(blocks, blockSeparator)
|
||||
}
|
||||
|
||||
func renderBlocks(blocks []block, separator string) string {
|
||||
parts := make([]string, 0, len(blocks))
|
||||
for _, b := range blocks {
|
||||
if rendered := renderBlock(b); rendered != "" {
|
||||
parts = append(parts, rendered)
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, separator)
|
||||
}
|
||||
|
||||
func renderBlock(b block) string {
|
||||
rendered := renderPlainBlock(b)
|
||||
if b.align == "" || rendered == "" {
|
||||
return rendered
|
||||
}
|
||||
return alignOpen + b.align + alignOpenEnd + blockSeparator + rendered + blockSeparator + alignClose
|
||||
}
|
||||
|
||||
func renderPlainBlock(b block) string {
|
||||
switch b.kind {
|
||||
case kindHeading:
|
||||
return strings.Repeat("#", b.level) + " " + renderInlines(b.inlines)
|
||||
case kindParagraph:
|
||||
return escapeLineStarts(renderInlines(b.inlines))
|
||||
case kindList:
|
||||
return renderList(b)
|
||||
case kindBlockquote:
|
||||
return prefixLines(renderBlocks(b.children, blockSeparator), "> ", ">")
|
||||
case kindCode:
|
||||
return renderCode(b)
|
||||
case kindImage:
|
||||
return " + ")"
|
||||
}
|
||||
return "---"
|
||||
}
|
||||
|
||||
func escapeLineStarts(text string) string {
|
||||
lines := strings.Split(text, "\n")
|
||||
for index, line := range lines {
|
||||
line = numberedLineStart.ReplaceAllString(line, `$1\$2$3`)
|
||||
if markerLineStart.MatchString(line) {
|
||||
line = `\` + line
|
||||
}
|
||||
lines[index] = line
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
func renderCode(b block) string {
|
||||
fence := codeFence
|
||||
for strings.Contains(b.text, fence) {
|
||||
fence += "`"
|
||||
}
|
||||
return fence + b.language + "\n" + b.text + "\n" + fence
|
||||
}
|
||||
|
||||
func escapeAlt(alt string) string {
|
||||
return strings.NewReplacer("[", "\\[", "]", "\\]", "\n", " ").Replace(alt)
|
||||
}
|
||||
|
||||
func renderList(b block) string {
|
||||
lines := make([]string, 0, len(b.items))
|
||||
for index, item := range b.items {
|
||||
marker := bulletMarker
|
||||
if b.ordered {
|
||||
marker = strconv.Itoa(index+1) + ". "
|
||||
}
|
||||
content := renderBlocks(item, itemSeparator(item))
|
||||
lines = append(lines, marker+indentContinuation(content, len(marker)))
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
func itemSeparator(item []block) string {
|
||||
textBlocks := 0
|
||||
for _, b := range item {
|
||||
if b.kind != kindList {
|
||||
textBlocks++
|
||||
}
|
||||
}
|
||||
if textBlocks > 1 {
|
||||
return blockSeparator
|
||||
}
|
||||
return "\n"
|
||||
}
|
||||
|
||||
func indentContinuation(content string, width int) string {
|
||||
indent := strings.Repeat(" ", width)
|
||||
lines := strings.Split(content, "\n")
|
||||
for index := 1; index < len(lines); index++ {
|
||||
if lines[index] != "" {
|
||||
lines[index] = indent + lines[index]
|
||||
}
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
func prefixLines(content, prefix, emptyPrefix string) string {
|
||||
lines := strings.Split(content, "\n")
|
||||
for index, line := range lines {
|
||||
if line == "" {
|
||||
lines[index] = emptyPrefix
|
||||
continue
|
||||
}
|
||||
lines[index] = prefix + line
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
func renderInlines(inlines []inline) string {
|
||||
var builder strings.Builder
|
||||
for _, item := range inlines {
|
||||
builder.WriteString(renderInline(item))
|
||||
}
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
func renderInline(item inline) string {
|
||||
isCode := hasMarkKind(item.marks, markCode)
|
||||
lines := strings.Split(item.text, "\n")
|
||||
for index, line := range lines {
|
||||
lines[index] = wrapMarks(item.marks, line, isCode)
|
||||
}
|
||||
return strings.Join(lines, hardBreak)
|
||||
}
|
||||
|
||||
func hasMarkKind(marks []mark, kind string) bool {
|
||||
for _, m := range marks {
|
||||
if m.kind == kind {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func wrapMarks(marks []mark, text string, isCode bool) string {
|
||||
core := strings.TrimSpace(text)
|
||||
if core == "" {
|
||||
return text
|
||||
}
|
||||
start := strings.Index(text, core)
|
||||
leading, trailing := text[:start], text[start+len(core):]
|
||||
var wrapped string
|
||||
if isCode {
|
||||
wrapped = inlineCode(core)
|
||||
} else {
|
||||
wrapped = escapeText(core)
|
||||
}
|
||||
for index := len(marks) - 1; index >= 0; index-- {
|
||||
wrapped = applyMark(marks[index], wrapped)
|
||||
}
|
||||
return leading + wrapped + trailing
|
||||
}
|
||||
|
||||
func inlineCode(text string) string {
|
||||
fence := "`"
|
||||
for strings.Contains(text, fence) {
|
||||
fence += "`"
|
||||
}
|
||||
if strings.HasPrefix(text, "`") || strings.HasSuffix(text, "`") {
|
||||
return fence + " " + text + " " + fence
|
||||
}
|
||||
return fence + text + fence
|
||||
}
|
||||
|
||||
func applyMark(m mark, text string) string {
|
||||
switch m.kind {
|
||||
case markBold:
|
||||
return "**" + text + "**"
|
||||
case markItalic:
|
||||
return "*" + text + "*"
|
||||
case markLink:
|
||||
return "[" + text + "](" + hrefEscaper.Replace(m.href) + ")"
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
func escapeText(text string) string {
|
||||
return textEscaper.Replace(text)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package mappers
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/apikey"
|
||||
"RenewCMS/internal/infrastructure/persistence/models"
|
||||
)
|
||||
|
||||
func APIKeyToDomain(m models.APIKey) apikey.APIKey {
|
||||
return apikey.APIKey{
|
||||
ID: m.ID,
|
||||
UserID: m.UserID,
|
||||
Name: m.Name,
|
||||
Prefix: m.Prefix,
|
||||
HashedKey: m.HashedKey,
|
||||
ExpiresAt: m.ExpiresAt,
|
||||
RevokedAt: m.RevokedAt,
|
||||
LastUsedAt: m.LastUsedAt,
|
||||
CreatedAt: m.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func APIKeyToModel(k apikey.APIKey) models.APIKey {
|
||||
return models.APIKey{
|
||||
ID: k.ID,
|
||||
UserID: k.UserID,
|
||||
Name: k.Name,
|
||||
Prefix: k.Prefix,
|
||||
HashedKey: k.HashedKey,
|
||||
ExpiresAt: k.ExpiresAt,
|
||||
RevokedAt: k.RevokedAt,
|
||||
LastUsedAt: k.LastUsedAt,
|
||||
CreatedAt: k.CreatedAt,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type APIKey struct {
|
||||
ID uint32 `gorm:"primaryKey;autoIncrement"`
|
||||
UserID uint32 `gorm:"index;not null"`
|
||||
Name string `gorm:"not null"`
|
||||
Prefix string `gorm:"not null"`
|
||||
HashedKey string `gorm:"uniqueIndex;not null"`
|
||||
ExpiresAt *time.Time
|
||||
RevokedAt *time.Time
|
||||
LastUsedAt *time.Time
|
||||
CreatedAt time.Time `gorm:"autoCreateTime"`
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package persistence
|
||||
|
||||
import (
|
||||
domainAPIKey "RenewCMS/internal/domain/apikey"
|
||||
"RenewCMS/internal/infrastructure/persistence/mappers"
|
||||
entity "RenewCMS/internal/infrastructure/persistence/models"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type APIKeyRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewAPIKeyRepository(db *gorm.DB) *APIKeyRepository {
|
||||
return &APIKeyRepository{db}
|
||||
}
|
||||
|
||||
func (a *APIKeyRepository) Create(key domainAPIKey.APIKey) (domainAPIKey.APIKey, error) {
|
||||
model := mappers.APIKeyToModel(key)
|
||||
model.ID = 0
|
||||
if err := a.db.Create(&model).Error; err != nil {
|
||||
return domainAPIKey.APIKey{}, err
|
||||
}
|
||||
return mappers.APIKeyToDomain(model), nil
|
||||
}
|
||||
|
||||
func (a *APIKeyRepository) Get(id uint32) (domainAPIKey.APIKey, error) {
|
||||
var model entity.APIKey
|
||||
if err := a.db.First(&model, id).Error; err != nil {
|
||||
return domainAPIKey.APIKey{}, mapNotFoundErr(err, domainAPIKey.ErrAPIKeyNotFound)
|
||||
}
|
||||
return mappers.APIKeyToDomain(model), nil
|
||||
}
|
||||
|
||||
func (a *APIKeyRepository) GetByHashedKey(hashedKey string) (domainAPIKey.APIKey, error) {
|
||||
var model entity.APIKey
|
||||
if err := a.db.Where("hashed_key = ?", hashedKey).First(&model).Error; err != nil {
|
||||
return domainAPIKey.APIKey{}, mapNotFoundErr(err, domainAPIKey.ErrAPIKeyNotFound)
|
||||
}
|
||||
return mappers.APIKeyToDomain(model), nil
|
||||
}
|
||||
|
||||
func (a *APIKeyRepository) ListByUser(userId uint32) ([]domainAPIKey.APIKey, error) {
|
||||
return a.list(a.db.Where("user_id = ?", userId))
|
||||
}
|
||||
|
||||
func (a *APIKeyRepository) ListAll() ([]domainAPIKey.APIKey, error) {
|
||||
return a.list(a.db)
|
||||
}
|
||||
|
||||
func (a *APIKeyRepository) list(query *gorm.DB) ([]domainAPIKey.APIKey, error) {
|
||||
var found []entity.APIKey
|
||||
if err := query.Order("created_at DESC, id DESC").Find(&found).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
keys := make([]domainAPIKey.APIKey, 0, len(found))
|
||||
for _, model := range found {
|
||||
keys = append(keys, mappers.APIKeyToDomain(model))
|
||||
}
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
func (a *APIKeyRepository) Revoke(id uint32, at time.Time) error {
|
||||
result := a.db.Model(&entity.APIKey{}).
|
||||
Where("id = ? AND revoked_at IS NULL", id).
|
||||
Update("revoked_at", at)
|
||||
return result.Error
|
||||
}
|
||||
|
||||
func (a *APIKeyRepository) RevokeAllByUser(userId uint32, at time.Time) error {
|
||||
return a.db.Model(&entity.APIKey{}).
|
||||
Where("user_id = ? AND revoked_at IS NULL", userId).
|
||||
Update("revoked_at", at).Error
|
||||
}
|
||||
|
||||
func (a *APIKeyRepository) TouchLastUsed(id uint32, at time.Time) error {
|
||||
return a.db.Model(&entity.APIKey{}).
|
||||
Where("id = ?", id).
|
||||
Update("last_used_at", at).Error
|
||||
}
|
||||
|
||||
var _ domainAPIKey.Repository = &APIKeyRepository{}
|
||||
@@ -0,0 +1,46 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
)
|
||||
|
||||
const readableFilePermissions = 0o644
|
||||
|
||||
func writeFileAtomically(path string, content []byte, permissions os.FileMode) error {
|
||||
temporary := path + ".tmp"
|
||||
if err := os.WriteFile(temporary, content, permissions); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(temporary, path); err != nil {
|
||||
_ = os.Remove(temporary)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeJSONAtomically(path string, value any, permissions os.FileMode) error {
|
||||
content, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return writeFileAtomically(path, content, permissions)
|
||||
}
|
||||
|
||||
func removeFile(path string) (bool, error) {
|
||||
err := os.Remove(path)
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
func removeIfPresent(path string) error {
|
||||
_, err := removeFile(path)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"crypto/ed25519"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
errSignatureEncoding = errors.New("the signature is not a base64 encoded ed25519 signature")
|
||||
errSignatureMismatch = errors.New("the signature does not match the checksums file")
|
||||
)
|
||||
|
||||
type Ed25519SignatureVerifier struct {
|
||||
key ed25519.PublicKey
|
||||
}
|
||||
|
||||
var _ domain.SignatureVerifier = &Ed25519SignatureVerifier{}
|
||||
|
||||
func NewEd25519SignatureVerifier(key ed25519.PublicKey) *Ed25519SignatureVerifier {
|
||||
return &Ed25519SignatureVerifier{key: key}
|
||||
}
|
||||
|
||||
func (v *Ed25519SignatureVerifier) Verify(checksumsPath string, signaturePath string) error {
|
||||
content, err := os.ReadFile(checksumsPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rawSignature, err := os.ReadFile(signaturePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
signature, err := base64.StdEncoding.DecodeString(strings.TrimSpace(string(rawSignature)))
|
||||
if err != nil || len(signature) != ed25519.SignatureSize {
|
||||
return errSignatureEncoding
|
||||
}
|
||||
if len(v.key) != ed25519.PublicKeySize || !ed25519.Verify(v.key, content, signature) {
|
||||
return errSignatureMismatch
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"context"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const stagedBinaryRunTimeout = 15 * time.Second
|
||||
|
||||
type ExecStagedBinaryRunner struct{}
|
||||
|
||||
var _ domain.StagedBinaryRunner = &ExecStagedBinaryRunner{}
|
||||
|
||||
func NewExecStagedBinaryRunner() *ExecStagedBinaryRunner {
|
||||
return &ExecStagedBinaryRunner{}
|
||||
}
|
||||
|
||||
func (r *ExecStagedBinaryRunner) Version(binaryPath string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), stagedBinaryRunTimeout)
|
||||
defer cancel()
|
||||
output, err := exec.CommandContext(ctx, binaryPath, "--version").Output()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(string(output)), nil
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"encoding/json"
|
||||
"os"
|
||||
)
|
||||
|
||||
type FileHelperDetector struct {
|
||||
statusPath string
|
||||
}
|
||||
|
||||
var _ domain.HelperDetector = &FileHelperDetector{}
|
||||
|
||||
func NewFileHelperDetector(statusPath string) *FileHelperDetector {
|
||||
return &FileHelperDetector{statusPath: statusPath}
|
||||
}
|
||||
|
||||
func (d *FileHelperDetector) Installed() bool {
|
||||
content, err := os.ReadFile(d.statusPath)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
var status map[string]any
|
||||
return json.Unmarshal(content, &status) == nil && status != nil
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
)
|
||||
|
||||
type FSRestartRequestStore struct {
|
||||
files domain.HelperFilesystem
|
||||
path string
|
||||
}
|
||||
|
||||
var _ domain.RestartRequestStore = &FSRestartRequestStore{}
|
||||
|
||||
func NewFSRestartRequestStore(files domain.HelperFilesystem, path string) *FSRestartRequestStore {
|
||||
return &FSRestartRequestStore{files: files, path: path}
|
||||
}
|
||||
|
||||
func (s *FSRestartRequestStore) Write(request domain.RestartRequest) error {
|
||||
return writeJSONThroughTemporary(s.files, s.path, request, statusFilePermissions)
|
||||
}
|
||||
|
||||
func (s *FSRestartRequestStore) Read() (domain.RestartRequest, error) {
|
||||
info, err := s.files.Lstat(s.path)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return domain.RestartRequest{}, domain.ErrNoRestartRequest
|
||||
}
|
||||
if err != nil {
|
||||
return domain.RestartRequest{}, err
|
||||
}
|
||||
if info.IsSymlink {
|
||||
return domain.RestartRequest{}, domain.SymlinkError{Path: s.path}
|
||||
}
|
||||
if !info.IsRegular {
|
||||
return domain.RestartRequest{}, fmt.Errorf("%s is not a regular file", s.path)
|
||||
}
|
||||
content, err := s.files.ReadFile(s.path)
|
||||
if err != nil {
|
||||
return domain.RestartRequest{}, err
|
||||
}
|
||||
var request domain.RestartRequest
|
||||
return request, json.Unmarshal(content, &request)
|
||||
}
|
||||
|
||||
func (s *FSRestartRequestStore) Delete() error {
|
||||
return removeThrough(s.files, s.path)
|
||||
}
|
||||
|
||||
func removeThrough(files domain.HelperFilesystem, path string) error {
|
||||
if err := files.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeJSONThroughTemporary(files domain.HelperFilesystem, path string, value any, mode uint32) error {
|
||||
content, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return writeThroughTemporary(files, path, content, mode)
|
||||
}
|
||||
|
||||
func writeThroughTemporary(files domain.HelperFilesystem, path string, content []byte, mode uint32) error {
|
||||
temporary := path + domain.ResultTempSuffix
|
||||
if _, err := files.Lstat(temporary); err == nil {
|
||||
if err := files.Remove(temporary); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := files.CreateExclusive(temporary, content, mode); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := files.Rename(temporary, path); err != nil {
|
||||
_ = files.Remove(temporary)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
)
|
||||
|
||||
type FSResultStore struct {
|
||||
files domain.HelperFilesystem
|
||||
path string
|
||||
}
|
||||
|
||||
var _ domain.ResultStore = &FSResultStore{}
|
||||
|
||||
func NewFSResultStore(files domain.HelperFilesystem, path string) *FSResultStore {
|
||||
return &FSResultStore{files: files, path: path}
|
||||
}
|
||||
|
||||
func (s *FSResultStore) Read() (domain.Result, bool) {
|
||||
info, err := s.files.Lstat(s.path)
|
||||
if err != nil || !info.IsRegular {
|
||||
return domain.Result{}, false
|
||||
}
|
||||
content, err := s.files.ReadFile(s.path)
|
||||
if err != nil {
|
||||
return domain.Result{}, false
|
||||
}
|
||||
return decodeResult(content)
|
||||
}
|
||||
|
||||
func (s *FSResultStore) Write(result domain.Result) error {
|
||||
return writeJSONThroughTemporary(s.files, s.path, result, readableFilePermissions)
|
||||
}
|
||||
|
||||
func (s *FSResultStore) Delete() error {
|
||||
return removeThrough(s.files, s.path)
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
releasesPath = "/api/v1/repos/fsylvain/RenewCMS/releases"
|
||||
feedRequestTimeout = 10 * time.Second
|
||||
maxFeedBodyBytes = 4 << 20
|
||||
)
|
||||
|
||||
type GiteaReleaseFeed struct {
|
||||
baseURL string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
var _ domain.ReleaseFeed = &GiteaReleaseFeed{}
|
||||
|
||||
type giteaRelease struct {
|
||||
TagName string `json:"tag_name"`
|
||||
HTMLURL string `json:"html_url"`
|
||||
Body string `json:"body"`
|
||||
Draft bool `json:"draft"`
|
||||
PublishedAt time.Time `json:"published_at"`
|
||||
Assets []giteaAsset `json:"assets"`
|
||||
}
|
||||
|
||||
type giteaAsset struct {
|
||||
Name string `json:"name"`
|
||||
Size int64 `json:"size"`
|
||||
DownloadURL string `json:"browser_download_url"`
|
||||
}
|
||||
|
||||
func NewGiteaReleaseFeed(baseURL string) *GiteaReleaseFeed {
|
||||
return &GiteaReleaseFeed{
|
||||
baseURL: strings.TrimRight(baseURL, "/"),
|
||||
client: &http.Client{Timeout: feedRequestTimeout},
|
||||
}
|
||||
}
|
||||
|
||||
func (g *GiteaReleaseFeed) Latest() (domain.Release, error) {
|
||||
releases, err := g.fetch()
|
||||
if err != nil {
|
||||
return domain.Release{}, err
|
||||
}
|
||||
return domain.Newest(releases)
|
||||
}
|
||||
|
||||
func (g *GiteaReleaseFeed) fetch() ([]domain.Release, error) {
|
||||
response, err := g.client.Get(g.baseURL + releasesPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", domain.ErrFeedUnavailable, err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("%w: status %d", domain.ErrFeedUnavailable, response.StatusCode)
|
||||
}
|
||||
var raw []giteaRelease
|
||||
if err := json.NewDecoder(io.LimitReader(response.Body, maxFeedBodyBytes)).Decode(&raw); err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", domain.ErrFeedUnavailable, err)
|
||||
}
|
||||
return toReleases(raw), nil
|
||||
}
|
||||
|
||||
func toReleases(raw []giteaRelease) []domain.Release {
|
||||
releases := make([]domain.Release, 0, len(raw))
|
||||
for _, item := range raw {
|
||||
if item.Draft {
|
||||
continue
|
||||
}
|
||||
releases = append(releases, domain.Release{
|
||||
Tag: item.TagName,
|
||||
URL: item.HTMLURL,
|
||||
PublishedAt: item.PublishedAt,
|
||||
Notes: domain.BuildNotes(item.TagName, item.PublishedAt, item.Body),
|
||||
Assets: toAssets(item.Assets),
|
||||
})
|
||||
}
|
||||
return releases
|
||||
}
|
||||
|
||||
func toAssets(raw []giteaAsset) []domain.Asset {
|
||||
assets := make([]domain.Asset, 0, len(raw))
|
||||
for _, item := range raw {
|
||||
assets = append(assets, domain.Asset{Name: item.Name, URL: item.DownloadURL, Size: item.Size})
|
||||
}
|
||||
return assets
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
maxBinaryBytes int64 = 200 << 20
|
||||
maxChecksumsBytes int64 = 64 << 10
|
||||
maxSignatureBytes int64 = 1 << 10
|
||||
assetDownloadTimeout = 10 * time.Minute
|
||||
maxAssetRedirects = 5
|
||||
assetFilePermission = 0o644
|
||||
signatureSuffix = ".sig"
|
||||
)
|
||||
|
||||
var (
|
||||
errAssetURLRefused = errors.New("the asset url is not https on the release feed host")
|
||||
errAssetStatus = errors.New("the asset server answered with an error status")
|
||||
errAssetTooLarge = errors.New("the asset is larger than its size cap")
|
||||
errTooManyRedirects = errors.New("the asset url redirected too many times")
|
||||
)
|
||||
|
||||
type FileOpener func(path string) (io.WriteCloser, error)
|
||||
|
||||
type HTTPAssetFetcher struct {
|
||||
allowedHost string
|
||||
allowInsecure bool
|
||||
sizeCap int64
|
||||
timeout time.Duration
|
||||
transport http.RoundTripper
|
||||
openFile FileOpener
|
||||
}
|
||||
|
||||
var _ domain.AssetFetcher = &HTTPAssetFetcher{}
|
||||
|
||||
type FetcherOption func(*HTTPAssetFetcher)
|
||||
|
||||
func WithInsecureScheme() FetcherOption {
|
||||
return func(f *HTTPAssetFetcher) { f.allowInsecure = true }
|
||||
}
|
||||
|
||||
func WithSizeCap(bytes int64) FetcherOption {
|
||||
return func(f *HTTPAssetFetcher) { f.sizeCap = bytes }
|
||||
}
|
||||
|
||||
func WithTimeout(timeout time.Duration) FetcherOption {
|
||||
return func(f *HTTPAssetFetcher) { f.timeout = timeout }
|
||||
}
|
||||
|
||||
func WithTransport(transport http.RoundTripper) FetcherOption {
|
||||
return func(f *HTTPAssetFetcher) { f.transport = transport }
|
||||
}
|
||||
|
||||
func WithFileOpener(opener FileOpener) FetcherOption {
|
||||
return func(f *HTTPAssetFetcher) { f.openFile = opener }
|
||||
}
|
||||
|
||||
func NewHTTPAssetFetcher(feedURL string, options ...FetcherOption) *HTTPAssetFetcher {
|
||||
fetcher := &HTTPAssetFetcher{
|
||||
allowedHost: domain.HostOf(feedURL),
|
||||
timeout: assetDownloadTimeout,
|
||||
openFile: createAssetFile,
|
||||
}
|
||||
for _, option := range options {
|
||||
option(fetcher)
|
||||
}
|
||||
return fetcher
|
||||
}
|
||||
|
||||
func (f *HTTPAssetFetcher) Fetch(asset domain.Asset, destination string, report domain.ProgressFunc) error {
|
||||
if !f.isAllowed(asset.URL) {
|
||||
return errAssetURLRefused
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), f.timeout)
|
||||
defer cancel()
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, asset.URL, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
response, err := f.client().Do(request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("%w: %d", errAssetStatus, response.StatusCode)
|
||||
}
|
||||
limit := f.capFor(asset.Name)
|
||||
if response.ContentLength > limit {
|
||||
return errAssetTooLarge
|
||||
}
|
||||
if err := f.writeBody(response.Body, destination, limit, asset.Size, report); err != nil {
|
||||
_ = os.Remove(destination)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *HTTPAssetFetcher) writeBody(body io.Reader, destination string, limit int64, declaredSize int64, report domain.ProgressFunc) error {
|
||||
file, err := f.openFile(destination)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
counter := &progressWriter{destination: file, total: declaredSize, report: report}
|
||||
written, copyErr := io.Copy(counter, io.LimitReader(body, limit+1))
|
||||
closeErr := file.Close()
|
||||
if copyErr != nil {
|
||||
return copyErr
|
||||
}
|
||||
if closeErr != nil {
|
||||
return closeErr
|
||||
}
|
||||
if written > limit {
|
||||
return errAssetTooLarge
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *HTTPAssetFetcher) isAllowed(rawURL string) bool {
|
||||
parsed, err := url.Parse(rawURL)
|
||||
if err != nil || f.allowedHost == "" || parsed.Host != f.allowedHost {
|
||||
return false
|
||||
}
|
||||
return parsed.Scheme == "https" || (f.allowInsecure && parsed.Scheme == "http")
|
||||
}
|
||||
|
||||
func (f *HTTPAssetFetcher) client() *http.Client {
|
||||
return &http.Client{
|
||||
Transport: f.transport,
|
||||
CheckRedirect: func(next *http.Request, via []*http.Request) error {
|
||||
if len(via) >= maxAssetRedirects {
|
||||
return errTooManyRedirects
|
||||
}
|
||||
if !f.isAllowed(next.URL.String()) {
|
||||
return errAssetURLRefused
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (f *HTTPAssetFetcher) capFor(name string) int64 {
|
||||
if f.sizeCap > 0 {
|
||||
return f.sizeCap
|
||||
}
|
||||
if name == domain.ChecksumsAssetName {
|
||||
return maxChecksumsBytes
|
||||
}
|
||||
if strings.HasSuffix(name, signatureSuffix) {
|
||||
return maxSignatureBytes
|
||||
}
|
||||
return maxBinaryBytes
|
||||
}
|
||||
|
||||
type progressWriter struct {
|
||||
destination io.Writer
|
||||
total int64
|
||||
done int64
|
||||
report domain.ProgressFunc
|
||||
}
|
||||
|
||||
func (w *progressWriter) Write(chunk []byte) (int, error) {
|
||||
written, err := w.destination.Write(chunk)
|
||||
w.done += int64(written)
|
||||
w.report(w.done, w.total)
|
||||
return written, err
|
||||
}
|
||||
|
||||
func createAssetFile(path string) (io.WriteCloser, error) {
|
||||
if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, assetFilePermission)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
const healthCheckTimeout = 2 * time.Second
|
||||
|
||||
type HTTPHealthChecker struct {
|
||||
url string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
var _ domain.HealthChecker = &HTTPHealthChecker{}
|
||||
|
||||
func NewHTTPHealthChecker(port string) *HTTPHealthChecker {
|
||||
return &HTTPHealthChecker{
|
||||
url: "http://127.0.0.1:" + port + "/healthz",
|
||||
client: &http.Client{Timeout: healthCheckTimeout},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *HTTPHealthChecker) Healthy() bool {
|
||||
response, err := c.client.Get(c.url)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer response.Body.Close()
|
||||
return response.StatusCode == http.StatusOK
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
type JSONHelperStatusWriter struct{}
|
||||
|
||||
var _ domain.HelperStatusWriter = &JSONHelperStatusWriter{}
|
||||
|
||||
func NewJSONHelperStatusWriter() *JSONHelperStatusWriter {
|
||||
return &JSONHelperStatusWriter{}
|
||||
}
|
||||
|
||||
func (w *JSONHelperStatusWriter) Write(dataDir string, status domain.HelperStatus) error {
|
||||
return writeJSONAtomically(filepath.Join(dataDir, domain.HelperStatusFileName), status, readableFilePermissions)
|
||||
}
|
||||
|
||||
func (w *JSONHelperStatusWriter) Remove(dataDir string) (bool, error) {
|
||||
return removeFile(filepath.Join(dataDir, domain.HelperStatusFileName))
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type JSONJobStore struct {
|
||||
path string
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
var _ domain.JobStore = &JSONJobStore{}
|
||||
|
||||
func NewJSONJobStore(path string) *JSONJobStore {
|
||||
store := &JSONJobStore{path: path}
|
||||
store.failInterruptedJob()
|
||||
return store
|
||||
}
|
||||
|
||||
func (s *JSONJobStore) failInterruptedJob() {
|
||||
job, found := s.read()
|
||||
if !found || !job.IsRunning() {
|
||||
return
|
||||
}
|
||||
job.State = domain.StateFailed
|
||||
job.Error = domain.ErrorKindDownload
|
||||
job.DownloadedBytes = 0
|
||||
job.TotalBytes = 0
|
||||
_ = s.write(job)
|
||||
}
|
||||
|
||||
func (s *JSONJobStore) Load() (domain.Job, bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
job, found := s.read()
|
||||
if !found {
|
||||
return domain.Job{}, false
|
||||
}
|
||||
if job.State == domain.StateReady && !fileExists(job.StagedBinary) {
|
||||
return domain.Job{}, false
|
||||
}
|
||||
return job, true
|
||||
}
|
||||
|
||||
func (s *JSONJobStore) Save(job domain.Job) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
return s.write(job)
|
||||
}
|
||||
|
||||
func (s *JSONJobStore) read() (domain.Job, bool) {
|
||||
content, err := os.ReadFile(s.path)
|
||||
if err != nil {
|
||||
return domain.Job{}, false
|
||||
}
|
||||
var job domain.Job
|
||||
if err := json.Unmarshal(content, &job); err != nil || job.State == "" {
|
||||
return domain.Job{}, false
|
||||
}
|
||||
return job, true
|
||||
}
|
||||
|
||||
func (s *JSONJobStore) write(job domain.Job) error {
|
||||
content, err := json.Marshal(job)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(s.path), os.ModePerm); err != nil {
|
||||
return err
|
||||
}
|
||||
temporary := s.path + ".tmp"
|
||||
if err := os.WriteFile(temporary, content, statusFilePermissions); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(temporary, s.path)
|
||||
}
|
||||
|
||||
func fileExists(path string) bool {
|
||||
if path == "" {
|
||||
return false
|
||||
}
|
||||
info, err := os.Stat(path)
|
||||
return err == nil && !info.IsDir()
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type JSONRestartRequestStore struct {
|
||||
path string
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
var _ domain.RestartRequestStore = &JSONRestartRequestStore{}
|
||||
|
||||
func NewJSONRestartRequestStore(path string) *JSONRestartRequestStore {
|
||||
return &JSONRestartRequestStore{path: path}
|
||||
}
|
||||
|
||||
func (s *JSONRestartRequestStore) Write(request domain.RestartRequest) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
return writeJSONAtomically(s.path, request, statusFilePermissions)
|
||||
}
|
||||
|
||||
func (s *JSONRestartRequestStore) Read() (domain.RestartRequest, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
info, err := os.Lstat(s.path)
|
||||
if errors.Is(err, fs.ErrNotExist) || (err == nil && info.IsDir()) {
|
||||
return domain.RestartRequest{}, domain.ErrNoRestartRequest
|
||||
}
|
||||
if err != nil {
|
||||
return domain.RestartRequest{}, err
|
||||
}
|
||||
content, err := os.ReadFile(s.path)
|
||||
if err != nil {
|
||||
return domain.RestartRequest{}, err
|
||||
}
|
||||
var request domain.RestartRequest
|
||||
return request, json.Unmarshal(content, &request)
|
||||
}
|
||||
|
||||
func (s *JSONRestartRequestStore) Delete() error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
return removeIfPresent(s.path)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type JSONResultStore struct {
|
||||
path string
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
var _ domain.ResultStore = &JSONResultStore{}
|
||||
|
||||
func NewJSONResultStore(path string) *JSONResultStore {
|
||||
return &JSONResultStore{path: path}
|
||||
}
|
||||
|
||||
func (s *JSONResultStore) Read() (domain.Result, bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
content, err := os.ReadFile(s.path)
|
||||
if err != nil {
|
||||
return domain.Result{}, false
|
||||
}
|
||||
return decodeResult(content)
|
||||
}
|
||||
|
||||
func (s *JSONResultStore) Write(result domain.Result) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
return writeJSONAtomically(s.path, result, readableFilePermissions)
|
||||
}
|
||||
|
||||
func (s *JSONResultStore) Delete() error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
return removeIfPresent(s.path)
|
||||
}
|
||||
|
||||
func decodeResult(content []byte) (domain.Result, bool) {
|
||||
var result domain.Result
|
||||
if err := json.Unmarshal(content, &result); err != nil || !result.IsKnown() {
|
||||
return domain.Result{}, false
|
||||
}
|
||||
return result, true
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type JSONRunningInfoStore struct {
|
||||
path string
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
var _ domain.RunningInfoStore = &JSONRunningInfoStore{}
|
||||
|
||||
func NewJSONRunningInfoStore(path string) *JSONRunningInfoStore {
|
||||
return &JSONRunningInfoStore{path: path}
|
||||
}
|
||||
|
||||
func (s *JSONRunningInfoStore) Write(info domain.RunningInfo) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
return writeJSONAtomically(s.path, info, readableFilePermissions)
|
||||
}
|
||||
|
||||
func (s *JSONRunningInfoStore) Read() (domain.RunningInfo, bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
linkInfo, err := os.Lstat(s.path)
|
||||
if err != nil || !linkInfo.Mode().IsRegular() {
|
||||
return domain.RunningInfo{}, false
|
||||
}
|
||||
content, err := os.ReadFile(s.path)
|
||||
if err != nil {
|
||||
return domain.RunningInfo{}, false
|
||||
}
|
||||
var info domain.RunningInfo
|
||||
if err := json.Unmarshal(content, &info); err != nil || info.Version == "" || info.Pid == 0 {
|
||||
return domain.RunningInfo{}, false
|
||||
}
|
||||
return info, true
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
)
|
||||
|
||||
const statusFilePermissions = 0o600
|
||||
|
||||
type JSONStatusStore struct {
|
||||
path string
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
var _ domain.StatusStore = &JSONStatusStore{}
|
||||
|
||||
func NewJSONStatusStore(path string) *JSONStatusStore {
|
||||
return &JSONStatusStore{path: path}
|
||||
}
|
||||
|
||||
func (s *JSONStatusStore) Load() (domain.CheckResult, bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
content, err := os.ReadFile(s.path)
|
||||
if err != nil {
|
||||
return domain.CheckResult{}, false
|
||||
}
|
||||
var result domain.CheckResult
|
||||
if err := json.Unmarshal(content, &result); err != nil || result.CheckedAt.IsZero() {
|
||||
return domain.CheckResult{}, false
|
||||
}
|
||||
return result, true
|
||||
}
|
||||
|
||||
func (s *JSONStatusStore) Save(result domain.CheckResult) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
content, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(s.path), os.ModePerm); err != nil {
|
||||
return err
|
||||
}
|
||||
temporary := s.path + ".tmp"
|
||||
if err := os.WriteFile(temporary, content, statusFilePermissions); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(temporary, s.path)
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
//go:build linux
|
||||
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"errors"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
const (
|
||||
privateTempDirPrefix = "renewcms-update-"
|
||||
readNoFollowFlags = os.O_RDONLY | syscall.O_NOFOLLOW | syscall.O_NONBLOCK
|
||||
createNoFollowFlags = os.O_WRONLY | os.O_CREATE | os.O_EXCL | syscall.O_NOFOLLOW
|
||||
directoryFlags = os.O_RDONLY | syscall.O_NOFOLLOW | syscall.O_DIRECTORY
|
||||
)
|
||||
|
||||
var errNotRegularFile = errors.New("not a regular file")
|
||||
|
||||
type NoFollowFilesystem struct{}
|
||||
|
||||
var _ domain.HelperFilesystem = &NoFollowFilesystem{}
|
||||
|
||||
func NewNoFollowFilesystem() *NoFollowFilesystem {
|
||||
return &NoFollowFilesystem{}
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) Lstat(path string) (domain.FileInfo, error) {
|
||||
info, err := os.Lstat(path)
|
||||
if err != nil {
|
||||
return domain.FileInfo{}, err
|
||||
}
|
||||
mode := info.Mode()
|
||||
return domain.FileInfo{
|
||||
IsSymlink: mode&fs.ModeSymlink != 0,
|
||||
IsDir: mode.IsDir(),
|
||||
IsRegular: mode.IsRegular(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) ReadFile(path string) ([]byte, error) {
|
||||
file, err := openRegularNoFollow(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close()
|
||||
return io.ReadAll(file)
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) CreateExclusive(path string, content []byte, mode uint32) error {
|
||||
file, err := os.OpenFile(path, createNoFollowFlags, fs.FileMode(mode))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := file.Write(content); err != nil {
|
||||
file.Close()
|
||||
return err
|
||||
}
|
||||
return finishWrite(file, mode)
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) Copy(source string, destination string, mode uint32) error {
|
||||
input, err := openRegularNoFollow(source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer input.Close()
|
||||
output, err := os.OpenFile(destination, createNoFollowFlags, fs.FileMode(mode))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := io.Copy(output, input); err != nil {
|
||||
output.Close()
|
||||
return err
|
||||
}
|
||||
return finishWrite(output, mode)
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) Rename(oldPath string, newPath string) error {
|
||||
return os.Rename(oldPath, newPath)
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) Remove(path string) error {
|
||||
return os.Remove(path)
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) RemoveAll(path string) error {
|
||||
info, err := os.Lstat(path)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return os.Remove(path)
|
||||
}
|
||||
names, err := readDirectoryNames(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, name := range names {
|
||||
if err := f.RemoveAll(filepath.Join(path, name)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return os.Remove(path)
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) Chmod(path string, mode uint32) error {
|
||||
file, err := os.OpenFile(path, readNoFollowFlags, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
return file.Chmod(fs.FileMode(mode))
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) MakePrivateTempDir() (string, error) {
|
||||
return os.MkdirTemp("", privateTempDirPrefix)
|
||||
}
|
||||
|
||||
func openRegularNoFollow(path string) (*os.File, error) {
|
||||
file, err := os.OpenFile(path, readNoFollowFlags, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
file.Close()
|
||||
return nil, err
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
file.Close()
|
||||
return nil, errNotRegularFile
|
||||
}
|
||||
return file, nil
|
||||
}
|
||||
|
||||
func finishWrite(file *os.File, mode uint32) error {
|
||||
if err := file.Chmod(fs.FileMode(mode)); err != nil {
|
||||
file.Close()
|
||||
return err
|
||||
}
|
||||
if err := file.Sync(); err != nil {
|
||||
file.Close()
|
||||
return err
|
||||
}
|
||||
return file.Close()
|
||||
}
|
||||
|
||||
func readDirectoryNames(path string) ([]string, error) {
|
||||
directory, err := os.OpenFile(path, directoryFlags, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer directory.Close()
|
||||
return directory.Readdirnames(-1)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
//go:build !linux
|
||||
|
||||
package update
|
||||
|
||||
import domain "RenewCMS/internal/domain/update"
|
||||
|
||||
type NoFollowFilesystem struct{}
|
||||
|
||||
var _ domain.HelperFilesystem = &NoFollowFilesystem{}
|
||||
|
||||
func NewNoFollowFilesystem() *NoFollowFilesystem {
|
||||
return &NoFollowFilesystem{}
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) Lstat(string) (domain.FileInfo, error) {
|
||||
return domain.FileInfo{}, domain.ErrHelperUnsupported
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) ReadFile(string) ([]byte, error) {
|
||||
return nil, domain.ErrHelperUnsupported
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) CreateExclusive(string, []byte, uint32) error {
|
||||
return domain.ErrHelperUnsupported
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) Copy(string, string, uint32) error {
|
||||
return domain.ErrHelperUnsupported
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) Rename(string, string) error {
|
||||
return domain.ErrHelperUnsupported
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) Remove(string) error {
|
||||
return domain.ErrHelperUnsupported
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) RemoveAll(string) error {
|
||||
return domain.ErrHelperUnsupported
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) Chmod(string, uint32) error {
|
||||
return domain.ErrHelperUnsupported
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) MakePrivateTempDir() (string, error) {
|
||||
return "", domain.ErrHelperUnsupported
|
||||
}
|
||||
Loaded 100 of 316 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user