diff --git a/CHANGELOG.md b/CHANGELOG.md index 08a3d82..6292f44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## [0.0.16] - Interface nova +- **Interface nova:** menu lateral à esquerda, com ícones e grupos (Operação e Administração), que pode ser recolhido; no celular vira uma gaveta. Cartões, login e painel redesenhados. +- **Ícones no lugar dos links** de ação (executar, histórico, editar, pausar, excluir, testar...), com dica ao passar o mouse ou focar pelo teclado. +- **Tema único do sistema:** o seletor de tema do topo saiu. O tema é escolhido só em **Aparência**, pelo administrador, e vale para todos. **Correção:** a escolha antiga guardada em cada navegador podia sobrepor o tema do sistema, mostrando um tema diferente do selecionado; ela é descartada. +- **Créditos do rodapé configuráveis** em Aparência (texto, nome e link), também nos e-mails e no PDF. Nome vazio esconde os créditos. +- **Janelas de confirmação no visual do sistema** no lugar dos alertas do navegador (excluir, executar, revogar, renomear, redefinir senha...). +- **Execução ao vivo:** em Jobs e no Histórico, o backup em andamento aparece com indicador girando, fase e percentual, atualizados a cada 2 segundos. +- **Temas só por pacote, com modo claro e escuro:** a tela de Aparência não cria nem edita cores; instala, atualiza ou exclui pacotes, além dos temas da Coruja (Coruja e Floresta). Cada tema tem modo claro e escuro (`colors_dark` no pacote, ou gerado automaticamente), e o modo pode ser Claro, Escuro ou Automático. O antigo tema "Noturno" vira Coruja no modo escuro. +- **Assistentes:** Novo job (Identificação › Origem › Agenda › Destino › Revisão) e Novo agente (Identificação › Instalação › Conexão, que espera o agente aparecer) passam a ser em etapas. Na edição de um job, qualquer etapa pode ser aberta e salva. +- **Foto do usuário:** em Minha conta, cada usuário envia a própria foto (PNG, JPEG, GIF ou WebP, até 2 MB; o sistema recorta o centro e reduz para 256×256 px), mostrada no menu e em Usuários. + ## [0.0.15] - Agente e tipos na lista - **Pasta e arquivo diferenciados:** nas listas do que salvar e das exclusões, cada item tem ícone e etiqueta (Pasta, Arquivo, Atalho, Padrão), e as pastas terminam com `/`. Um caminho que não existe mais no agente aparece como **Não encontrado**. - **Nomes:** a máquina onde o backup roda é sempre chamada de **agente** na interface, nos e-mails e no PDF. "Servidor" fica só para servidores SMTP, SFTP, FTP, SMB e de banco. diff --git a/Dockerfile b/Dockerfile index a96a28d..1ae9007 100644 --- a/Dockerfile +++ b/Dockerfile @@ -12,7 +12,7 @@ RUN mkdir -p /src/internal/webui && npm run build # Os estágios web e gobuild rodam na plataforma nativa do runner (sem emulação); só o binário é cruzado. # --- binários Go ----------------------------------------------------------------------------------------------------- FROM --platform=$BUILDPLATFORM golang:1.26-alpine AS gobuild -ARG VERSION=0.0.15 +ARG VERSION=0.0.16 ARG TARGETOS ARG TARGETARCH WORKDIR /src @@ -32,7 +32,7 @@ RUN --mount=type=secret,id=google_client_secret --mount=type=secret,id=google_we # --- Server ------------------------------------------------------------------------------------------------------------ FROM alpine:3.21 AS server -ARG VERSION=0.0.15 +ARG VERSION=0.0.16 LABEL org.opencontainers.image.title="Coruja Backup Server" \ org.opencontainers.image.description="Backup centralizado: orquestração, agendamentos, nuvem e interface web" \ org.opencontainers.image.source="https://github.com/AprendendoLinux/corujabackup" \ @@ -48,7 +48,7 @@ ENTRYPOINT ["/usr/local/bin/coruja-server"] # --- Agente ------------------------------------------------------------------------------------------------------------ FROM alpine:3.21 AS agent -ARG VERSION=0.0.15 +ARG VERSION=0.0.16 LABEL org.opencontainers.image.title="Coruja Backup Agent" \ org.opencontainers.image.description="Agente leve do Coruja Backup (conecta ao Server por IP:porta)" \ org.opencontainers.image.source="https://github.com/AprendendoLinux/corujabackup" \ diff --git a/README.md b/README.md index b1a8e89..ddcd7af 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Sistema de backup **centralizado**, em Docker, gerenciado por **interface web**. Um **Server** orquestra tudo; **Agentes** leves rodam nos servidores de destino e se conectam a ele informando só **IP:porta + token**. -> **Versão 0.0.15** · [Changelog](CHANGELOG.md) · [Instalação](docs/INSTALACAO.md) · [Operação](docs/OPERACAO.md) · [Segurança](docs/SEGURANCA.md) · [FAQ](docs/FAQ.md) +> **Versão 0.0.16** · [Changelog](CHANGELOG.md) · [Instalação](docs/INSTALACAO.md) · [Operação](docs/OPERACAO.md) · [Segurança](docs/SEGURANCA.md) · [FAQ](docs/FAQ.md) ## O que faz @@ -69,4 +69,4 @@ docker run --rm --network SUA_REDE -e CORUJA_TEST_DSN='usuario:senha@tcp(db:3306 ``` --- -Coruja Backup - Versão 0.0.15 - Desenvolvido por [Henrique Fagundes](https://henrique.tec.br) · Licença MIT +Coruja Backup - Versão 0.0.16 - Desenvolvido por [Henrique Fagundes](https://henrique.tec.br) · Licença MIT diff --git a/VERSION b/VERSION index ceddfb2..e3b86dd 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.0.15 +0.0.16 diff --git a/deploy/docker-compose.agent.yml b/deploy/docker-compose.agent.yml index 563fde8..1c88bd5 100644 --- a/deploy/docker-compose.agent.yml +++ b/deploy/docker-compose.agent.yml @@ -2,7 +2,7 @@ # Informe o endereço do canal dos agentes do Server e o token gerado na interface (Agentes > Novo agente; vale uma vez). services: agent: - image: ghcr.io/aprendendolinux/corujabackup-agent:0.0.15 + image: ghcr.io/aprendendolinux/corujabackup-agent:0.0.16 container_name: corujabackup-agent restart: always environment: diff --git a/deploy/docker-compose.server.yml b/deploy/docker-compose.server.yml index e129f05..fc6ff20 100644 --- a/deploy/docker-compose.server.yml +++ b/deploy/docker-compose.server.yml @@ -31,7 +31,7 @@ services: networks: [echelon] server: - image: ghcr.io/aprendendolinux/corujabackup-server:0.0.15 + image: ghcr.io/aprendendolinux/corujabackup-server:0.0.16 container_name: corujabackup-server restart: always depends_on: diff --git a/docker-compose.dev.example.yml b/docker-compose.dev.example.yml index 56f0eda..b5d121f 100644 --- a/docker-compose.dev.example.yml +++ b/docker-compose.dev.example.yml @@ -2,7 +2,7 @@ # docker compose -f docker-compose.dev.yml up -d --build -> http://187.110.161.52:8081 services: server: - build: { context: ., target: server, args: { VERSION: "0.0.15" } } + build: { context: ., target: server, args: { VERSION: "0.0.16" } } container_name: corujabackup-dev-server restart: unless-stopped ports: ["8081:8080", "8444:8443"] # 8081 = interface web · 8444 = canal dos agentes diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 486a413..0472806 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -14,6 +14,7 @@ - [x] **Usabilidade (0.0.13):** seleção de pastas e arquivos por clique (origem, exclusões e destinos), endereço público do canal dos agentes e botões de copiar funcionando em `http://IP`. - [x] **Pasta local pelo painel (0.0.14):** servidor inteiro visível, pasta do backup local escolhida na interface com o espaço livre, e o que é do agente (backups, destinos e credenciais) fora dos backups. - [x] **Clareza da interface (0.0.15):** a máquina do backup é sempre chamada de agente; pastas, arquivos, atalhos e padrões identificados nas listas. +- [x] **Interface nova (0.0.16):** menu lateral, ícones, modais próprios, assistentes de job e agente, execução ao vivo, temas só por pacote com modo claro e escuro, créditos configuráveis e foto do usuário. - [ ] **Fase 9, parte 3:** vários destinos por job; compatíveis com S3; SharePoint. - [ ] **Fase 10 – Full/Incremental e MikroTik (versão seguinte):** motor `tar.gz` em blocos com índice e catálogo; agenda full + incrementais; retenção por cadeia; jobs de MikroTik (SSH: `.rsc` e `.backup`). - [ ] **Fase 11 – Restauração inteligente (versão posterior):** árvore de arquivos, linha do tempo de versões, restauração de arquivos selecionados e de bancos pela interface. diff --git a/docs/TEMAS.md b/docs/TEMAS.md index eddf81c..d2ff952 100644 --- a/docs/TEMAS.md +++ b/docs/TEMAS.md @@ -46,6 +46,7 @@ Limites: `.zip` até 3 MiB; cada arquivo até 1 MiB; até 12 arquivos; nomes só | `name` | Nome exibido (1 a 40 caracteres). | | `version`, `author`, `description` | Opcionais, informativos. | | `colors` | As 10 cores da interface, **todas obrigatórias**, no formato `#RRGGBB`. | +| `colors_dark` | Opcional. As mesmas 10 cores para o **modo escuro**. Sem ele, o modo escuro é gerado automaticamente a partir de `colors` (fundos escuros tingidos pela cor principal e destaques clareados para manter o contraste). | | `document` | Opcional. Cores de e-mail e PDF que você quer **sobrescrever** (veja abaixo). | | `logo.ui`, `logo.document` | Opcionais. Nomes de arquivos que estão no pacote. | @@ -78,6 +79,9 @@ O tema que vale para e-mail e PDF é o **tema padrão** (em Aparência › Ident > Fontes personalizadas ainda **não** são suportadas (a versão 1 do formato só cobre cores e logos). +## Modo claro e escuro +Todo tema tem os dois modos. Em **Aparência**, o administrador escolhe o tema e o modo: **Claro**, **Escuro** ou **Automático**, que segue o modo do sistema operacional de cada pessoa. Os temas só entram por pacote; na tela não é possível alterar as cores de um tema instalado, apenas instalar, atualizar (importando de novo o mesmo `id`) ou excluir. E-mails e PDF usam sempre o modo claro. + ## Passo a passo: criar e importar um tema 1. Copie a pasta [`themes/exemplo`](../themes/exemplo) e renomeie. diff --git a/docs/theme.schema.json b/docs/theme.schema.json index ac6ea25..f44b25b 100644 --- a/docs/theme.schema.json +++ b/docs/theme.schema.json @@ -4,31 +4,117 @@ "title": "Coruja Backup · theme.json (schema 1)", "type": "object", "additionalProperties": false, - "required": ["schema", "id", "name", "colors"], + "required": [ + "schema", + "id", + "name", + "colors" + ], "properties": { - "schema": { "const": 1 }, - "id": { "type": "string", "pattern": "^[a-z0-9][a-z0-9-]{1,29}$", "not": { "enum": ["coruja", "noturno", "floresta"] } }, - "name": { "type": "string", "minLength": 1, "maxLength": 40 }, - "version": { "type": "string", "pattern": "^[0-9A-Za-z.+-]{1,20}$" }, - "author": { "type": "string", "maxLength": 80 }, - "description": { "type": "string", "maxLength": 300 }, + "schema": { + "const": 1 + }, + "id": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9-]{1,29}$", + "not": { + "enum": [ + "coruja", + "noturno", + "floresta", + "floresta-escuro" + ] + } + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 40 + }, + "version": { + "type": "string", + "pattern": "^[0-9A-Za-z.+-]{1,20}$" + }, + "author": { + "type": "string", + "maxLength": 80 + }, + "description": { + "type": "string", + "maxLength": 300 + }, "colors": { "type": "object", "additionalProperties": false, - "required": ["bg", "surface", "text", "muted", "border", "primary", "primary_contrast", "accent", "ok", "danger"], - "patternProperties": { "^(bg|surface|text|muted|border|primary|primary_contrast|accent|ok|danger)$": { "$ref": "#/$defs/color" } } + "required": [ + "bg", + "surface", + "text", + "muted", + "border", + "primary", + "primary_contrast", + "accent", + "ok", + "danger" + ], + "patternProperties": { + "^(bg|surface|text|muted|border|primary|primary_contrast|accent|ok|danger)$": { + "$ref": "#/$defs/color" + } + } }, "document": { "type": "object", "additionalProperties": false, - "patternProperties": { "^(bg|text|muted|border|primary|accent|ok|danger)$": { "$ref": "#/$defs/color" } } + "patternProperties": { + "^(bg|text|muted|border|primary|accent|ok|danger)$": { + "$ref": "#/$defs/color" + } + } }, "logo": { "type": "object", "additionalProperties": false, - "properties": { "ui": { "type": "string" }, "document": { "type": "string" } } + "properties": { + "ui": { + "type": "string" + }, + "document": { + "type": "string" + } + } + }, + "preview": { + "type": "string" }, - "preview": { "type": "string" } + "colors_dark": { + "type": "object", + "additionalProperties": false, + "required": [ + "bg", + "surface", + "text", + "muted", + "border", + "primary", + "primary_contrast", + "accent", + "ok", + "danger" + ], + "patternProperties": { + "^(bg|surface|text|muted|border|primary|primary_contrast|accent|ok|danger)$": { + "$ref": "#/$defs/color" + } + }, + "description": "Modo escuro, com as mesmas 10 cores. Opcional: sem ele, o Coruja Backup gera um modo escuro a partir de \"colors\"." + } }, - "$defs": { "color": { "type": "string", "pattern": "^#[0-9a-fA-F]{6}$" } } + "$defs": { + "color": { + "type": "string", + "pattern": "^#[0-9a-fA-F]{6}$" + } + } } 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) + } +} diff --git a/internal/version/version.go b/internal/version/version.go index 7de0999..18e1a86 100644 --- a/internal/version/version.go +++ b/internal/version/version.go @@ -2,6 +2,6 @@ package version // Version é sobrescrita no build: -ldflags "-X github.com/AprendendoLinux/corujabackup/internal/version.Version=1.2.3". -var Version = "0.0.15" +var Version = "0.0.16" const Name = "Coruja Backup" diff --git a/scripts/release.sh b/scripts/release.sh index cc419ad..04508a7 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -1,8 +1,8 @@ #!/bin/sh # Publicação manual das imagens multi-arquitetura (o fluxo normal é o workflow "Release", disparado pela tag vX.Y.Z). -# Uso: ./scripts/release.sh 0.0.15 (precisa de "docker login ghcr.io" e do buildx) +# Uso: ./scripts/release.sh 0.0.16 (precisa de "docker login ghcr.io" e do buildx) set -e -V="${1:?informe a versão, ex.: 0.0.15}" +V="${1:?informe a versão, ex.: 0.0.16}" OWNER="${OWNER:-aprendendolinux}" cd "$(dirname "$0")/.." # Segredo do app OAuth padrão do Google (opcional): GOOGLE_CLIENT_SECRET_FILE=/caminho/arquivo ./scripts/release.sh X.Y.Z diff --git a/web/package.json b/web/package.json index 2f90e60..d7c8c47 100644 --- a/web/package.json +++ b/web/package.json @@ -1,7 +1,7 @@ { "name": "coruja-backup-web", "private": true, - "version": "0.0.15", + "version": "0.0.16", "type": "module", "scripts": { "dev": "vite", 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 =