From a020b1c53ec48cf0ef768fcc88cead880793c7af Mon Sep 17 00:00:00 2001 From: Henrique Fagundes Date: Thu, 26 Nov 2026 19:59:09 -0300 Subject: [PATCH 1/3] =?UTF-8?q?cr=C3=A9ditos=20configur=C3=A1veis,=20temas?= =?UTF-8?q?=20s=C3=B3=20por=20pacote=20com=20modo=20claro=20e=20escuro,=20?= =?UTF-8?q?foto=20do=20usu=C3=A1rio?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- go.mod | 1 + go.sum | 2 + internal/db/migrations/007_avatar.sql | 5 + internal/httpapi/avatarimg.go | 49 ++++++++ internal/httpapi/handlers_avatar.go | 75 +++++++++++++ internal/httpapi/handlers_brand.go | 155 ++++++++++++++++++++------ internal/httpapi/httpapi.go | 3 + internal/httpapi/httpapi_test.go | 10 +- internal/httpapi/themes_test.go | 132 +++++++++++++++++++++- internal/notify/collect.go | 8 +- internal/report/data.go | 21 +++- internal/report/html.go | 16 ++- internal/report/pdf.go | 2 +- internal/report/report_test.go | 16 +++ internal/report/text.go | 8 +- internal/store/store.go | 25 ++++- internal/themepkg/dark.go | 102 +++++++++++++++++ internal/themepkg/themepkg.go | 18 ++- internal/themepkg/themepkg_test.go | 21 ++++ 19 files changed, 609 insertions(+), 60 deletions(-) create mode 100644 internal/db/migrations/007_avatar.sql create mode 100644 internal/httpapi/avatarimg.go create mode 100644 internal/httpapi/handlers_avatar.go create mode 100644 internal/themepkg/dark.go diff --git a/go.mod b/go.mod index 8e4ea7d..9e9e5b2 100644 --- a/go.mod +++ b/go.mod @@ -10,6 +10,7 @@ require ( github.com/pkg/sftp v1.13.13 github.com/robfig/cron/v3 v3.0.1 golang.org/x/crypto v0.59.0 + golang.org/x/image v0.48.0 google.golang.org/grpc v1.85.0 google.golang.org/protobuf v1.36.12 ) diff --git a/go.sum b/go.sum index fd5be7d..9dbbd9c 100644 --- a/go.sum +++ b/go.sum @@ -61,6 +61,8 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= +golang.org/x/image v0.48.0 h1:1AvuPcuoOTJpA7s4VZ5umrb90T3So0rkB/bSGmxkxik= +golang.org/x/image v0.48.0/go.mod h1:mmtg64iqJKGqEgy+r13dfybl85tmxUd2lMnmaiSdWYY= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= diff --git a/internal/db/migrations/007_avatar.sql b/internal/db/migrations/007_avatar.sql new file mode 100644 index 0000000..abd7291 --- /dev/null +++ b/internal/db/migrations/007_avatar.sql @@ -0,0 +1,5 @@ +-- Coruja Backup · migração 007: foto (avatar) de cada usuário +ALTER TABLE users + ADD COLUMN avatar MEDIUMBLOB NULL, + ADD COLUMN avatar_type VARCHAR(40) NOT NULL DEFAULT '', + ADD COLUMN avatar_version VARCHAR(16) NOT NULL DEFAULT ''; diff --git a/internal/httpapi/avatarimg.go b/internal/httpapi/avatarimg.go new file mode 100644 index 0000000..0f31648 --- /dev/null +++ b/internal/httpapi/avatarimg.go @@ -0,0 +1,49 @@ +package httpapi + +import ( + "bytes" + "errors" + "image" + "image/color" + stddraw "image/draw" + _ "image/gif" // decodificadores registrados para image.Decode + "image/jpeg" + _ "image/png" + + "golang.org/x/image/draw" + _ "golang.org/x/image/webp" +) + +const ( + avatarSide = 256 // lado da foto guardada (px) + maxAvatarPixels = 50 << 20 // recusa imagens gigantes antes de decodificar (bomba de descompressão) +) + +// normalizeAvatar decodifica a foto enviada, recorta o quadrado central, reduz para 256×256 e devolve um JPEG leve. +// Transparência vira fundo branco. Metadados (EXIF, localização) não passam para a imagem final. +func normalizeAvatar(b []byte) ([]byte, error) { + cfg, _, err := image.DecodeConfig(bytes.NewReader(b)) + if err != nil { + return nil, errors.New("não foi possível ler a imagem (use PNG, JPEG, GIF ou WebP)") + } + if cfg.Width < 16 || cfg.Height < 16 || cfg.Width*cfg.Height > maxAvatarPixels { + return nil, errors.New("a imagem deve ter entre 16 px e cerca de 50 megapixels") + } + src, _, err := image.Decode(bytes.NewReader(b)) + if err != nil { + return nil, errors.New("não foi possível ler a imagem (use PNG, JPEG, GIF ou WebP)") + } + r := src.Bounds() + side := min(r.Dx(), r.Dy()) + crop := image.Rect(r.Min.X+(r.Dx()-side)/2, r.Min.Y+(r.Dy()-side)/2, 0, 0) + crop.Max = crop.Min.Add(image.Pt(side, side)) + out := min(avatarSide, side) + dst := image.NewRGBA(image.Rect(0, 0, out, out)) + stddraw.Draw(dst, dst.Bounds(), image.NewUniform(color.White), image.Point{}, stddraw.Src) + draw.CatmullRom.Scale(dst, dst.Bounds(), src, crop, draw.Over, nil) + var buf bytes.Buffer + if err := jpeg.Encode(&buf, dst, &jpeg.Options{Quality: 86}); err != nil { + return nil, err + } + return buf.Bytes(), nil +} diff --git a/internal/httpapi/handlers_avatar.go b/internal/httpapi/handlers_avatar.go new file mode 100644 index 0000000..fb3d125 --- /dev/null +++ b/internal/httpapi/handlers_avatar.go @@ -0,0 +1,75 @@ +package httpapi + +// Foto (avatar) do usuário: cada um troca a sua; qualquer usuário autenticado pode ver (aparece no menu e em Usuários). + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "io" + "net/http" + + "github.com/AprendendoLinux/corujabackup/internal/store" + "github.com/AprendendoLinux/corujabackup/internal/themepkg" +) + +const maxAvatarBytes = 2 << 20 // a foto enviada; a guardada é reduzida para 256×256 em JPEG + +func (s *Server) uploadAvatar(w http.ResponseWriter, r *http.Request, cu *ctxUser) { + r.Body = http.MaxBytesReader(w, r.Body, maxAvatarBytes+1024) + b, err := io.ReadAll(r.Body) + if err != nil || len(b) == 0 || len(b) > maxAvatarBytes { + writeErr(w, 400, "a foto deve ter até 2 MB") + return + } + if typ, ok := themepkg.SniffImage(b); !ok || typ == "image/svg+xml" { // só imagens raster: SVG não é aceito como foto + writeErr(w, 400, "use uma imagem PNG, JPEG, GIF ou WebP") + return + } + b, err = normalizeAvatar(b) + if err != nil { + writeErr(w, 400, err.Error()) + return + } + typ := "image/jpeg" + sum := sha256.Sum256(b) + ver := hex.EncodeToString(sum[:6]) + if err := s.Store.SetAvatar(r.Context(), cu.User.ID, b, typ, ver); err != nil { + writeErr(w, 500, "erro interno") + return + } + s.Store.Audit(r.Context(), cu.User.ID, cu.User.Username, "user.avatar_set", typ, s.clientIP(r)) + writeJSON(w, 200, map[string]string{"avatar_version": ver}) +} + +func (s *Server) deleteAvatar(w http.ResponseWriter, r *http.Request, cu *ctxUser) { + if err := s.Store.SetAvatar(r.Context(), cu.User.ID, nil, "", ""); err != nil { + writeErr(w, 500, "erro interno") + return + } + s.Store.Audit(r.Context(), cu.User.ID, cu.User.Username, "user.avatar_removed", "", s.clientIP(r)) + writeJSON(w, 200, map[string]bool{"ok": true}) +} + +func (s *Server) avatar(w http.ResponseWriter, r *http.Request, _ *ctxUser) { + id, ok := pathID(r) + if !ok { + writeErr(w, 400, "id inválido") + return + } + b, typ, err := s.Store.Avatar(r.Context(), id) + if errors.Is(err, store.ErrNotFound) { + writeErr(w, 404, "sem foto") + return + } + if err != nil { + writeErr(w, 500, "erro interno") + return + } + h := w.Header() + h.Set("Content-Type", typ) + h.Set("Cache-Control", "private, max-age=3600") // o endereço muda com a versão da foto + h.Set("Content-Security-Policy", "default-src 'none'; sandbox") + h.Set("X-Content-Type-Options", "nosniff") + _, _ = w.Write(b) +} diff --git a/internal/httpapi/handlers_brand.go b/internal/httpapi/handlers_brand.go index ed5be6f..4bb665f 100644 --- a/internal/httpapi/handlers_brand.go +++ b/internal/httpapi/handlers_brand.go @@ -7,9 +7,11 @@ import ( "encoding/json" "io" "net/http" + "net/url" "regexp" "strings" + "github.com/AprendendoLinux/corujabackup/internal/report" "github.com/AprendendoLinux/corujabackup/internal/themepkg" "github.com/AprendendoLinux/corujabackup/internal/version" ) @@ -20,7 +22,9 @@ const ( ) var ( - builtinThemes = map[string]bool{"coruja": true, "noturno": true, "floresta": true} + // Temas embutidos (cada um com modo claro e escuro). "noturno" é o antigo tema escuro da Coruja: vira coruja + modo escuro. + builtinThemes = map[string]bool{"coruja": true, "floresta": true} + themeModes = map[string]bool{"auto": true, "light": true, "dark": true} themeIDRE = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{1,29}$`) colorRE = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`) themeKeys = []string{"bg", "surface", "text", "muted", "border", "primary", "primary_contrast", "accent", "ok", "danger"} @@ -38,10 +42,21 @@ type themeMeta struct { } type customTheme struct { - ID string `json:"id"` - Label string `json:"label"` - Vars map[string]string `json:"vars"` - Pkg *themeMeta `json:"pkg,omitempty"` + ID string `json:"id"` + Label string `json:"label"` + Vars map[string]string `json:"vars"` + VarsDark map[string]string `json:"vars_dark,omitempty"` + Pkg *themeMeta `json:"pkg,omitempty"` +} + +// withDark garante o modo escuro (temas importados antes dele existir ganham um gerado a partir das cores claras). +func withDark(list []customTheme) []customTheme { + for i := range list { + if len(list[i].VarsDark) == 0 && len(list[i].Vars) > 0 { + list[i].VarsDark = themepkg.DeriveDark(list[i].Vars) + } + } + return list } func assetKey(id, kind string) string { return "brand.asset." + id + "." + kind } @@ -130,7 +145,11 @@ func (s *Server) importTheme(w http.ResponseWriter, r *http.Request, cu *ctxUser return } meta.LogoUI, meta.LogoDoc = pk.LogoUIType, pk.LogoDocType - t := customTheme{ID: pk.ID, Label: pk.Name, Vars: pk.Colors, Pkg: meta} + dark := pk.ColorsDark + if dark == nil { + dark = themepkg.DeriveDark(pk.Colors) + } + t := customTheme{ID: pk.ID, Label: pk.Name, Vars: pk.Colors, VarsDark: dark, Pkg: meta} if idx >= 0 { list[idx] = t } else { @@ -145,12 +164,12 @@ func (s *Server) importTheme(w http.ResponseWriter, r *http.Request, cu *ctxUser writeJSON(w, 200, map[string]any{"ok": true, "theme": t, "replaced": idx >= 0}) } -func (s *Server) loadBrand(r *http.Request) (name, theme string, themes []customTheme, logoType, logoHash string) { - name, theme, themes = version.Name, "coruja", []customTheme{} +func (s *Server) loadBrand(r *http.Request) (name, theme, mode string, themes []customTheme, logoType, logoHash string) { + name, theme, mode, themes = version.Name, "coruja", "auto", []customTheme{} if s.Store == nil { return } - m, err := s.Store.GetSettings(r.Context(), "brand.name", "brand.theme", "brand.themes", "brand.logo_type", "brand.logo") + m, err := s.Store.GetSettings(r.Context(), "brand.name", "brand.theme", "brand.mode", "brand.themes", "brand.logo_type", "brand.logo") if err != nil { return } @@ -160,9 +179,19 @@ func (s *Server) loadBrand(r *http.Request) (name, theme string, themes []custom if v := m["brand.theme"]; v != "" { theme = v } + if themeModes[m["brand.mode"]] { + mode = m["brand.mode"] + } + if theme == "noturno" { + theme = "coruja" + if m["brand.mode"] == "" { + mode = "dark" + } + } if v := m["brand.themes"]; v != "" { _ = json.Unmarshal([]byte(v), &themes) } + themes = withDark(themes) if lg := m["brand.logo"]; lg != "" { h := sha256.Sum256([]byte(lg)) logoType, logoHash = m["brand.logo_type"], hex.EncodeToString(h[:6]) @@ -170,10 +199,50 @@ func (s *Server) loadBrand(r *http.Request) (name, theme string, themes []custom return } +// credit são os créditos do rodapé (interface, e-mails e PDF). Name vazio = sem créditos; URL vazia = sem link. +type credit struct { + Label string `json:"label"` + Name string `json:"name"` + URL string `json:"url"` +} + +func defaultCredit() credit { + return credit{Label: report.DefaultCreditLabel, Name: report.DefaultCreditName, URL: report.DefaultCreditURL} +} + +func (s *Server) loadCredit(r *http.Request) credit { + c := defaultCredit() + if s.Store == nil { + return c + } + if m, err := s.Store.GetSettings(r.Context(), "brand.credit"); err == nil && m["brand.credit"] != "" { + _ = json.Unmarshal([]byte(m["brand.credit"]), &c) + } + return c +} + +// cleanCredit valida os créditos; devolve a mensagem de erro ou "". +func cleanCredit(c *credit) string { + c.Label, c.Name, c.URL = strings.TrimSpace(c.Label), strings.TrimSpace(c.Name), strings.TrimSpace(c.URL) + if len([]rune(c.Label)) > 40 || len([]rune(c.Name)) > 80 || strings.ContainsAny(c.Label+c.Name+c.URL, "\x00\r\n<>") { + return "créditos inválidos: rótulo até 40 caracteres e nome até 80, sem < e >" + } + if c.URL != "" { + u, err := url.Parse(c.URL) + if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" || len(c.URL) > 200 || strings.ContainsAny(c.URL, "\"' ") { + return "o link dos créditos deve começar com https:// ou http://" + } + } + if c.Name == "" { + c.URL = "" + } + return "" +} + // branding é público (a tela de login precisa do nome, tema e logo antes de autenticar). func (s *Server) branding(w http.ResponseWriter, r *http.Request) { - name, theme, themes, lt, lh := s.loadBrand(r) - out := map[string]any{"name": name, "theme": theme, "themes": themes, "has_logo": lt != ""} + name, theme, mode, themes, lt, lh := s.loadBrand(r) + out := map[string]any{"name": name, "theme": theme, "mode": mode, "themes": themes, "has_logo": lt != "", "credit": s.loadCredit(r)} if lt != "" { out["logo_version"] = lh } @@ -204,6 +273,8 @@ func (s *Server) saveBranding(w http.ResponseWriter, r *http.Request, cu *ctxUse Name string `json:"name"` Theme string `json:"theme"` Themes []customTheme `json:"themes"` + Credit *credit `json:"credit"` + Mode string `json:"mode"` } if !decode(w, r, &in) { return @@ -213,40 +284,52 @@ func (s *Server) saveBranding(w http.ResponseWriter, r *http.Request, cu *ctxUse writeErr(w, 400, "o nome deve ter de 1 a 60 caracteres") return } + cred := s.loadCredit(r) + if in.Credit != nil { + cred = *in.Credit + } + if msg := cleanCredit(&cred); msg != "" { + writeErr(w, 400, msg) + return + } + cj, _ := json.Marshal(cred) if len(in.Themes) > maxThemes { writeErr(w, 400, "no máximo 10 temas personalizados") return } - seen := map[string]bool{} - custom := map[string]bool{} + // Temas só entram por pacote (.zip): aqui o cliente apenas mantém ou exclui os já instalados. Cores, nomes e metadados + // vêm sempre do que está guardado, nunca do cliente. + storedList := s.storedThemes(r) + byID := map[string]customTheme{} stored := map[string]*themeMeta{} - for _, t := range s.storedThemes(r) { + for _, t := range storedList { + byID[t.ID] = t stored[t.ID] = t.Pkg } - for i := range in.Themes { - t := &in.Themes[i] - t.Pkg = stored[t.ID] // metadados e logos de pacote só mudam por importação - t.Label = strings.TrimSpace(t.Label) - if !themeIDRE.MatchString(t.ID) || builtinThemes[t.ID] || seen[t.ID] { - writeErr(w, 400, "identificador de tema inválido ou repetido: "+t.ID) - return - } - seen[t.ID] = true - custom[t.ID] = true - if t.Label == "" || len([]rune(t.Label)) > 40 { - writeErr(w, 400, "o nome do tema deve ter de 1 a 40 caracteres") + custom := map[string]bool{} + kept := make([]customTheme, 0, len(in.Themes)) + for _, t := range in.Themes { + st, ok := byID[t.ID] + if !ok { + writeErr(w, 400, "tema inexistente: "+t.ID+" (temas novos entram importando um pacote .zip)") return } - clean := map[string]string{} - for _, k := range themeKeys { - v := t.Vars[k] - if !colorRE.MatchString(v) { - writeErr(w, 400, "cor inválida em "+t.Label+" ("+k+"): use o formato #RRGGBB") - return - } - clean[k] = strings.ToLower(v) + if custom[t.ID] { + continue } - t.Vars = clean + custom[t.ID] = true + kept = append(kept, st) + } + in.Themes = kept + if in.Mode == "" { + _, _, in.Mode, _, _, _ = s.loadBrand(r) + } + if !themeModes[in.Mode] { + writeErr(w, 400, "modo inválido (auto, light ou dark)") + return + } + if in.Theme == "noturno" { + in.Theme, in.Mode = "coruja", "dark" } if in.Theme == "" { in.Theme = "coruja" @@ -261,7 +344,7 @@ func (s *Server) saveBranding(w http.ResponseWriter, r *http.Request, cu *ctxUse } } tj, _ := json.Marshal(in.Themes) - for k, v := range map[string]string{"brand.name": in.Name, "brand.theme": in.Theme, "brand.themes": string(tj)} { + for k, v := range map[string]string{"brand.name": in.Name, "brand.theme": in.Theme, "brand.themes": string(tj), "brand.credit": string(cj), "brand.mode": in.Mode} { if err := s.Store.SetSetting(r.Context(), k, v); err != nil { writeErr(w, 500, "erro interno") return diff --git a/internal/httpapi/httpapi.go b/internal/httpapi/httpapi.go index bbb8eaa..3e48a1d 100644 --- a/internal/httpapi/httpapi.go +++ b/internal/httpapi/httpapi.go @@ -108,6 +108,9 @@ func (s *Server) Routes() http.Handler { // autenticadas mux.HandleFunc("GET /api/me", s.authed(roleAny, s.me)) mux.HandleFunc("POST /api/me/password", s.authed(roleAny, s.changePassword)) + mux.HandleFunc("POST /api/me/avatar", s.authed(roleAny, s.uploadAvatar)) + mux.HandleFunc("DELETE /api/me/avatar", s.authed(roleAny, s.deleteAvatar)) + mux.HandleFunc("GET /api/users/{id}/avatar", s.authed(roleAny, s.avatar)) mux.HandleFunc("POST /api/me/2fa/begin", s.authed(roleAny, s.twoFABegin)) mux.HandleFunc("POST /api/me/2fa/enable", s.authed(roleAny, s.twoFAEnable)) mux.HandleFunc("POST /api/me/2fa/disable", s.authed(roleAny, s.twoFADisable)) diff --git a/internal/httpapi/httpapi_test.go b/internal/httpapi/httpapi_test.go index dcc7222..4219d6b 100644 --- a/internal/httpapi/httpapi_test.go +++ b/internal/httpapi/httpapi_test.go @@ -913,12 +913,12 @@ func TestIdentidadeVisualTemasELogo(t *testing.T) { code, _ := adm.do("PUT", "/api/branding", map[string]any{"name": "Backup Acme", "theme": theme, "themes": themes}) return code } + // temas só entram por pacote: qualquer tema que o cliente tente criar é recusado for name, c := range map[string]int{ - "cor inválida": save([]any{tema("acme", func(m map[string]string) { m["primary"] = "azul" })}, "coruja"), + "tema criado na tela": save([]any{tema("acme", nil)}, "coruja"), "id de tema embutido": save([]any{tema("coruja", nil)}, "coruja"), - "id repetido": save([]any{tema("acme", nil), tema("acme", nil)}, "coruja"), "id inválido": save([]any{tema("A cme!", nil)}, "coruja"), - "tema padrão inexiste": save([]any{tema("acme", nil)}, "outro"), + "tema padrão inexiste": save([]any{}, "outro"), } { if c != 400 { t.Errorf("%s: esperava 400, veio %d", name, c) @@ -927,11 +927,11 @@ func TestIdentidadeVisualTemasELogo(t *testing.T) { if code, _ := adm.do("PUT", "/api/branding", map[string]any{"name": "", "theme": "coruja", "themes": []any{}}); code != 400 { t.Fatalf("nome vazio: %d", code) } - if save([]any{tema("acme", nil)}, "acme") != 200 { + if save([]any{}, "floresta") != 200 { t.Fatal("configuração válida recusada") } _, m := pub.do("GET", "/api/branding", nil) - if m["name"] != "Backup Acme" || m["theme"] != "acme" || len(m["themes"].([]any)) != 1 { + if m["name"] != "Backup Acme" || m["theme"] != "floresta" || len(m["themes"].([]any)) != 0 { t.Fatalf("branding: %v", m) } // somente administrador altera diff --git a/internal/httpapi/themes_test.go b/internal/httpapi/themes_test.go index 89dd27a..35846f1 100644 --- a/internal/httpapi/themes_test.go +++ b/internal/httpapi/themes_test.go @@ -6,6 +6,10 @@ import ( "context" "encoding/base64" "encoding/json" + "image" + "image/jpeg" + "image/png" + "math/rand/v2" "testing" "github.com/AprendendoLinux/corujabackup/internal/notify" @@ -73,15 +77,33 @@ func TestPacoteDeTemaImportaAplicaEPreserva(t *testing.T) { if c, _, _ := pub.raw("GET", "/api/branding/themes/acme/logo", nil, ""); c != 200 { t.Fatalf("logo perdido ao salvar: %d", c) } - // O cliente não pode forjar metadados de pacote em tema comum. - forjado := []map[string]any{{"id": "meu", "label": "Meu", "vars": ths[0].(map[string]any)["vars"], "pkg": map[string]any{"logo_doc": "image/png", "doc": map[string]string{"primary": "#ff0000"}}}} - adm.mustOK("PUT", "/api/branding", map[string]any{"name": "Acme", "theme": "coruja", "themes": forjado}) + // Temas só entram por pacote: o cliente não cria tema nem altera cores, nome ou metadados de um instalado. + forjado := []map[string]any{{"id": "meu", "label": "Meu", "vars": ths[0].(map[string]any)["vars"]}} + if code, _ := adm.do("PUT", "/api/branding", map[string]any{"name": "Acme", "theme": "coruja", "themes": forjado}); code != 400 { + t.Fatalf("tema criado pelo cliente deveria ser recusado: %d", code) + } + alterado := []map[string]any{{"id": "acme", "label": "Outro nome", "vars": map[string]string{"primary": "#ff0000"}, "pkg": map[string]any{"doc": map[string]string{"primary": "#ff0000"}}}} + adm.mustOK("PUT", "/api/branding", map[string]any{"name": "Acme", "theme": "acme", "themes": alterado, "mode": "dark"}) + _, m2 := pub.do("GET", "/api/branding", nil) + t0 := m2["themes"].([]any)[0].(map[string]any) + if t0["label"] == "Outro nome" || t0["vars"].(map[string]any)["primary"] == "#ff0000" || t0["pkg"].(map[string]any)["doc"] != nil && t0["pkg"].(map[string]any)["doc"].(map[string]any)["primary"] == "#ff0000" { + t.Fatalf("o cliente alterou o tema instalado: %v", t0) + } + if m2["mode"] != "dark" || t0["vars_dark"] == nil { + t.Fatalf("modo escuro: %v %v", m2["mode"], t0["vars_dark"]) + } + if code, _ := adm.do("PUT", "/api/branding", map[string]any{"name": "Acme", "theme": "acme", "themes": alterado, "mode": "roxo"}); code != 400 { + t.Fatal("modo inválido deveria ser recusado") + } + // excluir o tema apaga o logo do pacote + adm.mustOK("PUT", "/api/branding", map[string]any{"name": "Acme", "theme": "coruja", "themes": []any{}}) if c, _, _ := pub.raw("GET", "/api/branding/themes/acme/logo", nil, ""); c != 404 { t.Fatalf("logo do tema removido deveria sumir: %d", c) } - _, m2 := pub.do("GET", "/api/branding", nil) - if p := m2["themes"].([]any)[0].(map[string]any)["pkg"]; p != nil { - t.Fatalf("pkg forjado foi aceito: %v", p) + // o antigo tema "noturno" vira Coruja no modo escuro + adm.mustOK("PUT", "/api/branding", map[string]any{"name": "Acme", "theme": "noturno", "themes": []any{}, "mode": "light"}) + if _, m2 = pub.do("GET", "/api/branding", nil); m2["theme"] != "coruja" || m2["mode"] != "dark" { + t.Fatalf("noturno: %v %v", m2["theme"], m2["mode"]) } // E-mail/PDF: cores do documento e logo do pacote. @@ -104,3 +126,101 @@ func TestPacoteDeTemaImportaAplicaEPreserva(t *testing.T) { t.Fatalf("deveria atualizar: %s", b2) } } + +func TestCreditosDoRodapeConfiguraveis(t *testing.T) { + e := newEnv(t) + adm := setupAdmin(e) + pub := e.client() + _, m := pub.do("GET", "/api/branding", nil) + c := m["credit"].(map[string]any) + if c["label"] != "Desenvolvido por" || c["name"] != "Henrique Fagundes" || c["url"] != "https://henrique.tec.br" { + t.Fatalf("padrão: %v", c) + } + adm.mustOK("PUT", "/api/branding", map[string]any{"name": "Acme", "theme": "coruja", "themes": []any{}, + "credit": map[string]string{"label": " Feito por ", "name": "TI da Acme", "url": "https://acme.example/ti"}}) + _, m = pub.do("GET", "/api/branding", nil) + if c = m["credit"].(map[string]any); c["label"] != "Feito por" || c["name"] != "TI da Acme" || c["url"] != "https://acme.example/ti" { + t.Fatalf("salvo: %v", c) + } + // sem o campo, os créditos são mantidos + adm.mustOK("PUT", "/api/branding", map[string]any{"name": "Acme 2", "theme": "coruja", "themes": []any{}}) + if _, m = pub.do("GET", "/api/branding", nil); m["credit"].(map[string]any)["name"] != "TI da Acme" { + t.Fatalf("perdeu os créditos: %v", m["credit"]) + } + for _, bad := range []map[string]string{{"name": "x", "url": "javascript:alert(1)"}, {"name": "x"}, {"name": "x", "url": "https://a.b/\"onmouseover"}, {"name": "x", "url": "ftp://a.b"}} { + if code, _ := adm.do("PUT", "/api/branding", map[string]any{"name": "Acme", "theme": "coruja", "themes": []any{}, "credit": bad}); code != 400 { + t.Errorf("%v deveria ser recusado: %d", bad, code) + } + } + // nome vazio desliga os créditos (e o link) + adm.mustOK("PUT", "/api/branding", map[string]any{"name": "Acme", "theme": "coruja", "themes": []any{}, "credit": map[string]string{"label": "x", "name": "", "url": "https://a.b"}}) + if _, m = pub.do("GET", "/api/branding", nil); m["credit"].(map[string]any)["url"] != "" { + t.Fatalf("%v", m["credit"]) + } +} + +func TestAvatarDoUsuario(t *testing.T) { + e := newEnv(t) + adm := setupAdmin(e) + me := adm.mustOK("GET", "/api/me", nil)["user"].(map[string]any) + id := itoa(int(me["id"].(float64))) + if me["avatar_version"] != "" { + t.Fatalf("sem foto no início: %v", me) + } + if c, _, _ := adm.raw("GET", "/api/users/"+id+"/avatar", nil, ""); c != 404 { + t.Fatalf("sem foto: %d", c) + } + for name, body := range map[string][]byte{ + "svg": []byte(``), + "html": []byte(""), + "gigante": append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte{1}, 2<<20+10)...), + "corrompida": append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte{1}, 900<<10)...), + } { + if c, _, _ := adm.raw("POST", "/api/me/avatar", body, "image/png"); c != 400 { + t.Errorf("%s: esperava 400, veio %d", name, c) + } + } + // uma foto grande (1,6 MB, retangular) é aceita, recortada no centro e reduzida para um JPEG de 256×256 + big := image.NewRGBA(image.Rect(0, 0, 720, 560)) + rnd := rand.New(rand.NewPCG(1, 2)) + for i := range big.Pix { + big.Pix[i] = byte(rnd.IntN(256)) + } + var pngBuf bytes.Buffer + if err := png.Encode(&pngBuf, big); err != nil { + t.Fatal(err) + } + if pngBuf.Len() < 1<<20 || pngBuf.Len() > 2<<20 { + t.Fatalf("a imagem de teste deveria ter entre 1 e 2 MB: %d", pngBuf.Len()) + } + if c, b, _ := adm.raw("POST", "/api/me/avatar", pngBuf.Bytes(), "image/png"); c != 200 { + t.Fatalf("envio: %d %s", c, b) + } + ver := adm.mustOK("GET", "/api/me", nil)["user"].(map[string]any)["avatar_version"] + if ver == "" { + t.Fatal("versão da foto não mudou") + } + // outro usuário autenticado vê; quem não entrou, não + adm.mustOK("POST", "/api/users", map[string]string{"username": "leitor9", "password": pw, "role": "viewer"}) + v := e.client() + v.mustOK("POST", "/api/login", map[string]string{"username": "leitor9", "password": pw}) + c, b, h := v.raw("GET", "/api/users/"+id+"/avatar", nil, "") + if c != 200 || h.Get("Content-Type") != "image/jpeg" || h.Get("X-Content-Type-Options") != "nosniff" || len(b) > 200<<10 { + t.Fatalf("ver a foto: %d %s %d bytes", c, h.Get("Content-Type"), len(b)) + } + if cfg, err := jpeg.DecodeConfig(bytes.NewReader(b)); err != nil || cfg.Width != 256 || cfg.Height != 256 { + t.Fatalf("a foto guardada deveria ser 256×256: %v %+v", err, cfg) + } + if c, _, _ := e.client().raw("GET", "/api/users/"+id+"/avatar", nil, ""); c != 401 { + t.Fatalf("sem login: %d", c) + } + // cada um só troca a própria foto: o leitor envia e não altera a do administrador + v.raw("POST", "/api/me/avatar", pngBuf.Bytes(), "image/png") + adm.mustOK("DELETE", "/api/me/avatar", nil) + if c, _, _ := v.raw("GET", "/api/users/"+id+"/avatar", nil, ""); c != 404 { + t.Fatalf("foto removida: %d", c) + } + if u := v.mustOK("GET", "/api/me", nil)["user"].(map[string]any); u["avatar_version"] == "" { + t.Fatal("a foto do leitor deveria continuar") + } +} diff --git a/internal/notify/collect.go b/internal/notify/collect.go index 5f6a925..cf23fee 100644 --- a/internal/notify/collect.go +++ b/internal/notify/collect.go @@ -26,7 +26,7 @@ var builtinColors = map[string]map[string]string{ func LoadBrand(ctx context.Context, st *store.Store) report.Brand { b := report.DefaultBrand() b.Version = version.Version - m, err := st.GetSettings(ctx, "brand.name", "brand.theme", "brand.themes", "brand.logo", "brand.logo_type", "app.base_url") + m, err := st.GetSettings(ctx, "brand.name", "brand.theme", "brand.themes", "brand.logo", "brand.logo_type", "app.base_url", "brand.credit") themeLogo := "" if err != nil { return b @@ -34,6 +34,12 @@ func LoadBrand(ctx context.Context, st *store.Store) report.Brand { if v := m["brand.name"]; v != "" { b.Name = v } + if v := m["brand.credit"]; v != "" { + var c struct{ Label, Name, URL string } + if json.Unmarshal([]byte(v), &c) == nil { + b.CreditLabel, b.CreditName, b.CreditURL = c.Label, c.Name, c.URL + } + } vars := builtinColors["coruja"] theme := m["brand.theme"] if c, ok := builtinColors[theme]; ok { diff --git a/internal/report/data.go b/internal/report/data.go index 7b11ead..b6e709c 100644 --- a/internal/report/data.go +++ b/internal/report/data.go @@ -22,12 +22,31 @@ type Brand struct { LogoMIME string Version string BaseURL string // endereço público do sistema (para links); vazio = sem links + // Créditos do rodapé (configuráveis em Aparência). CreditName vazio = sem créditos; CreditURL vazio = sem link. + CreditLabel string + CreditName string + CreditURL string +} + +// Credit devolve " - " (texto puro) ou "" quando os créditos estão desligados. +func (b Brand) Credit() string { + if b.CreditName == "" { + return "" + } + return " - " + strings.TrimSpace(b.CreditLabel+" "+b.CreditName) } func DefaultBrand() Brand { - return Brand{Name: "Coruja Backup", Primary: "#3b2a6b", Accent: "#f5a524", Bg: "#f6f5fb", Text: "#1e1b2e", Muted: "#6b6784", Border: "#e3e0f0", Ok: "#1f9d55", Danger: "#d64545", Version: "0.0.8"} + return Brand{Name: "Coruja Backup", Primary: "#3b2a6b", Accent: "#f5a524", Bg: "#f6f5fb", Text: "#1e1b2e", Muted: "#6b6784", Border: "#e3e0f0", Ok: "#1f9d55", Danger: "#d64545", Version: "0.0.8", + CreditLabel: DefaultCreditLabel, CreditName: DefaultCreditName, CreditURL: DefaultCreditURL} } +const ( + DefaultCreditLabel = "Desenvolvido por" + DefaultCreditName = "Henrique Fagundes" + DefaultCreditURL = "https://henrique.tec.br" +) + type RunRow struct { ID int64 Job string diff --git a/internal/report/html.go b/internal/report/html.go index c7240c0..e03e478 100644 --- a/internal/report/html.go +++ b/internal/report/html.go @@ -29,8 +29,8 @@ func shell(b Brand, title, banner, bannerColor, body string, hasLogo bool) strin fmt.Fprintf(&sb, `
%s
`, bannerColor, esc(banner)) } fmt.Fprintf(&sb, `%s`, body) - fmt.Fprintf(&sb, `%s - Versão %s - Desenvolvido por Henrique Fagundes`, - b.Bg, b.Border, b.Muted, esc(b.Name), esc(b.Version), b.Primary) + fmt.Fprintf(&sb, `%s - Versão %s%s`, + b.Bg, b.Border, b.Muted, esc(b.Name), esc(b.Version), creditHTML(b)) sb.WriteString(``) return sb.String() } @@ -201,3 +201,15 @@ func (e AgentEvent) HTML() string { kv(b, "Agente", ""+esc(e.Agent.Name)+""), kv(b, "Visto por último", esc(fmtTime(e.Agent.LastSeen, loc))), kv(b, "Versão do agente", esc(e.Agent.Version)), b.Muted, e.Minutes) return shell(b, e.Subject(), "Agente offline", b.Danger, body, len(b.LogoPNG) > 0) } + +// creditHTML monta os créditos do rodapé do e-mail (com link, se houver). +func creditHTML(b Brand) string { + if b.CreditName == "" { + return "" + } + name := esc(b.CreditName) + if b.CreditURL != "" { + name = fmt.Sprintf(`%s`, esc(b.CreditURL), b.Primary, name) + } + return " - " + strings.TrimSpace(esc(b.CreditLabel)+" "+name) +} diff --git a/internal/report/pdf.go b/internal/report/pdf.go index e037e95..ebc09e4 100644 --- a/internal/report/pdf.go +++ b/internal/report/pdf.go @@ -89,7 +89,7 @@ func (d *doc) footer() { mr, mg, mb := rgb(d.b.Muted) p.SetTextColor(mr, mg, mb) p.SetFont("Helvetica", "", 8) - p.CellFormat(150, 5, d.tr(fmt.Sprintf("%s - Versão %s - Desenvolvido por Henrique Fagundes", d.b.Name, d.b.Version)), "", 0, "L", false, 0, "") + p.CellFormat(150, 5, d.tr(fmt.Sprintf("%s - Versão %s%s", d.b.Name, d.b.Version, d.b.Credit())), "", 0, "L", false, 0, "") p.CellFormat(30, 5, d.tr(fmt.Sprintf("Página %d/{nb}", p.PageNo())), "", 0, "R", false, 0, "") } diff --git a/internal/report/report_test.go b/internal/report/report_test.go index 3f973c2..af0e1d2 100644 --- a/internal/report/report_test.go +++ b/internal/report/report_test.go @@ -136,3 +136,19 @@ func TestFormatacao(t *testing.T) { t.Fatal(fmtDur(&a, &b)) } } + +func TestCreditosConfiguraveisNosRelatorios(t *testing.T) { + b := DefaultBrand() + b.CreditLabel, b.CreditName, b.CreditURL = "Feito por", "TI ", "https://acme.example" + ev := RunEvent{Brand: b, Run: sample().Runs[2]} + if h := ev.HTML(); !strings.Contains(h, `Feito por ") || strings.Contains(txt, "Henrique") { + t.Fatalf("%s", txt) + } + b.CreditName = "" + if h := (RunEvent{Brand: b, Run: sample().Runs[2]}).HTML(); strings.Contains(h, "Feito por") || strings.Contains(h, "acme.example") { + t.Fatal("créditos desligados ainda aparecem") + } +} diff --git a/internal/report/text.go b/internal/report/text.go index 03b2224..09eafbc 100644 --- a/internal/report/text.go +++ b/internal/report/text.go @@ -31,7 +31,11 @@ func (d Daily) Text() string { } fmt.Fprintf(&sb, " - %s (%s): %s%s\n", j.Name, j.Agent, st, size) } - fmt.Fprintf(&sb, "\n%s - Versão %s - Desenvolvido por Henrique Fagundes (https://henrique.tec.br)\n", d.Name, d.Version) + credit := d.Brand.Credit() + if credit != "" && d.Brand.CreditURL != "" { + credit += " (" + d.Brand.CreditURL + ")" + } + fmt.Fprintf(&sb, "\n%s - Versão %s%s\n", d.Name, d.Version, credit) return sb.String() } @@ -126,7 +130,7 @@ func (e RunEvent) Text() string { if r.Error != "" { s += "\n" + r.Error + "\n" } - return s + fmt.Sprintf("\n%s - Versão %s - Desenvolvido por Henrique Fagundes\n", e.Name, e.Version) + return s + fmt.Sprintf("\n%s - Versão %s%s\n", e.Name, e.Version, e.Brand.Credit()) } func (e AgentEvent) Telegram() string { diff --git a/internal/store/store.go b/internal/store/store.go index 71ac107..db0ebe6 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -37,15 +37,16 @@ type User struct { Disabled bool `json:"disabled"` CreatedAt time.Time `json:"created_at"` LastLoginAt *time.Time `json:"last_login_at"` + AvatarVersion string `json:"avatar_version"` // vazio = sem foto } -const userCols = "id, username, display_name, password_hash, role, COALESCE(totp_secret,''), totp_enabled, totp_last_counter, COALESCE(recovery_codes,''), disabled, created_at, last_login_at" +const userCols = "id, username, display_name, password_hash, role, COALESCE(totp_secret,''), totp_enabled, totp_last_counter, COALESCE(recovery_codes,''), disabled, created_at, last_login_at, avatar_version" func scanUser(r interface{ Scan(...any) error }) (*User, error) { var u User var ll sql.NullTime if err := r.Scan(&u.ID, &u.Username, &u.DisplayName, &u.PasswordHash, &u.Role, &u.TOTPSecret, &u.TOTPEnabled, - &u.TOTPLastCounter, &u.RecoveryCodes, &u.Disabled, &u.CreatedAt, &ll); err != nil { + &u.TOTPLastCounter, &u.RecoveryCodes, &u.Disabled, &u.CreatedAt, &ll, &u.AvatarVersion); err != nil { if errors.Is(err, sql.ErrNoRows) { return nil, ErrNotFound } @@ -340,3 +341,23 @@ func (s *Store) SealedSamples(ctx context.Context) []string { } return out } + +// SetAvatar grava a foto do usuário (nil apaga). +func (s *Store) SetAvatar(ctx context.Context, id int64, data []byte, typ, ver string) error { + if data == nil { + typ, ver = "", "" + } + _, err := s.DB.ExecContext(ctx, "UPDATE users SET avatar=?, avatar_type=?, avatar_version=? WHERE id=?", data, typ, ver, id) + return err +} + +// Avatar devolve a foto do usuário; ErrNotFound se ele não tiver uma. +func (s *Store) Avatar(ctx context.Context, id int64) ([]byte, string, error) { + var b []byte + var typ string + err := s.DB.QueryRowContext(ctx, "SELECT avatar, avatar_type FROM users WHERE id=?", id).Scan(&b, &typ) + if errors.Is(err, sql.ErrNoRows) || (err == nil && len(b) == 0) { + return nil, "", ErrNotFound + } + return b, typ, err +} diff --git a/internal/themepkg/dark.go b/internal/themepkg/dark.go new file mode 100644 index 0000000..6b07b30 --- /dev/null +++ b/internal/themepkg/dark.go @@ -0,0 +1,102 @@ +package themepkg + +import ( + "fmt" + "math" + "strconv" +) + +// DeriveDark gera um modo escuro legível a partir das cores claras de um tema: fundos escuros levemente tingidos pela cor +// principal, texto claro e as cores de destaque clareadas para manter o contraste. Usado quando o pacote não traz +// "colors_dark". +func DeriveDark(light map[string]string) map[string]string { + h, s, _ := toHSL(light["primary"]) + tint := func(l float64) string { return fromHSL(h, math.Min(s, 0.25), l) } + brighten := func(c string, min float64) string { + ch, cs, cl := toHSL(c) + return fromHSL(ch, cs, math.Max(cl, min)) + } + primary := brighten(light["primary"], 0.62) + contrast := "#ffffff" + if luminance(primary) > 0.45 { + contrast = tint(0.08) + } + return map[string]string{ + "bg": tint(0.08), "surface": tint(0.12), "text": "#e9ebf1", "muted": "#a0a6b5", "border": tint(0.22), + "primary": primary, "primary_contrast": contrast, "accent": brighten(light["accent"], 0.6), + "ok": brighten(light["ok"], 0.55), "danger": brighten(light["danger"], 0.62), + } +} + +func rgbOf(c string) (r, g, b float64) { + if len(c) != 7 { + return 0.5, 0.5, 0.5 + } + v, err := strconv.ParseUint(c[1:], 16, 32) + if err != nil { + return 0.5, 0.5, 0.5 + } + return float64(v>>16&255) / 255, float64(v>>8&255) / 255, float64(v&255) / 255 +} + +func luminance(c string) float64 { + r, g, b := rgbOf(c) + lin := func(x float64) float64 { + if x <= 0.03928 { + return x / 12.92 + } + return math.Pow((x+0.055)/1.055, 2.4) + } + return 0.2126*lin(r) + 0.7152*lin(g) + 0.0722*lin(b) +} + +func toHSL(c string) (h, s, l float64) { + r, g, b := rgbOf(c) + mx, mn := math.Max(r, math.Max(g, b)), math.Min(r, math.Min(g, b)) + l = (mx + mn) / 2 + if mx == mn { + return 0, 0, l + } + d := mx - mn + if l > 0.5 { + s = d / (2 - mx - mn) + } else { + s = d / (mx + mn) + } + switch mx { + case r: + h = math.Mod((g-b)/d+6, 6) + case g: + h = (b-r)/d + 2 + default: + h = (r-g)/d + 4 + } + return h / 6, s, l +} + +func fromHSL(h, s, l float64) string { + hue := func(p, q, t float64) float64 { + t = math.Mod(t+1, 1) + switch { + case t < 1.0/6: + return p + (q-p)*6*t + case t < 0.5: + return q + case t < 2.0/3: + return p + (q-p)*(2.0/3-t)*6 + } + return p + } + var r, g, b float64 + if s == 0 { + r, g, b = l, l, l + } else { + q := l * (1 + s) + if l >= 0.5 { + q = l + s - l*s + } + p := 2*l - q + r, g, b = hue(p, q, h+1.0/3), hue(p, q, h), hue(p, q, h-1.0/3) + } + return fmt.Sprintf("#%02x%02x%02x", int(math.Round(r*255)), int(math.Round(g*255)), int(math.Round(b*255))) +} diff --git a/internal/themepkg/themepkg.go b/internal/themepkg/themepkg.go index c4b90be..34ecdea 100644 --- a/internal/themepkg/themepkg.go +++ b/internal/themepkg/themepkg.go @@ -50,9 +50,11 @@ type Manifest struct { Author string `json:"author,omitempty"` Description string `json:"description,omitempty"` Colors map[string]string `json:"colors"` - Document map[string]string `json:"document,omitempty"` - Logo Logo `json:"logo,omitempty"` - Preview string `json:"preview,omitempty"` + // ColorsDark é o modo escuro (as mesmas 10 cores). Opcional: sem ele, o modo escuro é gerado a partir de "colors". + ColorsDark map[string]string `json:"colors_dark,omitempty"` + Document map[string]string `json:"document,omitempty"` + Logo Logo `json:"logo,omitempty"` + Preview string `json:"preview,omitempty"` } // Package é um pacote já validado, com os arquivos carregados. @@ -174,7 +176,7 @@ func Read(data []byte) (*Package, error) { return nil, errors.New("theme.json: \"id\" deve ter 2 a 30 caracteres: letras minúsculas, números e hífen") } switch m.ID { - case "coruja", "noturno", "floresta": + case "coruja", "noturno", "floresta", "floresta-escuro": return nil, errors.New("theme.json: esse \"id\" é de um tema embutido") } m.Name = strings.TrimSpace(m.Name) @@ -193,6 +195,14 @@ func Read(data []byte) (*Package, error) { if err := validColors(m.Document, DocKeys, false, "document"); err != nil { return nil, err } + if m.ColorsDark != nil { + if err := validColors(m.ColorsDark, UIKeys, true, "colors_dark"); err != nil { + return nil, err + } + for k, v := range m.ColorsDark { + m.ColorsDark[k] = strings.ToLower(v) + } + } for k, v := range m.Colors { m.Colors[k] = strings.ToLower(v) } diff --git a/internal/themepkg/themepkg_test.go b/internal/themepkg/themepkg_test.go index 9365807..374ed63 100644 --- a/internal/themepkg/themepkg_test.go +++ b/internal/themepkg/themepkg_test.go @@ -88,3 +88,24 @@ func TestPacotesDoRepositorio(t *testing.T) { } } } + +func TestModoEscuroGeradoELegivel(t *testing.T) { + light := map[string]string{"bg": "#f5f6f8", "surface": "#ffffff", "text": "#262a33", "muted": "#5f6673", "border": "#dfe3ea", + "primary": "#aa3335", "primary_contrast": "#ffffff", "accent": "#be904e", "ok": "#1f7a4d", "danger": "#c2410c"} + d := DeriveDark(light) + for _, k := range UIKeys { + if !colorRE.MatchString(d[k]) { + t.Fatalf("%s: %q", k, d[k]) + } + } + ratio := func(a, b string) float64 { + la, lb := luminance(a)+0.05, luminance(b)+0.05 + if la < lb { + la, lb = lb, la + } + return la / lb + } + if luminance(d["bg"]) > 0.05 || ratio(d["text"], d["bg"]) < 7 || ratio(d["primary"], d["bg"]) < 3 || ratio(d["primary_contrast"], d["primary"]) < 3 { + t.Fatalf("modo escuro pouco legível: %v", d) + } +} From 17c711f22426a3076b1bdfaa858169790f94787c Mon Sep 17 00:00:00 2001 From: Henrique Fagundes Date: Thu, 26 Nov 2026 19:59:09 -0300 Subject: [PATCH 2/3] =?UTF-8?q?web:=20interface=20nova=20com=20menu=20late?= =?UTF-8?q?ral,=20=C3=ADcones,=20modais,=20assistentes=20e=20execu=C3=A7?= =?UTF-8?q?=C3=A3o=20ao=20vivo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- web/src/App.tsx | 230 ++++++++++++++++++--------- web/src/Avatar.tsx | 14 ++ web/src/Dialogs.tsx | 86 ++++++++++ web/src/Icon.tsx | 46 ++++++ web/src/TipLayer.tsx | 38 +++++ web/src/Wizard.tsx | 66 ++++++++ web/src/api.ts | 7 +- web/src/index.css | 10 ++ web/src/pages/Account.tsx | 45 +++++- web/src/pages/Agents.tsx | 109 +++++++++---- web/src/pages/Appearance.tsx | 192 ++++++++++++----------- web/src/pages/Auth.tsx | 16 +- web/src/pages/Clouds.tsx | 15 +- web/src/pages/Jobs.tsx | 270 ++++++++++++++++++++++---------- web/src/pages/Notifications.tsx | 26 +-- web/src/pages/Runs.tsx | 14 +- web/src/pages/Security.tsx | 3 +- web/src/pages/Users.tsx | 16 +- web/src/themes.ts | 76 +++++---- web/src/ui.tsx | 30 +++- 20 files changed, 962 insertions(+), 347 deletions(-) create mode 100644 web/src/Avatar.tsx create mode 100644 web/src/Dialogs.tsx create mode 100644 web/src/Icon.tsx create mode 100644 web/src/TipLayer.tsx create mode 100644 web/src/Wizard.tsx diff --git a/web/src/App.tsx b/web/src/App.tsx index cb9ce5b..7615c69 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -1,8 +1,12 @@ import { useCallback, useEffect, useState } from 'react' import Logo, { BrandCtx, useFavicon } from './Logo' -import { THEMES, applyTheme, savedTheme } from './themes' +import { applyTheme, forgetLocalTheme, onSystemModeChange } from './themes' import { Agent, Branding, User, api, ApiError, ROLE_LABEL } from './api' -import { Card } from './ui' +import { Button, Card } from './ui' +import Icon, { IconName } from './Icon' +import TipLayer from './TipLayer' +import Avatar from './Avatar' +import DialogHost from './Dialogs' import { Login, Setup } from './pages/Auth' import Agents from './pages/Agents' import Jobs from './pages/Jobs' @@ -25,30 +29,50 @@ function useRoute() { return r } +type NavItem = { to: string; label: string; icon: IconName; admin?: boolean } +const NAV: { title: string; items: NavItem[] }[] = [ + { title: 'Operação', items: [ + { to: 'painel', label: 'Painel', icon: 'painel' }, { to: 'agentes', label: 'Agentes', icon: 'agentes' }, + { to: 'jobs', label: 'Jobs', icon: 'jobs' }, { to: 'nuvem', label: 'Destinos', icon: 'destinos' }, { to: 'historico', label: 'Histórico', icon: 'historico' }, + ] }, + { title: 'Administração', items: [ + { to: 'usuarios', label: 'Usuários', icon: 'usuarios', admin: true }, { to: 'notificacoes', label: 'Notificações', icon: 'notificacoes', admin: true }, + { to: 'seguranca', label: 'Segurança', icon: 'seguranca', admin: true }, { to: 'auditoria', label: 'Auditoria', icon: 'auditoria', admin: true }, + { to: 'aparencia', label: 'Aparência', icon: 'aparencia', admin: true }, + ] }, +] + +function readCollapsed() { try { return localStorage.getItem('coruja.menu') === 'recolhido' } catch { return false } } + export default function App() { const [brand, setBrand] = useState({ name: 'Coruja Backup', theme: 'coruja', themes: [], has_logo: false }) - const [theme, setTheme] = useState('coruja') const [phase, setPhase] = useState('loading') const [me, setMe] = useState(null) - const [version, setVersion] = useState('0.0.15') + const [version, setVersion] = useState('0.0.16') + const [drawer, setDrawer] = useState(false) + const [collapsed, setCollapsed] = useState(readCollapsed) const route = useRoute() + const page = route.split('?')[0] useFavicon(brand) const loadBrand = useCallback(() => { fetch('/api/branding').then((r) => r.json()).then((b: Branding) => { b.themes = b.themes ?? [] - setBrand(b); setTheme(applyTheme(savedTheme() ?? b.theme, b.themes)) - }).catch(() => setTheme(applyTheme(savedTheme() ?? 'coruja'))) + setBrand(b); applyTheme(b.theme, b.themes, b.mode ?? 'auto') + }).catch(() => applyTheme('coruja')) }, []) useEffect(() => { + forgetLocalTheme() loadBrand() fetch('/api/version').then((r) => r.json()).then((v) => setVersion(v.version)).catch(() => {}) }, [loadBrand]) - useEffect(() => { - document.title = brand.name - const link = document.querySelector('link[rel="icon"]') - if (link) link.href = brand.has_logo ? `/api/branding/logo?v=${brand.logo_version ?? ''}` : '/favicon.svg' - }, [brand]) + useEffect(() => { document.title = brand.name }, [brand]) + // no modo Automático, acompanha a troca de claro/escuro do sistema sem recarregar a página + useEffect(() => onSystemModeChange(() => { + if ((brand.mode ?? 'auto') === 'auto' && !window.location.hash.startsWith('#/aparencia')) applyTheme(brand.theme, brand.themes, 'auto') + }), [brand]) + useEffect(() => { setDrawer(false) }, [route]) + useEffect(() => { try { localStorage.setItem('coruja.menu', collapsed ? 'recolhido' : 'aberto') } catch { /* tudo bem */ } }, [collapsed]) const refresh = useCallback(async () => { try { @@ -65,72 +89,129 @@ export default function App() { async function logout() { try { await api('POST', '/api/logout') } catch { /* ignora */ } setMe(null); setPhase('login'); window.location.hash = '' } + const footer =