diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index b24de93..68569d8 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -36,6 +36,9 @@ jobs:
provenance: mode=max
sbom: true
build-args: VERSION=${{ steps.v.outputs.version }}
+ secrets: |
+ google_client_secret=${{ secrets.GOOGLE_CLIENT_SECRET }}
+ google_web_client_secret=${{ secrets.GOOGLE_WEB_CLIENT_SECRET }}
tags: |
ghcr.io/${{ steps.v.outputs.owner }}/corujabackup-server:${{ steps.v.outputs.version }}
ghcr.io/${{ steps.v.outputs.owner }}/corujabackup-server:latest
@@ -63,13 +66,19 @@ jobs:
- name: Interface web (embutida no binário do Server)
run: cd web && npm install --no-audit --no-fund && npm run build
- name: Compilar
+ env:
+ GOOGLE_CLIENT_SECRET: ${{ secrets.GOOGLE_CLIENT_SECRET }} # aplicativo OAuth padrão do Google (opcional)
+ GOOGLE_WEB_CLIENT_SECRET: ${{ secrets.GOOGLE_WEB_CLIENT_SECRET }}
run: |
VERSION="${GITHUB_REF_NAME#v}"
mkdir -p dist
for arch in amd64 arm64; do
for bin in server agent; do
+ LDF="-s -w -X github.com/AprendendoLinux/corujabackup/internal/version.Version=${VERSION}"
+ if [ "$bin" = server ] && [ -n "$GOOGLE_CLIENT_SECRET" ]; then LDF="$LDF -X github.com/AprendendoLinux/corujabackup/internal/cloud.DefaultGoogleClientSecret=${GOOGLE_CLIENT_SECRET}"; fi
+ if [ "$bin" = server ] && [ -n "$GOOGLE_WEB_CLIENT_SECRET" ]; then LDF="$LDF -X github.com/AprendendoLinux/corujabackup/internal/cloud.DefaultGoogleWebClientSecret=${GOOGLE_WEB_CLIENT_SECRET}"; fi
CGO_ENABLED=0 GOOS=linux GOARCH=$arch go build -trimpath \
- -ldflags "-s -w -X github.com/AprendendoLinux/corujabackup/internal/version.Version=${VERSION}" \
+ -ldflags "$LDF" \
-o "dist/coruja-${bin}-linux-${arch}" "./cmd/${bin}"
done
done
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a7d18f3..61dc201 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,11 @@
# Changelog
+## [0.0.10] - Fase 9 · Login com um clique e Dropbox
+- **Dropbox:** novo destino, com login por popup (cliente público, sem segredo) e acesso só à pasta do aplicativo. Envio em partes com retomada, conferência pelo `content_hash` do Dropbox, retenção, download e restauração. Como o Dropbox não tem endereço pré-autorizado para arquivos grandes, o agente recebe um **token de curta duração só de escrita de conteúdo** (exceção à regra "o agente não recebe tokens"); cada envio precisa terminar antes de o token vencer (cerca de 4 horas).
+- **Correção (todas as nuvens):** quando o agente detectava que o arquivo na nuvem não conferia, ele desistia sem avisar o Server e o arquivo corrompido ficava com nome de backup. Agora o Server confere de novo e o apaga, preservando as cópias boas.
+- **Login por popup** para Google Drive, OneDrive e Dropbox (e "Reautorizar" usa o popup nessas contas); tela de escolha de destino com ícones.
+- **Aplicativo OAuth padrão do Google Drive** nas imagens oficiais: o usuário só abre o link e digita o código, sem registrar aplicativo (o modo manual continua disponível).
+
## [0.0.9] - Fase 8 · Pacotes de temas
- **Pacotes de tema (`.zip`):** importados em Aparência; o tema vale para a **interface**, os **e-mails** e os **PDFs** (cores, logo de interface e logo de documento). Importar o mesmo `id` atualiza o tema.
- **Validação rígida:** `.zip` plano e limitado, nomes e tipos verificados, imagens identificadas pelo conteúdo, SVG com script/referência externa recusado, sem CSS livre; auditoria de importação.
diff --git a/Dockerfile b/Dockerfile
index 00cfcb0..98eb9aa 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.9
+ARG VERSION=0.0.10
ARG TARGETOS
ARG TARGETARCH
WORKDIR /src
@@ -22,12 +22,17 @@ COPY cmd ./cmd
COPY internal ./internal
COPY --from=web /src/internal/webui/dist ./internal/webui/dist
ENV CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH}
-RUN go build -trimpath -ldflags "-s -w -X github.com/AprendendoLinux/corujabackup/internal/version.Version=${VERSION}" -o /out/coruja-server ./cmd/server \
+# Aplicativo OAuth padrão do Google: o segredo vem de um build secret opcional (nunca fica em camada da imagem nem no repositório).
+RUN --mount=type=secret,id=google_client_secret --mount=type=secret,id=google_web_client_secret \
+ LDF="-s -w -X github.com/AprendendoLinux/corujabackup/internal/version.Version=${VERSION}"; \
+ if [ -s /run/secrets/google_client_secret ]; then LDF="$LDF -X github.com/AprendendoLinux/corujabackup/internal/cloud.DefaultGoogleClientSecret=$(cat /run/secrets/google_client_secret)"; fi; \
+ if [ -s /run/secrets/google_web_client_secret ]; then LDF="$LDF -X github.com/AprendendoLinux/corujabackup/internal/cloud.DefaultGoogleWebClientSecret=$(cat /run/secrets/google_web_client_secret)"; fi; \
+ go build -trimpath -ldflags "$LDF" -o /out/coruja-server ./cmd/server \
&& go build -trimpath -ldflags "-s -w -X github.com/AprendendoLinux/corujabackup/internal/version.Version=${VERSION}" -o /out/coruja-agent ./cmd/agent
# --- Server ------------------------------------------------------------------------------------------------------------
FROM alpine:3.21 AS server
-ARG VERSION=0.0.9
+ARG VERSION=0.0.10
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" \
@@ -43,7 +48,7 @@ ENTRYPOINT ["/usr/local/bin/coruja-server"]
# --- Agente ------------------------------------------------------------------------------------------------------------
FROM alpine:3.21 AS agent
-ARG VERSION=0.0.9
+ARG VERSION=0.0.10
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 d42864f..2bde27a 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.9** · [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.10** · [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
@@ -11,7 +11,7 @@ nos servidores de destino e se conectam a ele informando só **IP:porta + token*
| :--- | :--- |
| **Backups** | Pastas/arquivos (`.tar.gz` com exclusões) e **bancos de dados** (MySQL, MariaDB, PostgreSQL, MongoDB). Agenda cron com fuso; o **agente agenda sozinho** e roda mesmo com o Server fora do ar. |
| **Confiança** | Cada arquivo é conferido (SHA-256, gzip, estrutura) e há **teste de restauração real** de bancos num servidor descartável. A retenção só roda depois de verificar. Horários perdidos viram alerta. |
-| **Nuvem** | **OneDrive** e **Google Drive**: o agente envia **direto** (sessão retomável), conferência por hash do agente **e** do Server, retenção por quantidade/dias, exclusão definitiva (sem lixeira). |
+| **Nuvem** | **Google Drive**, **OneDrive** e **Dropbox**, conectados com um clique (login por popup): o agente envia **direto** (envio retomável), conferência por hash do agente **e** do Server, retenção por quantidade/dias, exclusão definitiva (sem lixeira). |
| **Restauração** | Baixar da nuvem, reenviar, extrair no agente (extração segura) e guia manual por tipo de backup. |
| **Avisos** | E-mail (SMTP) e Telegram; falha, aviso, sucesso, agente offline e **relatório diário consolidado em PDF A4**. |
| **Interface** | Painel, agentes, jobs, histórico com **log ao vivo**, nuvem, notificações, **white-label** (nome, logo, temas e **pacotes de tema `.zip`** para interface, e-mail e PDF), usuários e perfis, 2FA, auditoria. |
@@ -26,7 +26,7 @@ nos servidores de destino e se conectam a ele informando só **IP:porta + token*
└─────┬──────┘ └──────────┬────────────┘
│ envio direto (sessão emitida pelo Server) │ credenciais da nuvem ficam só aqui (cifradas)
▼ ▼
- OneDrive · Google Drive e-mail · Telegram · Prometheus
+ Drive · OneDrive · Dropbox e-mail · Telegram · Prometheus
```
- O **Server** guarda configuração, histórico e credenciais (cifradas) e expõe duas portas: `8080` (interface/API) e `8443` (agentes).
@@ -67,4 +67,4 @@ docker run --rm --network SUA_REDE -e CORUJA_TEST_DSN='usuario:senha@tcp(db:3306
```
---
-Coruja Backup - Versão 0.0.9 - Desenvolvido por [Henrique Fagundes](https://henrique.tec.br) · Licença MIT
+Coruja Backup - Versão 0.0.10 - Desenvolvido por [Henrique Fagundes](https://henrique.tec.br) · Licença MIT
diff --git a/VERSION b/VERSION
index c5d54ec..7c1886b 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.0.9
+0.0.10
diff --git a/cmd/server/main.go b/cmd/server/main.go
index 1a92776..d0444d5 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -18,6 +18,7 @@ import (
"github.com/AprendendoLinux/corujabackup/internal/agentsrv"
"github.com/AprendendoLinux/corujabackup/internal/auth"
+ "github.com/AprendendoLinux/corujabackup/internal/cloud"
"github.com/AprendendoLinux/corujabackup/internal/cloudmgr"
"github.com/AprendendoLinux/corujabackup/internal/config"
"github.com/AprendendoLinux/corujabackup/internal/db"
@@ -44,6 +45,9 @@ func main() {
fmt.Printf("%s Server %s\n", version.Name, version.Version)
return
}
+ if v := os.Getenv("CORUJA_OAUTH_BROKER"); v != "" { // página de retorno do login por popup (padrão: a do projeto)
+ cloud.OAuthBrokerURL = v
+ }
cfg, err := config.Load(config.Getenv)
if *healthcheck {
os.Exit(probe(cfg.Listen))
diff --git a/deploy/docker-compose.agent.yml b/deploy/docker-compose.agent.yml
index 863c6b2..b20bd83 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.9
+ image: ghcr.io/aprendendolinux/corujabackup-agent:0.0.10
container_name: corujabackup-agent
restart: always
environment:
diff --git a/deploy/docker-compose.server.yml b/deploy/docker-compose.server.yml
index e5c446b..3e8a9cc 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.9
+ image: ghcr.io/aprendendolinux/corujabackup-server:0.0.10
container_name: corujabackup-server
restart: always
depends_on:
diff --git a/docker-compose.dev.example.yml b/docker-compose.dev.example.yml
index 960ec5d..9007208 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.9" } }
+ build: { context: ., target: server, args: { VERSION: "0.0.10" } }
container_name: corujabackup-dev-server
restart: unless-stopped
ports: ["8081:8080", "8444:8443"] # 8081 = interface web · 8444 = canal dos agentes
diff --git a/docs/INSTALACAO.md b/docs/INSTALACAO.md
index e2f132c..0300c1e 100644
--- a/docs/INSTALACAO.md
+++ b/docs/INSTALACAO.md
@@ -66,7 +66,7 @@ docker run -d --name corujabackup-agent --restart always \
- O arquivo `deploy/docker-compose.agent.yml` traz tudo isso, com `cap_drop: ALL` e só as capacidades necessárias.
## 3. Primeiros passos
-1. **Nuvem** (opcional): registre um aplicativo no provedor e conecte a conta pelo código de dispositivo (a tela explica o passo a passo).
+1. **Nuvem** (opcional): no **Google Drive** das imagens oficiais não há nada a registrar: escolha o provedor, abra o link e digite o código (o aplicativo padrão do Coruja só acessa os arquivos que ele mesmo cria). Para OneDrive, ou para usar o seu próprio aplicativo do Google, registre um aplicativo no provedor e informe o Client ID (a tela explica o passo a passo).
2. **Jobs**: pastas/arquivos ou banco de dados; escolha a agenda, as cópias locais e o destino de nuvem.
3. **Notificações**: crie um canal (e-mail/Telegram), clique em **Enviar teste** e use **Criar regras recomendadas**.
4. **Aparência**: nome, logo e tema da sua marca.
diff --git a/docs/OPERACAO.md b/docs/OPERACAO.md
index 5322773..ee832b7 100644
--- a/docs/OPERACAO.md
+++ b/docs/OPERACAO.md
@@ -16,6 +16,12 @@ O Coruja Backup guarda tudo no MySQL e em **um volume** (`/data`). Faça backup
1. Suba o MySQL e restaure o dump. 2. Restaure o volume `/data` (ou ao menos `secret.key` e `tls/`). 3. Suba o Server (mesma versão ou mais nova).
Os agentes reconectam sozinhos e entregam o que ficou na fila local.
+## Aplicativo OAuth padrão (mantenedores e forks)
+
+As imagens oficiais embutem o aplicativo do Google do projeto: o ID do cliente é público (`internal/cloud/defaults.go`) e o **segredo é injetado só na compilação**, a partir do segredo `GOOGLE_CLIENT_SECRET` do GitHub Actions (ou `GOOGLE_CLIENT_SECRET_FILE` no `scripts/release.sh`). Esse segredo é o de um aplicativo do tipo "TVs e dispositivos de entrada limitada", que o Google documenta como não confidencial, mas ele **fica visível no binário**. Compilações sem o segredo (desenvolvimento, forks) simplesmente não oferecem o modo padrão e pedem o Client ID, como antes. Contas conectadas no modo padrão não gravam credenciais; se o segredo mudar, basta atualizar a imagem.
+
+Enquanto a marca do aplicativo não estiver verificada pelo Google, o app aceita até 100 usuários no total.
+
## Atualização
```bash
docker compose -f docker-compose.server.yml pull && docker compose -f docker-compose.server.yml up -d
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index d447b01..2da8dcc 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -9,9 +9,10 @@
- [x] **Fase 6 – Notificações e relatórios (0.0.7):** e-mail, Telegram, PDF A4, configurados pela interface.
- [x] **Fase 7 – Endurecimento e publicação (0.0.8):** TLS, auditoria, limites, documentação, imagens no GitHub Packages.
- [x] **Fase 8 – Pacotes de temas (0.0.9):** temas importáveis (`.zip`) aplicados à interface, ao e-mail e ao PDF; `docs/TEMAS.md`; pacotes de exemplo.
-- [ ] **Fase 9 – Destinos de armazenamento (0.0.10):** vários destinos por job; cartões de provedores com login em popup (OAuth); Dropbox, S3 (e compatíveis), SFTP, SMB, SharePoint, pasta local; NFS/iSCSI via volume montado no host.
-- [ ] **Fase 10 – Full/Incremental e MikroTik (0.0.11):** 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 (0.0.12):** árvore de arquivos, linha do tempo de versões, restauração de arquivos selecionados e de bancos pela interface.
+- [x] **Fase 9, parte 1 – Nuvens com um clique (0.0.10):** login por popup no Google Drive, OneDrive e Dropbox (conector novo), tela de escolha de destino com ícones; os três validados com contas reais.
+- [ ] **Fase 9, parte 2 – Mais destinos:** vários destinos por job; compatíveis com S3; SharePoint; SFTP e SMB; pasta local/volume do host (NFS e iSCSI montados no host).
+- [ ] **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.
- [ ] **Fase 12 – Piloto:** instalação em ambiente real, só com autorização e em paralelo ao backup existente; validação com contas reais de nuvem e Telegram.
Decisões: formato próprio (compatível com `tar -xzf`) em vez de restic; NFS/iSCSI por volume do host (perfil privilegiado opcional); aplicativos OAuth registrados pelo mantenedor (pessoa física).
diff --git a/docs/SEGURANCA.md b/docs/SEGURANCA.md
index 14055ad..451b88e 100644
--- a/docs/SEGURANCA.md
+++ b/docs/SEGURANCA.md
@@ -35,3 +35,7 @@
- [ ] Revisar a página Auditoria periodicamente; usuários em perfis mínimos (Operador/Somente leitura).
Para relatar uma vulnerabilidade, veja [SECURITY.md](../SECURITY.md).
+
+## Exceção do Dropbox
+
+No Google Drive e no OneDrive o agente recebe só o endereço de uma sessão de envio. O Dropbox não oferece isso para arquivos grandes, então o Server emite para o agente um **token de curta duração (cerca de 4 horas)** com o único escopo `files.content.write`, restrito à pasta do aplicativo. Esse escopo permite gravar e também **apagar** arquivos dessa pasta: um agente comprometido poderia remover backups da conta Dropbox durante a validade do token. Atenuantes: o Dropbox mantém os arquivos apagados recuperáveis por um período (conforme o plano da conta), e o token não lê o conteúdo nem alcança o restante do Dropbox. Se isso não for aceitável, use outro destino para esse job.
diff --git a/internal/agentcore/core.go b/internal/agentcore/core.go
index 87d8170..e5bdc53 100644
--- a/internal/agentcore/core.go
+++ b/internal/agentcore/core.go
@@ -555,10 +555,14 @@ func (c *Core) uploadToCloud(ctx context.Context, spec *pb.JobSpec, runUID strin
h.log("info", "sessão de upload aberta; enviando %s", HumanBytes(res.BytesOutput))
opt := c.httpc.opt
opt.Progress = func(sent, total int64) { progress(int(sent * 100 / total)) }
- up, err = uploader.Upload(ctx, uploader.Session{Protocol: sess.Protocol, URL: sess.Url, ChunkSize: sess.ChunkSize}, res.OutputPath, opt)
+ up, err = uploader.Upload(ctx, uploader.Session{Protocol: sess.Protocol, URL: sess.Url, ChunkSize: sess.ChunkSize, Token: sess.Token, Path: sess.UploadPath}, res.OutputPath, opt)
if err == nil {
break
}
+ if errors.Is(err, uploader.ErrMismatch) { // segue para o Server, que confere de novo e apaga o arquivo ruim
+ h.log("error", "%v; pedindo ao Server para conferir e descartar", err)
+ break
+ }
if errors.Is(err, uploader.ErrSessionExpired) && attempt == 0 {
h.log("warn", "a sessão de upload expirou; abrindo outra")
continue
@@ -568,7 +572,7 @@ func (c *Core) uploadToCloud(ctx context.Context, spec *pb.JobSpec, runUID strin
h.log("info", "envio concluído; aguardando a conferência do Server")
m, err := c.ask(ctx, 10*time.Minute, func(id string) *pb.AgentMessage {
return &pb.AgentMessage{Body: &pb.AgentMessage_UploadDone{UploadDone: &pb.UploadDone{RequestId: id, RunUid: runUID, JobId: spec.JobId, FileName: res.OutputName,
- Size: up.Digest.Size, Md5: up.Digest.MD5, Sha1: up.Digest.SHA1, Quickxor: up.Digest.QuickXor, Sha256: up.Digest.SHA256, RemoteId: up.RemoteID, Ok: true}}}
+ Size: up.Digest.Size, Md5: up.Digest.MD5, Sha1: up.Digest.SHA1, Quickxor: up.Digest.QuickXor, Sha256: up.Digest.SHA256, DropboxHash: up.Digest.Dropbox, RemoteId: up.RemoteID, Ok: true}}}
})
if err != nil {
return info, err
diff --git a/internal/agentsrv/agentsrv.go b/internal/agentsrv/agentsrv.go
index 1a9ebbf..28b9f1a 100644
--- a/internal/agentsrv/agentsrv.go
+++ b/internal/agentsrv/agentsrv.go
@@ -506,7 +506,7 @@ func (s *Server) handleUploadRequest(ctx context.Context, a *store.Agent, r *pb.
return deny(err.Error())
}
return &pb.ServerMessage{Body: &pb.ServerMessage_UploadSession{UploadSession: &pb.UploadSession{RequestId: r.RequestId, Ok: true,
- Protocol: up.Session.Protocol, Url: up.Session.URL, ChunkSize: up.Session.ChunkSize, ExpiresUnixMs: up.Session.ExpiresAt.UnixMilli(), RemotePath: up.RemotePath}}}
+ Protocol: up.Session.Protocol, Token: up.Session.Token, UploadPath: up.Session.Path, Url: up.Session.URL, ChunkSize: up.Session.ChunkSize, ExpiresUnixMs: up.Session.ExpiresAt.UnixMilli(), RemotePath: up.RemotePath}}}
}
func (s *Server) handleUploadDone(ctx context.Context, a *store.Agent, d *pb.UploadDone) *pb.ServerMessage {
@@ -521,7 +521,7 @@ func (s *Server) handleUploadDone(ctx context.Context, a *store.Agent, d *pb.Upl
if !d.Ok {
return reply(&pb.UploadVerdict{Ok: false, Message: "o agente relatou falha no envio: " + clip(d.Error, 500)})
}
- v := s.Cloud.VerifyAndRetain(ctx, j, d.FileName, d.Size, cloudmgr.Hashes{QuickXor: d.Quickxor, SHA1: d.Sha1, MD5: d.Md5}, time.Now().UTC())
+ v := s.Cloud.VerifyAndRetain(ctx, j, d.FileName, d.Size, cloudmgr.Hashes{QuickXor: d.Quickxor, SHA1: d.Sha1, MD5: d.Md5, Dropbox: d.DropboxHash}, time.Now().UTC())
if !v.OK {
slog.Warn("envio à nuvem não conferiu", "job", j.Name, "motivo", v.Message)
}
diff --git a/internal/cloud/cloud.go b/internal/cloud/cloud.go
index 8f81acb..587e5da 100644
--- a/internal/cloud/cloud.go
+++ b/internal/cloud/cloud.go
@@ -27,12 +27,16 @@ type RemoteFile struct {
QuickXor string // base64 (OneDrive)
SHA1 string // hex (OneDrive pessoal)
MD5 string // hex (Google Drive)
- Modified time.Time
+ // ContentHash é o hash próprio do Dropbox (hex).
+ ContentHash string
+ Modified time.Time
}
// UploadSession é uma sessão de upload retomável já autenticada (o agente não recebe nenhum token).
type UploadSession struct {
- Protocol string // "graph" | "gdrive"
+ Protocol string // "graph" | "gdrive" | "dropbox"
+ Token string // só no Dropbox: token de curta duração para o envio
+ Path string // só no Dropbox: caminho de destino
URL string
ChunkSize int64
ExpiresAt time.Time
diff --git a/internal/cloud/cloudtest/dropbox.go b/internal/cloud/cloudtest/dropbox.go
new file mode 100644
index 0000000..d4bbb38
--- /dev/null
+++ b/internal/cloud/cloudtest/dropbox.go
@@ -0,0 +1,222 @@
+package cloudtest
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "sort"
+ "strings"
+ "sync"
+
+ "github.com/AprendendoLinux/corujabackup/internal/cloud"
+)
+
+// Dropbox é um Dropbox falso: OAuth (PKCE e renovação com escopo), conta, arquivos e sessões de upload em partes.
+type Dropbox struct {
+ *httptest.Server
+ mu sync.Mutex
+ Key string
+ Files map[string][]byte // caminho completo ("/pasta/nome")
+ sessions map[string][]byte
+ scopes map[string]string // access token -> escopo
+ seq int
+
+ LastCode, LastVerifier, LastRedirect, LastSecret string
+ ScopesIssued []string
+ FailAppends int // próximos N append respondem 503
+ LoseAppendReply bool // grava o próximo append mas responde 503 (força correct_offset)
+ CorruptUpload bool // grava conteúdo diferente do recebido
+}
+
+func NewDropbox(key string) *Dropbox {
+ d := &Dropbox{Key: key, Files: map[string][]byte{}, sessions: map[string][]byte{}, scopes: map[string]string{}}
+ d.Server = httptest.NewServer(http.HandlerFunc(d.serve))
+ return d
+}
+
+// Names lista os arquivos de uma pasta.
+func (d *Dropbox) Names(folder string) []string {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ var out []string
+ for p := range d.Files {
+ if n, ok := strings.CutPrefix(p, "/"+folder+"/"); ok && !strings.Contains(n, "/") {
+ out = append(out, n)
+ }
+ }
+ sort.Strings(out)
+ return out
+}
+
+func (d *Dropbox) meta(path string) map[string]any {
+ h := cloud.NewDropboxHash()
+ _, _ = h.Write(d.Files[path])
+ return map[string]any{".tag": "file", "id": "id:" + path, "name": path[strings.LastIndex(path, "/")+1:], "path_lower": strings.ToLower(path),
+ "size": len(d.Files[path]), "content_hash": h.Hex(), "server_modified": "2026-01-02T03:04:05Z"}
+}
+
+func conflict(w http.ResponseWriter, summary string, extra map[string]any) {
+ writeJSON(w, 409, map[string]any{"error_summary": summary, "error": extra})
+}
+
+func (d *Dropbox) token(scope string) string {
+ d.seq++
+ t := fmt.Sprintf("tok%d", d.seq)
+ d.scopes[t] = scope
+ return t
+}
+
+func (d *Dropbox) serve(w http.ResponseWriter, r *http.Request) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ if r.URL.Path == "/oauth2/token" {
+ _ = r.ParseForm()
+ if r.Form.Get("client_id") != d.Key {
+ writeJSON(w, 400, map[string]any{"error": "invalid_client"})
+ return
+ }
+ switch r.Form.Get("grant_type") {
+ case "authorization_code":
+ d.LastCode, d.LastVerifier, d.LastRedirect, d.LastSecret = r.Form.Get("code"), r.Form.Get("code_verifier"), r.Form.Get("redirect_uri"), r.Form.Get("client_secret")
+ if d.LastCode != "codigo-ok" {
+ writeJSON(w, 400, map[string]any{"error": "invalid_grant"})
+ return
+ }
+ writeJSON(w, 200, map[string]any{"access_token": d.token("full"), "refresh_token": "dbx-refresh", "expires_in": 14400})
+ case "refresh_token":
+ if r.Form.Get("refresh_token") != "dbx-refresh" {
+ writeJSON(w, 400, map[string]any{"error": "invalid_grant"})
+ return
+ }
+ sc := r.Form.Get("scope")
+ if sc == "" {
+ sc = "full"
+ } else {
+ d.ScopesIssued = append(d.ScopesIssued, sc)
+ }
+ writeJSON(w, 200, map[string]any{"access_token": d.token(sc), "expires_in": 14400}) // sem novo refresh token, como o Dropbox
+ default:
+ writeJSON(w, 400, map[string]any{"error": "unsupported_grant_type"})
+ }
+ return
+ }
+ scope, ok := d.scopes[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")]
+ if !ok {
+ writeJSON(w, 401, map[string]any{"error_summary": "expired_access_token/"})
+ return
+ }
+ upload := strings.Contains(r.URL.Path, "/upload_session/")
+ if scope != "full" && !upload { // o token do agente só serve para enviar
+ writeJSON(w, 401, map[string]any{"error_summary": "missing_scope/"})
+ return
+ }
+ body, _ := io.ReadAll(r.Body)
+ var in struct {
+ Path string `json:"path"`
+ Cursor struct {
+ ID string `json:"session_id"`
+ Offset int64 `json:"offset"`
+ } `json:"cursor"`
+ Commit struct {
+ Path string `json:"path"`
+ } `json:"commit"`
+ }
+ if upload || strings.HasSuffix(r.URL.Path, "/files/download") {
+ arg := r.Header.Get("Dropbox-API-Arg")
+ for _, c := range arg {
+ if c > 0x7e {
+ writeJSON(w, 400, map[string]any{"error_summary": "cabeçalho não ASCII"})
+ return
+ }
+ }
+ _ = json.Unmarshal([]byte(arg), &in)
+ } else {
+ _ = json.Unmarshal(body, &in)
+ }
+ switch strings.TrimPrefix(r.URL.Path, "/2") {
+ case "/users/get_current_account":
+ writeJSON(w, 200, map[string]any{"email": "dono@dropbox.test"})
+ case "/users/get_space_usage":
+ writeJSON(w, 200, map[string]any{"used": 1000, "allocation": map[string]any{".tag": "individual", "allocated": 1 << 31}})
+ case "/files/upload_session/start":
+ d.seq++
+ id := fmt.Sprintf("sess%d", d.seq)
+ d.sessions[id] = append([]byte(nil), body...)
+ writeJSON(w, 200, map[string]any{"session_id": id})
+ case "/files/upload_session/append_v2", "/files/upload_session/finish":
+ cur, found := d.sessions[in.Cursor.ID]
+ if !found {
+ conflict(w, "lookup_failed/not_found/", map[string]any{".tag": "lookup_failed"})
+ return
+ }
+ finishing := strings.HasSuffix(r.URL.Path, "/finish")
+ if !finishing && d.FailAppends > 0 {
+ d.FailAppends--
+ w.WriteHeader(503)
+ return
+ }
+ if in.Cursor.Offset != int64(len(cur)) {
+ extra := map[string]any{".tag": "incorrect_offset", "correct_offset": len(cur)}
+ if finishing {
+ extra = map[string]any{".tag": "lookup_failed", "lookup_failed": map[string]any{".tag": "incorrect_offset", "correct_offset": len(cur)}}
+ }
+ conflict(w, "incorrect_offset/", extra)
+ return
+ }
+ cur = append(cur, body...)
+ d.sessions[in.Cursor.ID] = cur
+ if !finishing && d.LoseAppendReply {
+ d.LoseAppendReply = false
+ w.WriteHeader(503)
+ return
+ }
+ if !finishing {
+ writeJSON(w, 200, nil)
+ return
+ }
+ if d.CorruptUpload {
+ cur = append([]byte(nil), cur...)
+ cur[0] ^= 0xff
+ }
+ d.Files[in.Commit.Path] = cur
+ delete(d.sessions, in.Cursor.ID)
+ writeJSON(w, 200, d.meta(in.Commit.Path))
+ case "/files/get_metadata":
+ if _, ok := d.Files[in.Path]; !ok {
+ conflict(w, "path/not_found/", nil)
+ return
+ }
+ writeJSON(w, 200, d.meta(in.Path))
+ case "/files/list_folder":
+ var es []map[string]any
+ for p := range d.Files {
+ if n, ok := strings.CutPrefix(p, in.Path+"/"); ok && !strings.Contains(n, "/") {
+ es = append(es, d.meta(p))
+ }
+ }
+ if es == nil {
+ conflict(w, "path/not_found/", nil)
+ return
+ }
+ writeJSON(w, 200, map[string]any{"entries": es, "has_more": false, "cursor": "c"})
+ case "/files/delete_v2":
+ if _, ok := d.Files[in.Path]; !ok {
+ conflict(w, "path_lookup/not_found/", nil)
+ return
+ }
+ delete(d.Files, in.Path)
+ writeJSON(w, 200, map[string]any{})
+ case "/files/download":
+ c, ok := d.Files[in.Path]
+ if !ok {
+ conflict(w, "path/not_found/", nil)
+ return
+ }
+ w.Header().Set("Content-Length", fmt.Sprint(len(c)))
+ _, _ = w.Write(c)
+ default:
+ writeJSON(w, 404, map[string]any{"error_summary": "rota desconhecida " + r.URL.Path})
+ }
+}
diff --git a/internal/cloud/cloudtest/fake.go b/internal/cloud/cloudtest/fake.go
index 3bb3084..8342fb5 100644
--- a/internal/cloud/cloudtest/fake.go
+++ b/internal/cloud/cloudtest/fake.go
@@ -42,13 +42,14 @@ type Common struct {
seq int
// OAuth
- ClientID string
- PollsUntilOK int
- polls int
- RefreshCount int
- valid map[string]bool
- RefreshToken string
- IssuedTokens int
+ ClientID string
+ PollsUntilOK int
+ LastCode, LastVerifier, LastRedirect, LastSecret string // do último authorization_code recebido (login por popup)
+ polls int
+ RefreshCount int
+ valid map[string]bool
+ RefreshToken string
+ IssuedTokens int
// Falhas injetáveis
FailPuts int // próximos N PUTs de bloco respondem 503
@@ -158,6 +159,14 @@ func (c *Common) handleOAuth(w http.ResponseWriter, r *http.Request) bool {
}
acc, ref := c.newToken()
writeJSON(w, 200, map[string]any{"access_token": acc, "refresh_token": ref, "expires_in": 3600, "token_type": "Bearer"})
+ case "authorization_code": // login por popup (PKCE): guarda o que recebeu para o teste conferir
+ c.LastCode, c.LastVerifier, c.LastRedirect, c.LastSecret = r.Form.Get("code"), r.Form.Get("code_verifier"), r.Form.Get("redirect_uri"), r.Form.Get("client_secret")
+ if c.LastCode != "codigo-ok" {
+ writeJSON(w, 400, map[string]any{"error": "invalid_grant", "error_description": "código inválido"})
+ return true
+ }
+ acc, ref := c.newToken()
+ writeJSON(w, 200, map[string]any{"access_token": acc, "refresh_token": ref, "expires_in": 3600, "token_type": "Bearer"})
case "refresh_token":
if r.Form.Get("refresh_token") != c.RefreshToken {
writeJSON(w, 400, map[string]any{"error": "invalid_grant", "error_description": "refresh token inválido"})
diff --git a/internal/cloud/defaults.go b/internal/cloud/defaults.go
new file mode 100644
index 0000000..1b8f5ba
--- /dev/null
+++ b/internal/cloud/defaults.go
@@ -0,0 +1,74 @@
+package cloud
+
+import "strings"
+
+// Aplicativo OAuth padrão do Coruja Backup para o Google Drive: o usuário só autoriza a própria conta (código no navegador),
+// sem registrar aplicativo nem colar credenciais. O ID do cliente é público. O segredo NÃO fica no repositório: é injetado na
+// compilação das imagens oficiais (-ldflags -X) e é o "segredo" de um aplicativo do tipo TVs/dispositivos, que o Google
+// documenta como não confidencial. Em compilações sem o segredo (desenvolvimento, forks) o modo padrão fica desligado.
+var (
+ DefaultGoogleClientID = "808370832157-1j2fn12fpednq018lqbiuvnd7c1v37v0.apps.googleusercontent.com"
+ DefaultGoogleClientSecret = "" // -X github.com/AprendendoLinux/corujabackup/internal/cloud.DefaultGoogleClientSecret=...
+)
+
+// HasDefaultApp informa se há aplicativo padrão compilado para o tipo de nuvem.
+func HasDefaultApp(typ string) bool {
+ return typ == TypeGDrive && DefaultGoogleClientID != "" && DefaultGoogleClientSecret != ""
+}
+
+// Aplicativo "Aplicativo da Web" do Google (login por popup, com retorno em OAuthBrokerURL). O ID é público; o segredo é
+// injetado na compilação (-X ...cloud.DefaultGoogleWebClientSecret=...) e nunca fica no repositório.
+var (
+ DefaultGoogleWebClientID = "808370832157-vjk5g9bs0b0a3gntcvfsfo0ktsu9km7v.apps.googleusercontent.com"
+ DefaultGoogleWebClientSecret = ""
+ // OAuthBrokerURL é a página pública que recebe a volta do provedor e entrega o código à janela do Coruja (veja site/).
+ OAuthBrokerURL = "https://coruja.henrique.tec.br"
+)
+
+// Aplicativo da Microsoft (cliente público, sem segredo) para o login por popup do OneDrive. O ID é público.
+var DefaultMicrosoftClientID = "ec0121f5-4ea0-470a-860d-705b6dea180e"
+
+// DefaultDropboxAppKey é a chave (pública) do aplicativo do Dropbox: login por popup com PKCE, sem segredo.
+var DefaultDropboxAppKey = "29ptnyvv0n28wtf"
+
+// HasWebApp informa se o login por popup (aplicativo da Web) está disponível para o tipo de nuvem.
+func HasWebApp(typ string) bool {
+ if OAuthBrokerURL == "" {
+ return false
+ }
+ switch typ {
+ case TypeGDrive:
+ return DefaultGoogleWebClientID != "" && DefaultGoogleWebClientSecret != ""
+ case TypeOneDrive:
+ return DefaultMicrosoftClientID != ""
+ case TypeDropbox:
+ return DefaultDropboxAppKey != ""
+ }
+ return false
+}
+
+// WebAppCreds devolve o ID (e o segredo, se houver) do aplicativo de login por popup do tipo de nuvem.
+func WebAppCreds(typ string) (id, secret string) {
+ switch typ {
+ case TypeGDrive:
+ return DefaultGoogleWebClientID, DefaultGoogleWebClientSecret
+ case TypeOneDrive:
+ return DefaultMicrosoftClientID, ""
+ case TypeDropbox:
+ return DefaultDropboxAppKey, ""
+ }
+ return "", ""
+}
+
+// BrokerRedirect devolve o endereço de retorno cadastrado no provedor para o tipo de nuvem.
+func BrokerRedirect(typ string) string {
+ switch typ {
+ case TypeGDrive:
+ return strings.TrimRight(OAuthBrokerURL, "/") + "/oauth/google/callback"
+ case TypeOneDrive:
+ return strings.TrimRight(OAuthBrokerURL, "/") + "/oauth/microsoft/callback"
+ case TypeDropbox:
+ return strings.TrimRight(OAuthBrokerURL, "/") + "/oauth/dropbox/callback"
+ }
+ return ""
+}
diff --git a/internal/cloud/dropbox.go b/internal/cloud/dropbox.go
new file mode 100644
index 0000000..36cd0d7
--- /dev/null
+++ b/internal/cloud/dropbox.go
@@ -0,0 +1,296 @@
+package cloud
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "hash"
+ "io"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+ "unicode/utf16"
+)
+
+const (
+ TypeDropbox = "dropbox"
+ dropboxScope = "account_info.read files.metadata.read files.content.read files.content.write"
+ // DropboxAgentScope é o único escopo do token de curta duração entregue ao agente para o envio.
+ DropboxAgentScope = "files.content.write"
+ dropboxAPI = "https://api.dropboxapi.com/2"
+ dropboxContent = "https://content.dropboxapi.com/2"
+ dropboxBlock = 4 << 20
+ dropboxChunk = 8 << 20
+)
+
+// DropboxHash implementa o "content_hash" do Dropbox: SHA-256 de cada bloco de 4 MiB e, no fim, o SHA-256 da
+// concatenação desses resumos.
+type DropboxHash struct {
+ block hash.Hash
+ n int // bytes no bloco atual
+ all []byte
+}
+
+func NewDropboxHash() *DropboxHash { return &DropboxHash{block: sha256.New()} }
+
+func (d *DropboxHash) Write(p []byte) (int, error) {
+ total := len(p)
+ for len(p) > 0 {
+ k := min(dropboxBlock-d.n, len(p))
+ d.block.Write(p[:k])
+ d.n, p = d.n+k, p[k:]
+ if d.n == dropboxBlock {
+ d.all = d.block.Sum(d.all)
+ d.block.Reset()
+ d.n = 0
+ }
+ }
+ return total, nil
+}
+
+// Hex devolve o content_hash dos bytes escritos até aqui (sem alterar o estado).
+func (d *DropboxHash) Hex() string {
+ all := append([]byte(nil), d.all...)
+ if d.n > 0 {
+ all = d.block.Sum(all)
+ }
+ s := sha256.Sum256(all)
+ return hex.EncodeToString(s[:])
+}
+
+// DropboxOAuth: aplicativo público (PKCE, sem segredo) com acesso só à pasta do aplicativo.
+func DropboxOAuth(clientID, clientSecret string) *OAuth {
+ return &OAuth{ClientID: clientID, ClientSecret: clientSecret, Scope: dropboxScope,
+ AuthURL: "https://www.dropbox.com/oauth2/authorize", TokenURL: "https://api.dropboxapi.com/oauth2/token",
+ AuthExtra: url.Values{"token_access_type": {"offline"}}}
+}
+
+// Dropbox é o provedor. Os caminhos são relativos à pasta do aplicativo (App folder).
+type Dropbox struct {
+ TS Access
+ HTTP *http.Client
+ API string
+ Content string
+ // UploadToken emite um token de curta duração, só de escrita de conteúdo, para o agente fazer o envio.
+ UploadToken func(ctx context.Context) (token string, expires time.Time, err error)
+}
+
+func (d *Dropbox) Type() string { return TypeDropbox }
+
+func (d *Dropbox) http() *http.Client {
+ if d.HTTP != nil {
+ return d.HTTP
+ }
+ return &http.Client{Timeout: 60 * time.Second}
+}
+
+func (d *Dropbox) api() string {
+ if d.API != "" {
+ return strings.TrimRight(d.API, "/")
+ }
+ return dropboxAPI
+}
+
+func (d *Dropbox) content() string {
+ if d.Content != "" {
+ return strings.TrimRight(d.Content, "/")
+ }
+ return dropboxContent
+}
+
+// ASCIIJSON serializa v em JSON só com ASCII (exigência do cabeçalho Dropbox-API-Arg).
+func ASCIIJSON(v any) string {
+ b, _ := json.Marshal(v)
+ var out strings.Builder
+ for _, r := range string(b) {
+ switch {
+ case r < 0x7f:
+ out.WriteRune(r)
+ case r > 0xffff:
+ a, c := utf16.EncodeRune(r)
+ fmt.Fprintf(&out, "\\u%04x\\u%04x", a, c)
+ default:
+ fmt.Fprintf(&out, "\\u%04x", r)
+ }
+ }
+ return out.String()
+}
+
+type dbxError struct {
+ Summary string `json:"error_summary"`
+}
+
+func errorsIsNotFound(err error) bool { return errors.Is(err, ErrNotFound) }
+
+func dbxFail(op string, status int, body []byte) error {
+ var e dbxError
+ _ = json.Unmarshal(body, &e)
+ if status == http.StatusConflict && strings.Contains(e.Summary, "not_found") {
+ return fmt.Errorf("%s: %w", op, ErrNotFound)
+ }
+ return &APIError{Status: status, Body: string(body), Op: op}
+}
+
+// rpc chama um endpoint JSON da API.
+func (d *Dropbox) rpc(ctx context.Context, op, path string, in, out any) error {
+ tok, err := d.TS.Access(ctx)
+ if err != nil {
+ return err
+ }
+ body, _ := json.Marshal(in) // nil vira "null", que é o que o Dropbox espera em chamadas sem argumentos
+ req, err := http.NewRequestWithContext(ctx, "POST", d.api()+path, bytes.NewReader(body))
+ if err != nil {
+ return err
+ }
+ req.Header.Set("Authorization", "Bearer "+tok)
+ req.Header.Set("Content-Type", "application/json")
+ resp, err := d.http().Do(req)
+ if err != nil {
+ return fmt.Errorf("%s: %w", op, err)
+ }
+ defer resp.Body.Close()
+ b, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
+ if resp.StatusCode != 200 {
+ return dbxFail(op, resp.StatusCode, b)
+ }
+ if out == nil {
+ return nil
+ }
+ return json.Unmarshal(b, out)
+}
+
+func (d *Dropbox) Account(ctx context.Context) (string, error) {
+ var r struct {
+ Email string `json:"email"`
+ }
+ if err := d.rpc(ctx, "conta", "/users/get_current_account", nil, &r); err != nil {
+ return "", err
+ }
+ return r.Email, nil
+}
+
+func (d *Dropbox) Quota(ctx context.Context) (Quota, error) {
+ var r struct {
+ Used int64 `json:"used"`
+ Allocation struct {
+ Allocated int64 `json:"allocated"`
+ } `json:"allocation"`
+ }
+ if err := d.rpc(ctx, "cota", "/users/get_space_usage", nil, &r); err != nil {
+ return Quota{}, err
+ }
+ return Quota{Total: r.Allocation.Allocated, Used: r.Used}, nil
+}
+
+// NewUpload não cria sessão no Server: o Dropbox não tem endereço pré-autorizado para arquivos grandes, então o agente
+// recebe um token de curta duração (só files.content.write, restrito à pasta do aplicativo) e abre a sessão em partes.
+func (d *Dropbox) NewUpload(ctx context.Context, folder, name string, size int64) (*UploadSession, error) {
+ if d.UploadToken == nil {
+ return nil, fmt.Errorf("conta Dropbox sem emissor de token de envio")
+ }
+ tok, exp, err := d.UploadToken(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return &UploadSession{Protocol: "dropbox", URL: d.content() + "/files/upload_session", ChunkSize: dropboxChunk,
+ ExpiresAt: exp, Token: tok, Path: "/" + folder + "/" + name}, nil
+}
+
+type dbxEntry struct {
+ Tag string `json:".tag"`
+ ID string `json:"id"`
+ Name string `json:"name"`
+ PathLower string `json:"path_lower"`
+ Size int64 `json:"size"`
+ ContentHash string `json:"content_hash"`
+ Modified time.Time `json:"server_modified"`
+}
+
+func (e dbxEntry) remote() RemoteFile {
+ return RemoteFile{ID: e.ID, Name: e.Name, Size: e.Size, ContentHash: e.ContentHash, Modified: e.Modified}
+}
+
+func (d *Dropbox) Stat(ctx context.Context, folder, name string) (*RemoteFile, error) {
+ var e dbxEntry
+ if err := d.rpc(ctx, "consultar arquivo", "/files/get_metadata", map[string]any{"path": "/" + folder + "/" + name}, &e); err != nil {
+ return nil, err
+ }
+ if e.Tag != "" && e.Tag != "file" {
+ return nil, ErrNotFound
+ }
+ f := e.remote()
+ return &f, nil
+}
+
+func (d *Dropbox) List(ctx context.Context, folder string) ([]RemoteFile, error) {
+ var r struct {
+ Entries []dbxEntry `json:"entries"`
+ Cursor string `json:"cursor"`
+ HasMore bool `json:"has_more"`
+ }
+ err := d.rpc(ctx, "listar pasta", "/files/list_folder", map[string]any{"path": "/" + folder}, &r)
+ if err != nil {
+ if errorsIsNotFound(err) {
+ return nil, nil
+ }
+ return nil, err
+ }
+ var out []RemoteFile
+ for page := 0; ; page++ {
+ for _, e := range r.Entries {
+ if e.Tag == "file" {
+ out = append(out, e.remote())
+ }
+ }
+ if !r.HasMore {
+ return out, nil
+ }
+ if page > 500 {
+ return nil, fmt.Errorf("listar pasta: páginas demais")
+ }
+ cursor := r.Cursor
+ r.Entries, r.HasMore = nil, false
+ if err := d.rpc(ctx, "listar pasta", "/files/list_folder/continue", map[string]any{"cursor": cursor}, &r); err != nil {
+ return nil, err
+ }
+ }
+}
+
+// Delete apaga o arquivo. No Dropbox ele ainda pode ser recuperado por um período (regra do plano da conta).
+func (d *Dropbox) Delete(ctx context.Context, folder string, f RemoteFile) error {
+ err := d.rpc(ctx, "apagar arquivo", "/files/delete_v2", map[string]any{"path": "/" + folder + "/" + f.Name}, nil)
+ if errorsIsNotFound(err) {
+ return nil
+ }
+ return err
+}
+
+func (d *Dropbox) Open(ctx context.Context, folder, name string) (io.ReadCloser, int64, error) {
+ tok, err := d.TS.Access(ctx)
+ if err != nil {
+ return nil, 0, err
+ }
+ req, err := http.NewRequestWithContext(ctx, "POST", d.content()+"/files/download", nil)
+ if err != nil {
+ return nil, 0, err
+ }
+ req.Header.Set("Authorization", "Bearer "+tok)
+ req.Header.Set("Dropbox-API-Arg", ASCIIJSON(map[string]string{"path": "/" + folder + "/" + name}))
+ cl := *d.http()
+ cl.Timeout = 0 // download grande: quem limita é o contexto
+ resp, err := cl.Do(req)
+ if err != nil {
+ return nil, 0, err
+ }
+ if resp.StatusCode != 200 {
+ b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<16))
+ resp.Body.Close()
+ return nil, 0, dbxFail("baixar arquivo", resp.StatusCode, b)
+ }
+ return resp.Body, resp.ContentLength, nil
+}
diff --git a/internal/cloud/dropbox_test.go b/internal/cloud/dropbox_test.go
new file mode 100644
index 0000000..844c23d
--- /dev/null
+++ b/internal/cloud/dropbox_test.go
@@ -0,0 +1,44 @@
+package cloud
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "encoding/hex"
+ "testing"
+)
+
+// O content_hash é definido pela documentação do Dropbox: SHA-256 da concatenação dos SHA-256 de blocos de 4 MiB.
+func TestDropboxContentHash(t *testing.T) {
+ data := bytes.Repeat([]byte("coruja!"), 1_500_000) // ~10 MB: três blocos, o último parcial
+ var cat []byte
+ for i := 0; i < len(data); i += 4 << 20 {
+ s := sha256.Sum256(data[i:min(i+(4<<20), len(data))])
+ cat = append(cat, s[:]...)
+ }
+ want := sha256.Sum256(cat)
+ for _, step := range []int{len(data), 1 << 20, 4 << 20, 3333333, 7} {
+ if step == 7 && testing.Short() {
+ continue
+ }
+ h := NewDropboxHash()
+ for i := 0; i < len(data); i += step {
+ _, _ = h.Write(data[i:min(i+step, len(data))])
+ }
+ if h.Hex() != hex.EncodeToString(want[:]) || h.Hex() != h.Hex() {
+ t.Fatalf("passo %d: hash diferente", step)
+ }
+ }
+ empty := sha256.Sum256(nil)
+ if NewDropboxHash().Hex() != hex.EncodeToString(empty[:]) {
+ t.Fatal("hash de arquivo vazio")
+ }
+}
+
+func TestASCIIJSON(t *testing.T) {
+ got := ASCIIJSON(map[string]string{"path": "/Relatórios 😀/a.tar.gz"})
+ u := func(h string) string { return string(rune(92)) + "u" + h }
+ want := `{"path":"/Relat` + u("00f3") + "rios " + u("d83d") + u("de00") + `/a.tar.gz"}`
+ if got != want {
+ t.Fatalf("%s != %s", got, want)
+ }
+}
diff --git a/internal/cloud/gdrive.go b/internal/cloud/gdrive.go
index 1a01292..fc0f854 100644
--- a/internal/cloud/gdrive.go
+++ b/internal/cloud/gdrive.go
@@ -35,7 +35,8 @@ type GDrive struct {
func GDriveOAuth(clientID, clientSecret string) *OAuth {
return &OAuth{ClientID: clientID, ClientSecret: clientSecret, Scope: gdriveScope,
- DeviceURL: "https://oauth2.googleapis.com/device/code", TokenURL: "https://oauth2.googleapis.com/token"}
+ DeviceURL: "https://oauth2.googleapis.com/device/code", AuthURL: "https://accounts.google.com/o/oauth2/v2/auth", TokenURL: "https://oauth2.googleapis.com/token",
+ AuthExtra: url.Values{"access_type": {"offline"}, "prompt": {"consent"}, "include_granted_scopes": {"false"}}}
}
func (g *GDrive) Type() string { return TypeGDrive }
diff --git a/internal/cloud/hash.go b/internal/cloud/hash.go
index 88e073d..106fc83 100644
--- a/internal/cloud/hash.go
+++ b/internal/cloud/hash.go
@@ -57,10 +57,11 @@ var _ hash.Hash = (*QuickXor)(nil)
type Sums struct {
size int64
sha256, sha1, md5, qx hash.Hash
+ dbx *DropboxHash
}
func NewSums() *Sums {
- return &Sums{sha256: sha256.New(), sha1: sha1.New(), md5: md5.New(), qx: NewQuickXor()} //nolint:gosec
+ return &Sums{sha256: sha256.New(), sha1: sha1.New(), md5: md5.New(), qx: NewQuickXor(), dbx: NewDropboxHash()} //nolint:gosec
}
func (s *Sums) Write(p []byte) (int, error) {
@@ -69,6 +70,7 @@ func (s *Sums) Write(p []byte) (int, error) {
s.sha1.Write(p)
s.md5.Write(p)
s.qx.Write(p)
+ s.dbx.Write(p)
return len(p), nil
}
@@ -78,9 +80,10 @@ type Digest struct {
SHA1 string // hex
MD5 string // hex
QuickXor string // base64 (formato do OneDrive)
+ Dropbox string // hex (content_hash do Dropbox)
}
func (s *Sums) Digest() Digest {
return Digest{Size: s.size, SHA256: hex.EncodeToString(s.sha256.Sum(nil)), SHA1: hex.EncodeToString(s.sha1.Sum(nil)),
- MD5: hex.EncodeToString(s.md5.Sum(nil)), QuickXor: base64.StdEncoding.EncodeToString(s.qx.Sum(nil))}
+ MD5: hex.EncodeToString(s.md5.Sum(nil)), QuickXor: base64.StdEncoding.EncodeToString(s.qx.Sum(nil)), Dropbox: s.dbx.Hex()}
}
diff --git a/internal/cloud/oauth.go b/internal/cloud/oauth.go
index 14d4f69..46bac1e 100644
--- a/internal/cloud/oauth.go
+++ b/internal/cloud/oauth.go
@@ -33,6 +33,8 @@ type OAuth struct {
ClientID string
ClientSecret string
DeviceURL string
+ AuthURL string // fluxo com retorno (popup)
+ AuthExtra url.Values // parâmetros próprios do provedor no endereço de login
TokenURL string
Scope string
HTTP *http.Client
@@ -200,3 +202,56 @@ func (ts *TokenSource) Access(ctx context.Context) (string, error) {
}
return nt.Access, nil
}
+
+// AuthCodeURL monta o endereço de login do fluxo "código de autorização" com PKCE (S256).
+func (o *OAuth) AuthCodeURL(redirect, state, challenge string) string {
+ q := url.Values{"client_id": {o.ClientID}, "redirect_uri": {redirect}, "response_type": {"code"}, "scope": {o.Scope},
+ "state": {state}, "code_challenge": {challenge}, "code_challenge_method": {"S256"}}
+ for k, v := range o.AuthExtra {
+ q[k] = v
+ }
+ return o.AuthURL + "?" + q.Encode()
+}
+
+// ExchangeCode troca o código recebido na volta do login pelos tokens (com o verificador do PKCE).
+func (o *OAuth) ExchangeCode(ctx context.Context, code, verifier, redirect string, now time.Time) (*Token, error) {
+ form := url.Values{"client_id": {o.ClientID}, "code": {code}, "code_verifier": {verifier}, "redirect_uri": {redirect}, "grant_type": {"authorization_code"}}
+ if o.ClientSecret != "" {
+ form.Set("client_secret", o.ClientSecret)
+ }
+ m, status, err := o.post(ctx, o.TokenURL, form)
+ if err != nil {
+ return nil, err
+ }
+ if status != 200 || str(m, "access_token") == "" {
+ return nil, fmt.Errorf("o provedor recusou o código de autorização: %s", errText(m, status))
+ }
+ t := tokenFrom(m, "", now)
+ if t.Refresh == "" {
+ return nil, errors.New("o provedor não devolveu a renovação de acesso (refresh token): revogue o acesso do Coruja na sua conta e tente de novo")
+ }
+ return t, nil
+}
+
+// RefreshScoped emite um access token de curta duração restrito aos escopos pedidos (usado para o envio ao Dropbox).
+func (o *OAuth) RefreshScoped(ctx context.Context, refresh, scope string, now time.Time) (*Token, error) {
+ form := url.Values{"client_id": {o.ClientID}, "refresh_token": {refresh}, "grant_type": {"refresh_token"}, "scope": {scope}}
+ if o.ClientSecret != "" {
+ form.Set("client_secret", o.ClientSecret)
+ }
+ m, code, err := o.post(ctx, o.TokenURL, form)
+ if err != nil {
+ return nil, err
+ }
+ if code != 200 || str(m, "access_token") == "" {
+ return nil, fmt.Errorf("falha ao emitir o token de envio: %s", errText(m, code))
+ }
+ return tokenFrom(m, refresh, now), nil
+}
+
+// RefreshToken devolve o refresh token atual (para emitir tokens restritos).
+func (ts *TokenSource) RefreshToken() string {
+ ts.mu.Lock()
+ defer ts.mu.Unlock()
+ return ts.tok.Refresh
+}
diff --git a/internal/cloud/onedrive.go b/internal/cloud/onedrive.go
index c15c38b..26531d2 100644
--- a/internal/cloud/onedrive.go
+++ b/internal/cloud/onedrive.go
@@ -41,7 +41,9 @@ func OneDriveOAuth(clientID, clientSecret, tenant string) *OAuth {
}
return &OAuth{ClientID: clientID, ClientSecret: clientSecret, Scope: oneDriveScope,
DeviceURL: fmt.Sprintf("%s/%s/oauth2/v2.0/devicecode", msLoginBase, tenant),
- TokenURL: fmt.Sprintf("%s/%s/oauth2/v2.0/token", msLoginBase, tenant)}
+ AuthURL: fmt.Sprintf("%s/%s/oauth2/v2.0/authorize", msLoginBase, tenant),
+ TokenURL: fmt.Sprintf("%s/%s/oauth2/v2.0/token", msLoginBase, tenant),
+ AuthExtra: url.Values{"prompt": {"select_account"}, "response_mode": {"query"}}}
}
func (o *OneDrive) Type() string { return TypeOneDrive }
diff --git a/internal/cloudmgr/cloudmgr.go b/internal/cloudmgr/cloudmgr.go
index 0300ba2..3ce4bef 100644
--- a/internal/cloudmgr/cloudmgr.go
+++ b/internal/cloudmgr/cloudmgr.go
@@ -5,11 +5,16 @@ package cloudmgr
import (
"context"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
+ "regexp"
+ "strings"
"sync"
"time"
@@ -24,6 +29,10 @@ type Endpoints struct {
MSDevice, MSToken string
Graph string
GDevice, GToken string
+ GAuth string
+ DBXToken string
+ DBXAPI string
+ DBXContent string
GAPI, GUpload string
}
@@ -33,6 +42,10 @@ type AccountConfig struct {
Tenant string `json:"tenant,omitempty"`
DriveID string `json:"drive_id,omitempty"`
HardDelete bool `json:"hard_delete"`
+ // UseDefault: usa o aplicativo OAuth padrão compilado (as credenciais não são gravadas na conta).
+ UseDefault bool `json:"use_default,omitempty"`
+ // Web: o aplicativo padrão é o "da Web" (login por popup), não o de TVs/dispositivos.
+ Web bool `json:"web,omitempty"`
}
type Manager struct {
@@ -45,15 +58,33 @@ type Manager struct {
mu sync.Mutex
cache map[int64]cloud.Provider
lastPoll map[int64]time.Time
+ pending map[string]pendingWeb // logins por popup em andamento (nonce -> dados)
+}
+
+type pendingWeb struct {
+ Name, Typ, Origin, Verifier string
+ AccountID int64 // != 0: reautorização de uma conta existente
+ Expires time.Time
}
func New(st *store.Store, box *secrets.Box) *Manager {
- return &Manager{Store: st, Box: box, Now: time.Now, cache: map[int64]cloud.Provider{}, lastPoll: map[int64]time.Time{}}
+ return &Manager{Store: st, Box: box, Now: time.Now, cache: map[int64]cloud.Provider{}, lastPoll: map[int64]time.Time{}, pending: map[string]pendingWeb{}}
}
var ErrNotConnected = errors.New("a conta de nuvem não está conectada")
func (m *Manager) oauth(typ string, cfg AccountConfig) (*cloud.OAuth, error) {
+ if cfg.UseDefault && cfg.Web {
+ if !cloud.HasWebApp(typ) {
+ return nil, errors.New("este Server não tem o aplicativo de login por popup: reconecte a conta")
+ }
+ cfg.ClientID, cfg.ClientSecret = cloud.WebAppCreds(typ)
+ } else if cfg.UseDefault {
+ if !cloud.HasDefaultApp(typ) {
+ return nil, errors.New("este Server não tem aplicativo padrão para esse provedor: reconecte informando as credenciais")
+ }
+ cfg.ClientID, cfg.ClientSecret = cloud.DefaultGoogleClientID, cloud.DefaultGoogleClientSecret
+ }
var o *cloud.OAuth
switch typ {
case cloud.TypeOneDrive:
@@ -66,6 +97,14 @@ func (m *Manager) oauth(typ string, cfg AccountConfig) (*cloud.OAuth, error) {
if m.EP.GDevice != "" {
o.DeviceURL, o.TokenURL = m.EP.GDevice, m.EP.GToken
}
+ if m.EP.GAuth != "" {
+ o.AuthURL = m.EP.GAuth
+ }
+ case cloud.TypeDropbox:
+ o = cloud.DropboxOAuth(cfg.ClientID, cfg.ClientSecret)
+ if m.EP.DBXToken != "" {
+ o.TokenURL = m.EP.DBXToken
+ }
default:
return nil, fmt.Errorf("tipo de nuvem desconhecido: %q", typ)
}
@@ -84,10 +123,13 @@ func (m *Manager) openConfig(a *store.CloudAccount) (AccountConfig, error) {
// Create cadastra a conta (pendente) e inicia a autorização: o usuário abre a URL, digita o código e aprova.
func (m *Manager) Create(ctx context.Context, name, typ string, cfg AccountConfig) (int64, *cloud.Device, error) {
- if cfg.ClientID == "" {
+ if cfg.ClientID == "" && cloud.HasDefaultApp(typ) {
+ cfg.UseDefault, cfg.ClientSecret = true, ""
+ }
+ if cfg.ClientID == "" && !cfg.UseDefault {
return 0, nil, errors.New("informe o Client ID do aplicativo cadastrado no provedor")
}
- if typ == cloud.TypeGDrive && cfg.ClientSecret == "" {
+ if typ == cloud.TypeGDrive && cfg.ClientSecret == "" && !cfg.UseDefault {
return 0, nil, errors.New("o Google exige o Client Secret (credencial do tipo “TVs e dispositivos de entrada limitada”)")
}
o, err := m.oauth(typ, cfg)
@@ -281,6 +323,15 @@ func (m *Manager) Provider(ctx context.Context, id int64) (cloud.Provider, error
p = &cloud.OneDrive{TS: guard{m, id, ts}, HTTP: m.HTTP, Graph: m.EP.Graph, DriveID: cfg.DriveID, HardDelete: cfg.HardDelete}
case cloud.TypeGDrive:
p = &cloud.GDrive{TS: guard{m, id, ts}, HTTP: m.HTTP, API: m.EP.GAPI, Upload: m.EP.GUpload}
+ case cloud.TypeDropbox:
+ p = &cloud.Dropbox{TS: guard{m, id, ts}, HTTP: m.HTTP, API: m.EP.DBXAPI, Content: m.EP.DBXContent,
+ UploadToken: func(ctx context.Context) (string, time.Time, error) {
+ t, err := o.RefreshScoped(ctx, ts.RefreshToken(), cloud.DropboxAgentScope, m.Now())
+ if err != nil {
+ return "", time.Time{}, err
+ }
+ return t.Access, t.Expiry, nil
+ }}
default:
return nil, fmt.Errorf("tipo de nuvem desconhecido: %q", a.Type)
}
@@ -341,7 +392,7 @@ func (m *Manager) OpenUpload(ctx context.Context, j *store.Job, fileName string,
return &Upload{Session: s, RemotePath: folder + "/" + fileName}, nil
}
-type Hashes struct{ QuickXor, SHA1, MD5 string }
+type Hashes struct{ QuickXor, SHA1, MD5, Dropbox string }
type Verdict struct {
OK bool
@@ -379,6 +430,11 @@ func (m *Manager) VerifyAndRetain(ctx context.Context, j *store.Job, fileName st
switch {
case rf.Size != size:
v.Message = fmt.Sprintf("tamanho na nuvem (%d) diferente do enviado (%d)", rf.Size, size)
+ case rf.ContentHash != "" && h.Dropbox != "":
+ v.RemoteHash, v.VerifiedBy = rf.ContentHash, "dropbox"
+ if rf.ContentHash != h.Dropbox {
+ v.Message = "o content_hash do Dropbox difere do arquivo enviado"
+ }
case rf.QuickXor != "" && h.QuickXor != "":
v.RemoteHash, v.VerifiedBy = rf.QuickXor, "quickxor"
if rf.QuickXor != h.QuickXor {
@@ -431,3 +487,137 @@ func (m *Manager) Open(ctx context.Context, accountID int64, folder, name string
}
return p.Open(ctx, f, name)
}
+
+// OpenConfigForTest expõe a configuração decifrada (somente para testes).
+func (m *Manager) OpenConfigForTest(a *store.CloudAccount) (AccountConfig, error) {
+ return m.openConfig(a)
+}
+
+var originRE = regexp.MustCompile(`^https?://[A-Za-z0-9.\-]+(:[0-9]{1,5})?$|^https?://\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$`)
+
+func b64(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) }
+
+// BeginWeb prepara o login por popup: devolve o endereço do provedor (que o navegador abre) e o "state" a conferir na volta.
+// origin é a origem da interface do Coruja (a janela que abriu o popup): só ela recebe o código.
+func (m *Manager) BeginWeb(ctx context.Context, name, typ, origin string) (loginURL, state string, err error) {
+ return m.beginWeb(ctx, name, typ, origin, 0)
+}
+
+// BeginWebReauth refaz o login por popup de uma conta já existente (token revogado, por exemplo).
+func (m *Manager) BeginWebReauth(ctx context.Context, id int64, origin string) (loginURL, state string, err error) {
+ a, err := m.Store.GetCloud(ctx, id)
+ if err != nil {
+ return "", "", err
+ }
+ if !m.UsesPopup(ctx, id) {
+ return "", "", errors.New("esta conta não foi conectada pelo login por popup")
+ }
+ return m.beginWeb(ctx, a.Name, a.Type, origin, id)
+}
+
+// UsesPopup informa se a conta foi conectada pelo login por popup (aplicativo padrão "da Web").
+func (m *Manager) UsesPopup(ctx context.Context, id int64) bool {
+ a, err := m.Store.GetCloud(ctx, id)
+ if err != nil {
+ return false
+ }
+ cfg, err := m.openConfig(a)
+ return err == nil && cfg.UseDefault && cfg.Web
+}
+
+func (m *Manager) beginWeb(ctx context.Context, name, typ, origin string, accountID int64) (loginURL, state string, err error) {
+ if !cloud.HasWebApp(typ) {
+ return "", "", errors.New("login por popup indisponível neste Server")
+ }
+ if !originRE.MatchString(origin) {
+ return "", "", errors.New("origem da interface inválida")
+ }
+ if accs, e := m.Store.ListClouds(ctx); e == nil && accountID == 0 {
+ for _, a := range accs {
+ if a.Name == name {
+ return "", "", store.ErrDuplicate
+ }
+ }
+ }
+ nonce, ver := make([]byte, 18), make([]byte, 32)
+ if _, err = rand.Read(nonce); err != nil {
+ return "", "", err
+ }
+ if _, err = rand.Read(ver); err != nil {
+ return "", "", err
+ }
+ state = b64(nonce) + "." + b64([]byte(origin))
+ cfg := AccountConfig{UseDefault: true, Web: true}
+ o, err := m.oauth(typ, cfg)
+ if err != nil {
+ return "", "", err
+ }
+ ch := sha256.Sum256([]byte(b64(ver)))
+ m.mu.Lock()
+ now := m.Now()
+ for k, v := range m.pending { // limpa vencidos e limita o total
+ if now.After(v.Expires) {
+ delete(m.pending, k)
+ }
+ }
+ if len(m.pending) > 50 {
+ m.mu.Unlock()
+ return "", "", errors.New("muitos logins em andamento: tente de novo em instantes")
+ }
+ m.pending[b64(nonce)] = pendingWeb{Name: name, Typ: typ, Origin: origin, Verifier: b64(ver), AccountID: accountID, Expires: now.Add(10 * time.Minute)}
+ m.mu.Unlock()
+ return o.AuthCodeURL(cloud.BrokerRedirect(typ), state, b64(ch[:])), state, nil
+}
+
+// FinishWeb conclui o login por popup: confere o state (uso único), troca o código por tokens e cria a conta já conectada.
+func (m *Manager) FinishWeb(ctx context.Context, state, code string) (int64, error) {
+ i := strings.IndexByte(state, '.')
+ if i < 1 || code == "" || len(code) > 2048 {
+ return 0, errors.New("resposta de login inválida")
+ }
+ nonce := state[:i]
+ m.mu.Lock()
+ p, ok := m.pending[nonce]
+ delete(m.pending, nonce)
+ m.mu.Unlock()
+ if !ok || m.Now().After(p.Expires) {
+ return 0, errors.New("o login expirou ou já foi usado: comece de novo")
+ }
+ if o, e := base64.RawURLEncoding.DecodeString(state[i+1:]); e != nil || string(o) != p.Origin {
+ return 0, errors.New("resposta de login inválida")
+ }
+ cfg := AccountConfig{UseDefault: true, Web: true, HardDelete: p.Typ == cloud.TypeOneDrive}
+ o, err := m.oauth(p.Typ, cfg)
+ if err != nil {
+ return 0, err
+ }
+ tok, err := o.ExchangeCode(ctx, code, p.Verifier, cloud.BrokerRedirect(p.Typ), m.Now())
+ if err != nil {
+ return 0, err
+ }
+ id := p.AccountID
+ if id == 0 {
+ cj, _ := json.Marshal(cfg)
+ sc, err := m.Box.Seal(string(cj))
+ if err != nil {
+ return 0, err
+ }
+ if id, err = m.Store.CreateCloud(ctx, p.Name, p.Typ, sc, ""); err != nil {
+ return 0, err
+ }
+ }
+ tj, _ := json.Marshal(tok)
+ st, err := m.Box.Seal(string(tj))
+ if err != nil {
+ return 0, err
+ }
+ if err := m.Store.SetCloudTokens(ctx, id, st, ""); err != nil {
+ return 0, err
+ }
+ m.Invalidate(id)
+ if _, _, terr := m.Test(ctx, id); terr != nil {
+ _ = m.Store.SetCloudStatus(ctx, id, "error", terr.Error())
+ return id, terr
+ }
+ return id, nil
+}
diff --git a/internal/e2e/e2e_test.go b/internal/e2e/e2e_test.go
index 3057048..de7d275 100644
--- a/internal/e2e/e2e_test.go
+++ b/internal/e2e/e2e_test.go
@@ -6,9 +6,13 @@ import (
"bytes"
"compress/gzip"
"context"
+ "crypto/sha256"
+ "encoding/base64"
+ "errors"
"io"
"log/slog"
"net"
+ "net/url"
"os"
"path/filepath"
"strings"
@@ -516,3 +520,241 @@ func TestReenvioParaNuvemExtracaoEDownload(t *testing.T) {
t.Fatalf("deveria recusar sobrescrever:\n%s", r.logs(fixed))
}
}
+
+// Com o aplicativo padrão compilado, a conta não guarda credenciais e funciona de ponta a ponta; sem ele, o modo some.
+func TestGoogleDriveComAplicativoPadrao(t *testing.T) {
+ oldID, oldSec := cloud.DefaultGoogleClientID, cloud.DefaultGoogleClientSecret
+ defer func() { cloud.DefaultGoogleClientID, cloud.DefaultGoogleClientSecret = oldID, oldSec }()
+ cloud.DefaultGoogleClientID, cloud.DefaultGoogleClientSecret = "gid", "segredo-compilado"
+
+ fake := cloudtest.NewDrive("gid")
+ defer fake.Close()
+ r := newRig(t, cloudmgr.Endpoints{GDevice: fake.URL + "/device/code", GToken: fake.URL + "/token", GAPI: fake.APIURL(), GUpload: fake.UploadURL()})
+ cid := r.connectCloud(cloud.TypeGDrive, cloudmgr.AccountConfig{}) // sem ID nem segredo
+ acc, err := r.st.GetCloud(context.Background(), cid)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cfg, _ := r.mgr.OpenConfigForTest(acc)
+ if !cfg.UseDefault || cfg.ClientID != "" || cfg.ClientSecret != "" {
+ t.Fatalf("a conta não deve gravar credenciais: %+v", cfg)
+ }
+ jid := r.newJob("gd-padrao", cid, 2, 3)
+ if run := r.runNow(jid); run.Status != "ok" || run.CloudStatus != "ok" || run.CloudVerifiedBy != "md5" {
+ t.Fatalf("execução: %+v\n%s", run, r.logs(run))
+ }
+
+ // sem aplicativo padrão compilado: pedir conta sem credenciais é recusado com mensagem clara
+ cloud.DefaultGoogleClientSecret = ""
+ if _, _, err := r.mgr.Create(context.Background(), "sem-padrao", cloud.TypeGDrive, cloudmgr.AccountConfig{}); err == nil || !strings.Contains(err.Error(), "Client ID") {
+ t.Fatalf("esperava erro pedindo o Client ID: %v", err)
+ }
+ // uma conta criada no modo padrão não consegue renovar sem o aplicativo compilado
+ r.mgr.Invalidate(cid)
+ if _, err := r.mgr.Provider(context.Background(), cid); err == nil {
+ t.Fatal("sem o aplicativo padrão a conta deveria falhar de forma explícita")
+ }
+}
+
+// Login por popup: o Server gera o endereço do provedor (PKCE, state ligado à origem), recebe o código entregue pela página
+// de retorno e cria a conta já conectada, usando o aplicativo "da Web" compilado e sem gravar credenciais.
+func TestGoogleDriveLoginPorPopup(t *testing.T) {
+ oID, oSec, oBroker := cloud.DefaultGoogleWebClientID, cloud.DefaultGoogleWebClientSecret, cloud.OAuthBrokerURL
+ defer func() {
+ cloud.DefaultGoogleWebClientID, cloud.DefaultGoogleWebClientSecret, cloud.OAuthBrokerURL = oID, oSec, oBroker
+ }()
+ cloud.DefaultGoogleWebClientID, cloud.DefaultGoogleWebClientSecret, cloud.OAuthBrokerURL = "gid", "seg-web", "https://broker.exemplo.test"
+
+ fake := cloudtest.NewDrive("gid")
+ defer fake.Close()
+ r := newRig(t, cloudmgr.Endpoints{GDevice: fake.URL + "/device/code", GToken: fake.URL + "/token", GAPI: fake.APIURL(), GUpload: fake.UploadURL()})
+ ctx := context.Background()
+
+ for _, bad := range []string{"javascript:alert(1)", "http://evil.test/caminho", "ftp://x", "http://a b", ""} {
+ if _, _, err := r.mgr.BeginWeb(ctx, "gd-web", cloud.TypeGDrive, bad); err == nil {
+ t.Fatalf("origem %q deveria ser recusada", bad)
+ }
+ }
+ const origin = "http://187.110.161.52:8081"
+ loginURL, state, err := r.mgr.BeginWeb(ctx, "gd-web", cloud.TypeGDrive, origin)
+ if err != nil {
+ t.Fatal(err)
+ }
+ u, _ := url.Parse(loginURL)
+ q := u.Query()
+ if u.Host != "accounts.google.com" || q.Get("client_id") != "gid" || q.Get("redirect_uri") != "https://broker.exemplo.test/oauth/google/callback" ||
+ q.Get("code_challenge_method") != "S256" || q.Get("access_type") != "offline" || q.Get("state") != state || strings.Contains(loginURL, "seg-web") {
+ t.Fatalf("endereço de login: %s", loginURL)
+ }
+ if o, _ := base64.RawURLEncoding.DecodeString(state[strings.IndexByte(state, '.')+1:]); string(o) != origin {
+ t.Fatalf("o state deve carregar a origem: %q", o)
+ }
+
+ // state adulterado (outra origem) e código errado não criam nada; o state é de uso único
+ forged := state[:strings.IndexByte(state, '.')+1] + base64.RawURLEncoding.EncodeToString([]byte("http://evil.test"))
+ if _, err := r.mgr.FinishWeb(ctx, forged, "codigo-ok"); err == nil {
+ t.Fatal("origem diferente da registrada deveria falhar")
+ }
+ if _, err := r.mgr.FinishWeb(ctx, state, "codigo-ok"); err == nil {
+ t.Fatal("o state já foi consumido pela tentativa anterior")
+ }
+ _, state, _ = r.mgr.BeginWeb(ctx, "gd-web", cloud.TypeGDrive, origin)
+ if _, err := r.mgr.FinishWeb(ctx, state, "codigo-errado"); err == nil {
+ t.Fatal("código recusado pelo provedor deveria falhar")
+ }
+ if accs, _ := r.st.ListClouds(ctx); len(accs) != 0 {
+ t.Fatalf("nenhuma conta deveria existir ainda: %d", len(accs))
+ }
+
+ loginURL, state, _ = r.mgr.BeginWeb(ctx, "gd-web", cloud.TypeGDrive, origin)
+ q = mustParse(t, loginURL).Query()
+ id, err := r.mgr.FinishWeb(ctx, state, "codigo-ok")
+ if err != nil {
+ t.Fatal(err)
+ }
+ sum := sha256.Sum256([]byte(fake.LastVerifier))
+ if base64.RawURLEncoding.EncodeToString(sum[:]) != q.Get("code_challenge") || fake.LastSecret != "seg-web" || fake.LastRedirect != "https://broker.exemplo.test/oauth/google/callback" {
+ t.Fatalf("troca do código: verificador=%q segredo=%q redirect=%q", fake.LastVerifier, fake.LastSecret, fake.LastRedirect)
+ }
+ acc, _ := r.st.GetCloud(ctx, id)
+ cfg, _ := r.mgr.OpenConfigForTest(acc)
+ if acc.Status != "connected" || !cfg.UseDefault || !cfg.Web || cfg.ClientID != "" || cfg.ClientSecret != "" {
+ t.Fatalf("conta: status=%s cfg=%+v", acc.Status, cfg)
+ }
+ if _, err := r.mgr.FinishWeb(ctx, state, "codigo-ok"); err == nil {
+ t.Fatal("reutilizar o state deveria falhar")
+ }
+ // nome repetido é recusado antes de abrir o popup
+ if _, _, err := r.mgr.BeginWeb(ctx, "gd-web", cloud.TypeGDrive, origin); !errors.Is(err, store.ErrDuplicate) {
+ t.Fatalf("nome repetido: %v", err)
+ }
+ // e a conta funciona de ponta a ponta
+ jid := r.newJob("gd-web-job", id, 2, 3)
+ if run := r.runNow(jid); run.Status != "ok" || run.CloudStatus != "ok" {
+ t.Fatalf("execução: %+v\n%s", run, r.logs(run))
+ }
+}
+
+func mustParse(t *testing.T, s string) *url.URL {
+ t.Helper()
+ u, err := url.Parse(s)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return u
+}
+
+// OneDrive pelo popup: cliente público (sem segredo), retorno em /oauth/microsoft/callback e conta funcionando.
+func TestOneDriveLoginPorPopup(t *testing.T) {
+ oID, oBroker := cloud.DefaultMicrosoftClientID, cloud.OAuthBrokerURL
+ defer func() { cloud.DefaultMicrosoftClientID, cloud.OAuthBrokerURL = oID, oBroker }()
+ cloud.DefaultMicrosoftClientID, cloud.OAuthBrokerURL = "cid", "https://broker.exemplo.test"
+
+ fake := cloudtest.NewGraph("cid")
+ defer fake.Close()
+ r := newRig(t, cloudmgr.Endpoints{MSDevice: fake.URL + "/devicecode", MSToken: fake.URL + "/token", Graph: fake.GraphURL()})
+ ctx := context.Background()
+ loginURL, state, err := r.mgr.BeginWeb(ctx, "od-web", cloud.TypeOneDrive, "http://187.110.161.52:8081")
+ if err != nil {
+ t.Fatal(err)
+ }
+ u := mustParse(t, loginURL)
+ q := u.Query()
+ if u.Host != "login.microsoftonline.com" || !strings.HasSuffix(u.Path, "/common/oauth2/v2.0/authorize") || q.Get("client_id") != "cid" ||
+ q.Get("redirect_uri") != "https://broker.exemplo.test/oauth/microsoft/callback" || !strings.Contains(q.Get("scope"), "offline_access") || q.Get("code_challenge_method") != "S256" {
+ t.Fatalf("endereço de login: %s", loginURL)
+ }
+ id, err := r.mgr.FinishWeb(ctx, state, "codigo-ok")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if fake.LastSecret != "" || fake.LastRedirect != "https://broker.exemplo.test/oauth/microsoft/callback" || fake.LastVerifier == "" {
+ t.Fatalf("troca do código: segredo=%q redirect=%q verificador=%q", fake.LastSecret, fake.LastRedirect, fake.LastVerifier)
+ }
+ acc, _ := r.st.GetCloud(ctx, id)
+ cfg, _ := r.mgr.OpenConfigForTest(acc)
+ if acc.Status != "connected" || !cfg.UseDefault || !cfg.Web || cfg.ClientID != "" {
+ t.Fatalf("conta: %s %+v", acc.Status, cfg)
+ }
+ jid := r.newJob("od-web-job", id, 2, 3)
+ if run := r.runNow(jid); run.Status != "ok" || run.CloudStatus != "ok" {
+ t.Fatalf("execução: %+v\n%s", run, r.logs(run))
+ }
+}
+
+// Dropbox de ponta a ponta: popup (cliente público), envio em partes com token só de escrita, retomada, conferência por
+// content_hash, retenção, download e detecção de arquivo corrompido na nuvem.
+func TestDropboxDePontaAPonta(t *testing.T) {
+ oKey, oBroker := cloud.DefaultDropboxAppKey, cloud.OAuthBrokerURL
+ defer func() { cloud.DefaultDropboxAppKey, cloud.OAuthBrokerURL = oKey, oBroker }()
+ cloud.DefaultDropboxAppKey, cloud.OAuthBrokerURL = "dbxkey", "https://broker.exemplo.test"
+
+ fake := cloudtest.NewDropbox("dbxkey")
+ defer fake.Close()
+ r := newRig(t, cloudmgr.Endpoints{DBXToken: fake.URL + "/oauth2/token", DBXAPI: fake.URL + "/2", DBXContent: fake.URL + "/2"})
+ ctx := context.Background()
+
+ loginURL, state, err := r.mgr.BeginWeb(ctx, "dbx", cloud.TypeDropbox, "http://187.110.161.52:8081")
+ if err != nil {
+ t.Fatal(err)
+ }
+ u := mustParse(t, loginURL)
+ q := u.Query()
+ if u.Host != "www.dropbox.com" || q.Get("client_id") != "dbxkey" || q.Get("token_access_type") != "offline" ||
+ q.Get("redirect_uri") != "https://broker.exemplo.test/oauth/dropbox/callback" || q.Get("code_challenge_method") != "S256" ||
+ strings.Contains(q.Get("scope"), "account_info.write") {
+ t.Fatalf("endereço de login: %s", loginURL)
+ }
+ id, err := r.mgr.FinishWeb(ctx, state, "codigo-ok")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if fake.LastSecret != "" || fake.LastVerifier == "" {
+ t.Fatalf("cliente público: segredo=%q verificador=%q", fake.LastSecret, fake.LastVerifier)
+ }
+ acc, _ := r.st.GetCloud(ctx, id)
+ if acc.Status != "connected" || acc.AccountLabel != "dono@dropbox.test" {
+ t.Fatalf("conta: %+v", acc)
+ }
+
+ jid := r.newJob("dbx-job", id, 2, 2)
+ fake.LoseAppendReply = true // arquivo pequeno não tem append; o teste de retomada em partes está no uploader
+ run := r.runNow(jid)
+ if run.Status != "ok" || run.CloudStatus != "ok" || run.CloudVerifiedBy != "dropbox" {
+ t.Fatalf("execução: %+v\n%s", run, r.logs(run))
+ }
+ if len(fake.ScopesIssued) == 0 || fake.ScopesIssued[0] != "files.content.write" {
+ t.Fatalf("o token do agente deve ser só de escrita: %v", fake.ScopesIssued)
+ }
+ time.Sleep(1100 * time.Millisecond)
+ r.runNow(jid)
+ time.Sleep(1100 * time.Millisecond)
+ if run = r.runNow(jid); run.Status != "ok" {
+ t.Fatalf("terceira execução: %+v\n%s", run, r.logs(run))
+ }
+ folder := "Coruja Backup/srv-e2e/dbx-job"
+ if n := fake.Names(folder); len(n) != 2 {
+ t.Fatalf("retenção na nuvem deve manter 2: %v (%v)", n, r.logs(run))
+ }
+ rc, _, err := r.mgr.Open(ctx, id, folder, fake.Names(folder)[1])
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, _ := io.ReadAll(rc)
+ rc.Close()
+ if !bytes.HasPrefix(got, []byte{0x1f, 0x8b}) {
+ t.Fatal("o download deveria ser um gzip")
+ }
+
+ // arquivo corrompido na nuvem: a execução falha e as cópias boas são preservadas
+ before := fake.Names(folder)
+ fake.CorruptUpload = true
+ time.Sleep(1100 * time.Millisecond)
+ bad := r.runNow(jid)
+ if bad.Status != "failed" || !strings.Contains(bad.Error, "content_hash") {
+ t.Fatalf("corrompido: %+v\n%s", bad, r.logs(bad))
+ }
+ if after := fake.Names(folder); len(after) != len(before) {
+ t.Fatalf("as cópias antigas deveriam ficar: antes %v depois %v", before, after)
+ }
+}
diff --git a/internal/httpapi/handlers_cloud.go b/internal/httpapi/handlers_cloud.go
index 57e116b..f507891 100644
--- a/internal/httpapi/handlers_cloud.go
+++ b/internal/httpapi/handlers_cloud.go
@@ -16,7 +16,8 @@ var cloudNameRE = regexp.MustCompile(`^[\p{L}\p{N}._(][\p{L}\p{N}._ ()&,'-]{1,99
type cloudView struct {
store.CloudAccount
- Jobs int `json:"jobs"`
+ Jobs int `json:"jobs"`
+ Popup bool `json:"popup"`
}
func (s *Server) listClouds(w http.ResponseWriter, r *http.Request, _ *ctxUser) {
@@ -28,9 +29,9 @@ func (s *Server) listClouds(w http.ResponseWriter, r *http.Request, _ *ctxUser)
out := make([]cloudView, 0, len(accs))
for _, a := range accs {
n, _ := s.Store.JobsUsingCloud(r.Context(), a.ID)
- out = append(out, cloudView{a, n})
+ out = append(out, cloudView{a, n, s.Clouds != nil && s.Clouds.UsesPopup(r.Context(), a.ID)})
}
- writeJSON(w, 200, map[string]any{"accounts": out})
+ writeJSON(w, 200, map[string]any{"accounts": out, "defaults": map[string]any{"gdrive": cloud.HasDefaultApp(cloud.TypeGDrive), "gdrive_web": cloud.HasWebApp(cloud.TypeGDrive), "onedrive_web": cloud.HasWebApp(cloud.TypeOneDrive), "dropbox_web": cloud.HasWebApp(cloud.TypeDropbox), "broker": strings.TrimRight(cloud.OAuthBrokerURL, "/")}})
}
func deviceView(d *cloud.Device) map[string]any {
@@ -162,3 +163,63 @@ func (s *Server) deleteCloud(w http.ResponseWriter, r *http.Request, cu *ctxUser
}
func itoa64(i int64) string { return strconv.FormatInt(i, 10) }
+
+// beginCloudWeb inicia o login por popup: devolve o endereço do provedor para o navegador abrir.
+func (s *Server) beginCloudWeb(w http.ResponseWriter, r *http.Request, cu *ctxUser) {
+ if s.Clouds == nil {
+ writeErr(w, 503, "nuvem indisponível")
+ return
+ }
+ var in struct {
+ Name string `json:"name"`
+ Type string `json:"type"`
+ Origin string `json:"origin"`
+ AccountID int64 `json:"account_id"` // reautorização de uma conta existente
+ }
+ if !decode(w, r, &in) {
+ return
+ }
+ var u, state string
+ var err error
+ if in.AccountID > 0 {
+ u, state, err = s.Clouds.BeginWebReauth(r.Context(), in.AccountID, in.Origin)
+ } else {
+ in.Name = strings.TrimSpace(in.Name)
+ if !cloudNameRE.MatchString(in.Name) {
+ writeErr(w, 400, "nome inválido: use 2 a 100 caracteres (letras, números, espaço, ponto, hífen ou sublinhado)")
+ return
+ }
+ u, state, err = s.Clouds.BeginWeb(r.Context(), in.Name, in.Type, in.Origin)
+ }
+ if errors.Is(err, store.ErrDuplicate) {
+ writeErr(w, 409, "já existe uma conta de nuvem com esse nome")
+ return
+ }
+ if err != nil {
+ writeErr(w, 400, err.Error())
+ return
+ }
+ writeJSON(w, 200, map[string]any{"url": u, "state": state})
+}
+
+// finishCloudWeb recebe o código entregue pela janela do popup e conclui a conexão.
+func (s *Server) finishCloudWeb(w http.ResponseWriter, r *http.Request, cu *ctxUser) {
+ if s.Clouds == nil {
+ writeErr(w, 503, "nuvem indisponível")
+ return
+ }
+ var in struct {
+ State string `json:"state"`
+ Code string `json:"code"`
+ }
+ if !decode(w, r, &in) {
+ return
+ }
+ id, err := s.Clouds.FinishWeb(r.Context(), in.State, in.Code)
+ if err != nil {
+ writeErr(w, 400, err.Error())
+ return
+ }
+ s.Store.Audit(r.Context(), cu.User.ID, cu.User.Username, "cloud.connected", itoa64(id), s.clientIP(r))
+ writeJSON(w, 201, map[string]any{"id": id})
+}
diff --git a/internal/httpapi/httpapi.go b/internal/httpapi/httpapi.go
index 4d84c6d..161e4dc 100644
--- a/internal/httpapi/httpapi.go
+++ b/internal/httpapi/httpapi.go
@@ -45,6 +45,10 @@ type CloudAdmin interface {
PollDevice(ctx context.Context, id int64) (string, *cloud.Device, error)
Test(ctx context.Context, id int64) (string, cloud.Quota, error)
Invalidate(id int64)
+ BeginWeb(ctx context.Context, name, typ, origin string) (loginURL, state string, err error)
+ BeginWebReauth(ctx context.Context, id int64, origin string) (loginURL, state string, err error)
+ UsesPopup(ctx context.Context, id int64) bool
+ FinishWeb(ctx context.Context, state, code string) (int64, error)
Open(ctx context.Context, accountID int64, folder, name string) (io.ReadCloser, int64, error)
}
@@ -142,6 +146,8 @@ func (s *Server) Routes() http.Handler {
mux.HandleFunc("GET /api/reports/daily.pdf", s.authed(roleOperator, s.dailyPDF))
mux.HandleFunc("GET /api/clouds", s.authed(roleAny, s.listClouds))
mux.HandleFunc("POST /api/clouds", s.authed(roleAdmin, s.createCloud))
+ mux.HandleFunc("POST /api/clouds/oauth/begin", s.authed(roleAdmin, s.beginCloudWeb))
+ mux.HandleFunc("POST /api/clouds/oauth/finish", s.authed(roleAdmin, s.finishCloudWeb))
mux.HandleFunc("POST /api/clouds/{id}/poll", s.authed(roleAdmin, s.pollCloud))
mux.HandleFunc("POST /api/clouds/{id}/reauthorize", s.authed(roleAdmin, s.reauthCloud))
mux.HandleFunc("POST /api/clouds/{id}/test", s.authed(roleOperator, s.testCloud))
diff --git a/internal/httpapi/httpapi_test.go b/internal/httpapi/httpapi_test.go
index 4da1d6d..9c02135 100644
--- a/internal/httpapi/httpapi_test.go
+++ b/internal/httpapi/httpapi_test.go
@@ -561,6 +561,19 @@ func (f *fakeClouds) Test(context.Context, int64) (string, cloud.Quota, error) {
return "fulano@x.com", cloud.Quota{Total: 100, Used: 10}, nil
}
func (f *fakeClouds) Invalidate(int64) {}
+func (f *fakeClouds) BeginWeb(_ context.Context, name, typ, origin string) (string, string, error) {
+ return "https://login.test/?o=" + origin, "nonce." + name, nil
+}
+func (f *fakeClouds) BeginWebReauth(_ context.Context, id int64, origin string) (string, string, error) {
+ return "https://login.test/?re=1", "nonce.re", nil
+}
+func (f *fakeClouds) UsesPopup(context.Context, int64) bool { return false }
+func (f *fakeClouds) FinishWeb(_ context.Context, state, code string) (int64, error) {
+ if code != "ok" {
+ return 0, errors.New("código inválido")
+ }
+ return 42, nil
+}
func (f *fakeClouds) Open(context.Context, int64, string, string) (io.ReadCloser, int64, error) {
return io.NopCloser(strings.NewReader("conteudo-do-backup")), 18, nil
}
diff --git a/internal/notify/service_test.go b/internal/notify/service_test.go
index d069925..646334c 100644
--- a/internal/notify/service_test.go
+++ b/internal/notify/service_test.go
@@ -38,7 +38,7 @@ func newRig(t *testing.T) *rig {
r.svc.Log = slog.New(slog.NewTextHandler(io.Discard, nil))
ctx := context.Background()
h := auth.SHA256Hex("tok")
- st.CreateEnrollToken(ctx, h, "srv-n", 0, r.now.Add(time.Hour))
+ st.CreateEnrollToken(ctx, h, "srv-n", 0, time.Now().UTC().Add(time.Hour)) // o banco compara com o relógio real
a, err := st.Enroll(ctx, h, "host", "linux", "amd64", "0.0.7", "10.0.0.1", auth.SHA256Hex("c"))
if err != nil {
t.Fatal(err)
diff --git a/internal/pb/agent.pb.go b/internal/pb/agent.pb.go
index 4858bd8..034381a 100644
--- a/internal/pb/agent.pb.go
+++ b/internal/pb/agent.pb.go
@@ -1575,11 +1575,13 @@ type UploadSession struct {
RequestId string `protobuf:"bytes,1,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"`
Ok bool `protobuf:"varint,2,opt,name=ok,proto3" json:"ok,omitempty"`
Error string `protobuf:"bytes,3,opt,name=error,proto3" json:"error,omitempty"`
- Protocol string `protobuf:"bytes,4,opt,name=protocol,proto3" json:"protocol,omitempty"` // "graph" (OneDrive) | "gdrive" (Google Drive)
+ Protocol string `protobuf:"bytes,4,opt,name=protocol,proto3" json:"protocol,omitempty"` // "graph" (OneDrive) | "gdrive" (Google Drive) | "dropbox"
Url string `protobuf:"bytes,5,opt,name=url,proto3" json:"url,omitempty"` // URL da sessão (já autenticada; o agente não recebe tokens)
ChunkSize int64 `protobuf:"varint,6,opt,name=chunk_size,json=chunkSize,proto3" json:"chunk_size,omitempty"`
ExpiresUnixMs int64 `protobuf:"varint,7,opt,name=expires_unix_ms,json=expiresUnixMs,proto3" json:"expires_unix_ms,omitempty"`
RemotePath string `protobuf:"bytes,8,opt,name=remote_path,json=remotePath,proto3" json:"remote_path,omitempty"`
+ Token string `protobuf:"bytes,9,opt,name=token,proto3" json:"token,omitempty"` // só "dropbox": token de curta duração, só de escrita de conteúdo, na pasta do aplicativo
+ UploadPath string `protobuf:"bytes,10,opt,name=upload_path,json=uploadPath,proto3" json:"upload_path,omitempty"` // só "dropbox": caminho de destino
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -1670,6 +1672,20 @@ func (x *UploadSession) GetRemotePath() string {
return ""
}
+func (x *UploadSession) GetToken() string {
+ if x != nil {
+ return x.Token
+ }
+ return ""
+}
+
+func (x *UploadSession) GetUploadPath() string {
+ if x != nil {
+ return x.UploadPath
+ }
+ return ""
+}
+
type UploadDone struct {
state protoimpl.MessageState `protogen:"open.v1"`
RequestId string `protobuf:"bytes,1,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"`
@@ -1684,6 +1700,7 @@ type UploadDone struct {
RemoteId string `protobuf:"bytes,10,opt,name=remote_id,json=remoteId,proto3" json:"remote_id,omitempty"`
Ok bool `protobuf:"varint,11,opt,name=ok,proto3" json:"ok,omitempty"`
Error string `protobuf:"bytes,12,opt,name=error,proto3" json:"error,omitempty"`
+ DropboxHash string `protobuf:"bytes,13,opt,name=dropbox_hash,json=dropboxHash,proto3" json:"dropbox_hash,omitempty"` // content_hash do Dropbox
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -1802,6 +1819,13 @@ func (x *UploadDone) GetError() string {
return ""
}
+func (x *UploadDone) GetDropboxHash() string {
+ if x != nil {
+ return x.DropboxHash
+ }
+ return ""
+}
+
type UploadVerdict struct {
state protoimpl.MessageState `protogen:"open.v1"`
RequestId string `protobuf:"bytes,1,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"`
@@ -2509,7 +2533,7 @@ const file_coruja_v1_agent_proto_rawDesc = "" +
"\arun_uid\x18\x02 \x01(\tR\x06runUid\x12\x15\n" +
"\x06job_id\x18\x03 \x01(\x03R\x05jobId\x12\x1b\n" +
"\tfile_name\x18\x04 \x01(\tR\bfileName\x12\x12\n" +
- "\x04size\x18\x05 \x01(\x03R\x04size\"\xea\x01\n" +
+ "\x04size\x18\x05 \x01(\x03R\x04size\"\xa1\x02\n" +
"\rUploadSession\x12\x1d\n" +
"\n" +
"request_id\x18\x01 \x01(\tR\trequestId\x12\x0e\n" +
@@ -2521,7 +2545,11 @@ const file_coruja_v1_agent_proto_rawDesc = "" +
"chunk_size\x18\x06 \x01(\x03R\tchunkSize\x12&\n" +
"\x0fexpires_unix_ms\x18\a \x01(\x03R\rexpiresUnixMs\x12\x1f\n" +
"\vremote_path\x18\b \x01(\tR\n" +
- "remotePath\"\xa9\x02\n" +
+ "remotePath\x12\x14\n" +
+ "\x05token\x18\t \x01(\tR\x05token\x12\x1f\n" +
+ "\vupload_path\x18\n" +
+ " \x01(\tR\n" +
+ "uploadPath\"\xcc\x02\n" +
"\n" +
"UploadDone\x12\x1d\n" +
"\n" +
@@ -2537,7 +2565,8 @@ const file_coruja_v1_agent_proto_rawDesc = "" +
"\tremote_id\x18\n" +
" \x01(\tR\bremoteId\x12\x0e\n" +
"\x02ok\x18\v \x01(\bR\x02ok\x12\x14\n" +
- "\x05error\x18\f \x01(\tR\x05error\"\xe0\x01\n" +
+ "\x05error\x18\f \x01(\tR\x05error\x12!\n" +
+ "\fdropbox_hash\x18\r \x01(\tR\vdropboxHash\"\xe0\x01\n" +
"\rUploadVerdict\x12\x1d\n" +
"\n" +
"request_id\x18\x01 \x01(\tR\trequestId\x12\x0e\n" +
diff --git a/internal/uploader/dropbox.go b/internal/uploader/dropbox.go
new file mode 100644
index 0000000..81fbadf
--- /dev/null
+++ b/internal/uploader/dropbox.go
@@ -0,0 +1,170 @@
+package uploader
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/AprendendoLinux/corujabackup/internal/cloud"
+)
+
+// uploadDropbox envia em partes por uma sessão de upload do Dropbox (start, append_v2, finish). Retoma pelo
+// "correct_offset" quando o Dropbox diz ter recebido outra quantidade. O token é de curta duração: se vencer, devolve
+// ErrSessionExpired para o agente pedir um novo.
+func uploadDropbox(ctx context.Context, s Session, f *os.File, res Result, total int64, opt Options) (Result, error) {
+ chunk := s.ChunkSize
+ if chunk <= 0 {
+ chunk = 8 << 20
+ }
+ retries := opt.Retries
+ if retries <= 0 {
+ retries = 6
+ }
+ base := strings.TrimRight(s.URL, "/")
+ buf := make([]byte, chunk)
+ var offset int64
+ var id string
+ attempt := 0
+ for {
+ if ctx.Err() != nil {
+ return res, ctx.Err()
+ }
+ n := min(chunk, total-offset)
+ if n > 0 {
+ if _, err := f.ReadAt(buf[:n], offset); err != nil && err != io.EOF {
+ return res, err
+ }
+ }
+ data := buf[:max(n, 0)]
+ last := offset+int64(len(data)) >= total
+ var url string
+ var arg any
+ switch {
+ case id == "":
+ url, arg = base+"/start", map[string]any{"close": false}
+ case !last:
+ url, arg = base+"/append_v2", map[string]any{"cursor": map[string]any{"session_id": id, "offset": offset}, "close": false}
+ default:
+ url = base + "/finish"
+ arg = map[string]any{"cursor": map[string]any{"session_id": id, "offset": offset},
+ "commit": map[string]any{"path": s.Path, "mode": "overwrite", "autorename": false, "mute": true}}
+ }
+ body, correct, err := dbxPost(ctx, opt.client(), url, s.Token, arg, data)
+ if err == nil {
+ attempt = 0
+ if id == "" {
+ var r struct {
+ ID string `json:"session_id"`
+ }
+ if json.Unmarshal(body, &r) != nil || r.ID == "" {
+ return res, errors.New("o Dropbox não devolveu a sessão de upload")
+ }
+ id = r.ID
+ offset += int64(len(data))
+ } else if !last {
+ offset += int64(len(data))
+ } else {
+ return finishDropbox(body, res, total)
+ }
+ if opt.Progress != nil {
+ opt.Progress(min(offset, total), total)
+ }
+ continue
+ }
+ if correct >= 0 && correct <= total { // o Dropbox sabe até onde recebeu: continua dali
+ offset = correct
+ attempt++
+ } else if errors.Is(err, errRetry) {
+ attempt++
+ opt.sleep(ctx, backoff(attempt))
+ } else {
+ return res, err
+ }
+ if attempt > retries {
+ return res, fmt.Errorf("o envio falhou após %d tentativas: %w", retries, err)
+ }
+ }
+}
+
+// dbxPost devolve o corpo (HTTP 200) ou um erro; correct >= 0 quando o Dropbox informa o deslocamento certo.
+func dbxPost(ctx context.Context, c *http.Client, url, token string, arg any, data []byte) (body []byte, correct int64, err error) {
+ req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(data))
+ if err != nil {
+ return nil, -1, err
+ }
+ req.ContentLength = int64(len(data))
+ req.Header.Set("Authorization", "Bearer "+token)
+ req.Header.Set("Content-Type", "application/octet-stream")
+ req.Header.Set("Dropbox-API-Arg", cloud.ASCIIJSON(arg))
+ resp, err := c.Do(req)
+ if err != nil {
+ if ctx.Err() != nil {
+ return nil, -1, ctx.Err()
+ }
+ return nil, -1, fmt.Errorf("%w: %w", errRetry, err)
+ }
+ defer resp.Body.Close()
+ b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
+ if resp.StatusCode == 200 {
+ return b, -1, nil
+ }
+ var e struct {
+ Summary string `json:"error_summary"`
+ Error struct {
+ Tag string `json:".tag"`
+ Correct *int64 `json:"correct_offset"`
+ Lookup *struct {
+ Correct *int64 `json:"correct_offset"`
+ } `json:"lookup_failed"`
+ } `json:"error"`
+ }
+ _ = json.Unmarshal(b, &e)
+ switch {
+ case resp.StatusCode == 401:
+ return nil, -1, ErrSessionExpired // token de curta duração vencido
+ case resp.StatusCode == 409 && e.Error.Correct != nil:
+ return nil, *e.Error.Correct, fmt.Errorf("deslocamento incorreto: %s", e.Summary)
+ case resp.StatusCode == 409 && e.Error.Lookup != nil && e.Error.Lookup.Correct != nil:
+ return nil, *e.Error.Lookup.Correct, fmt.Errorf("deslocamento incorreto: %s", e.Summary)
+ case resp.StatusCode == 409 && strings.Contains(e.Summary, "not_found"):
+ return nil, -1, ErrSessionExpired
+ case retryable(resp.StatusCode):
+ if sec, perr := strconv.Atoi(resp.Header.Get("Retry-After")); perr == nil && sec > 0 && sec <= 120 {
+ time.Sleep(time.Duration(sec) * time.Second)
+ }
+ return nil, -1, fmt.Errorf("%w: HTTP %d", errRetry, resp.StatusCode)
+ }
+ return nil, -1, fmt.Errorf("a nuvem recusou o envio: HTTP %d %s", resp.StatusCode, trim(string(b)))
+}
+
+func finishDropbox(body []byte, res Result, total int64) (Result, error) {
+ var d struct {
+ ID string `json:"id"`
+ Size int64 `json:"size"`
+ Hash string `json:"content_hash"`
+ }
+ if err := json.Unmarshal(body, &d); err != nil {
+ return res, fmt.Errorf("resposta final inválida: %w", err)
+ }
+ res.RemoteID, res.RemoteSize, res.RemoteDropbox = d.ID, d.Size, d.Hash
+ if d.Size != total {
+ return res, fmt.Errorf("%w: a nuvem guardou %d bytes, esperado %d", ErrMismatch, d.Size, total)
+ }
+ if d.Hash == "" {
+ res.VerifiedBy = "size"
+ return res, nil
+ }
+ if d.Hash != res.Digest.Dropbox {
+ return res, fmt.Errorf("%w: o content_hash do Dropbox difere do arquivo enviado", ErrMismatch)
+ }
+ res.VerifiedBy = "dropbox"
+ return res, nil
+}
diff --git a/internal/uploader/dropbox_test.go b/internal/uploader/dropbox_test.go
new file mode 100644
index 0000000..e01086e
--- /dev/null
+++ b/internal/uploader/dropbox_test.go
@@ -0,0 +1,52 @@
+package uploader
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "errors"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/AprendendoLinux/corujabackup/internal/cloud"
+ "github.com/AprendendoLinux/corujabackup/internal/cloud/cloudtest"
+)
+
+func TestDropboxEnvioEmPartesRetomaEExpira(t *testing.T) {
+ fake := cloudtest.NewDropbox("k")
+ defer fake.Close()
+ o := cloud.DropboxOAuth("k", "")
+ o.TokenURL = fake.URL + "/oauth2/token"
+ tok, err := o.RefreshScoped(context.Background(), "dbx-refresh", cloud.DropboxAgentScope, time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ data := make([]byte, 13<<20+123)
+ _, _ = rand.Read(data)
+ p := filepath.Join(t.TempDir(), "a.bin")
+ if err := os.WriteFile(p, data, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ sess := Session{Protocol: "dropbox", URL: fake.URL + "/2/files/upload_session", ChunkSize: 4 << 20, Token: tok.Access, Path: "/Backups ção/x.bin"}
+ opt := Options{Sleep: func(context.Context, time.Duration) {}}
+ fake.FailAppends, fake.LoseAppendReply = 2, true // 2 falhas e uma resposta perdida (o Dropbox devolve correct_offset)
+ var last int64
+ opt.Progress = func(s, _ int64) { last = s }
+ res, err := Upload(context.Background(), sess, p, opt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if res.VerifiedBy != "dropbox" || !bytes.Equal(fake.Files["/Backups ção/x.bin"], data) || last == 0 {
+ t.Fatalf("resultado: %+v (%d bytes gravados)", res, len(fake.Files["/Backups ção/x.bin"]))
+ }
+ sess.Token = "vencido"
+ if _, err := Upload(context.Background(), sess, p, opt); !errors.Is(err, ErrSessionExpired) {
+ t.Fatalf("token vencido deveria pedir nova sessão: %v", err)
+ }
+ sess.Protocol = "inventado"
+ if _, err := Upload(context.Background(), sess, p, opt); err == nil {
+ t.Fatal("protocolo desconhecido deveria falhar")
+ }
+}
diff --git a/internal/uploader/uploader.go b/internal/uploader/uploader.go
index a971a47..87cf877 100644
--- a/internal/uploader/uploader.go
+++ b/internal/uploader/uploader.go
@@ -19,9 +19,11 @@ import (
)
type Session struct {
- Protocol string // "graph" | "gdrive"
+ Protocol string // "graph" | "gdrive" | "dropbox"
URL string
ChunkSize int64
+ Token string // só "dropbox"
+ Path string // só "dropbox"
}
type Result struct {
@@ -30,13 +32,16 @@ type Result struct {
RemoteMD5 string
RemoteSHA1 string
RemoteQuickXor string
+ RemoteDropbox string
Digest cloud.Digest
- VerifiedBy string // quickxor | sha1 | md5 | size
+ VerifiedBy string // quickxor | sha1 | md5 | dropbox | size
}
var (
ErrSessionExpired = errors.New("a sessão de upload expirou")
- errRetry = errors.New("tentar de novo")
+ // ErrMismatch: o envio terminou, mas o que a nuvem guardou não confere. O Server precisa ser avisado para apagar o arquivo.
+ ErrMismatch = errors.New("o arquivo na nuvem não confere")
+ errRetry = errors.New("tentar de novo")
)
type Options struct {
@@ -108,6 +113,13 @@ func Upload(ctx context.Context, sess Session, path string, opt Options) (Result
if res.Digest, err = HashFile(ctx, path); err != nil {
return res, err
}
+ switch sess.Protocol {
+ case "graph", "gdrive":
+ case "dropbox":
+ return uploadDropbox(ctx, sess, f, res, total, opt)
+ default:
+ return res, fmt.Errorf("protocolo de envio desconhecido (%q): atualize o agente", sess.Protocol)
+ }
chunk := sess.ChunkSize
if chunk <= 0 {
chunk = 8 << 20
@@ -332,22 +344,22 @@ func finish(s Session, body []byte, res Result, total int64) (Result, error) {
}
}
if res.RemoteSize != 0 && res.RemoteSize != total {
- return res, fmt.Errorf("a nuvem guardou %d bytes, esperado %d", res.RemoteSize, total)
+ return res, fmt.Errorf("%w: a nuvem guardou %d bytes, esperado %d", ErrMismatch, res.RemoteSize, total)
}
switch {
case res.RemoteQuickXor != "":
if res.RemoteQuickXor != res.Digest.QuickXor {
- return res, errors.New("o hash quickXor da nuvem difere do arquivo enviado")
+ return res, fmt.Errorf("%w: o hash quickXor da nuvem difere do arquivo enviado", ErrMismatch)
}
res.VerifiedBy = "quickxor"
case res.RemoteSHA1 != "":
if res.RemoteSHA1 != res.Digest.SHA1 {
- return res, errors.New("o hash SHA-1 da nuvem difere do arquivo enviado")
+ return res, fmt.Errorf("%w: o hash SHA-1 da nuvem difere do arquivo enviado", ErrMismatch)
}
res.VerifiedBy = "sha1"
case res.RemoteMD5 != "":
if res.RemoteMD5 != res.Digest.MD5 {
- return res, errors.New("o hash MD5 da nuvem difere do arquivo enviado")
+ return res, fmt.Errorf("%w: o hash MD5 da nuvem difere do arquivo enviado", ErrMismatch)
}
res.VerifiedBy = "md5"
case res.RemoteSize == total:
diff --git a/internal/version/version.go b/internal/version/version.go
index b0a9d9f..3b20bca 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.9"
+var Version = "0.0.10"
const Name = "Coruja Backup"
diff --git a/proto/coruja/v1/agent.proto b/proto/coruja/v1/agent.proto
index 4f4b9fc..b257e32 100644
--- a/proto/coruja/v1/agent.proto
+++ b/proto/coruja/v1/agent.proto
@@ -144,11 +144,13 @@ message UploadSession {
string request_id = 1;
bool ok = 2;
string error = 3;
- string protocol = 4; // "graph" (OneDrive) | "gdrive" (Google Drive)
+ string protocol = 4; // "graph" (OneDrive) | "gdrive" (Google Drive) | "dropbox"
string url = 5; // URL da sessão (já autenticada; o agente não recebe tokens)
int64 chunk_size = 6;
int64 expires_unix_ms = 7;
string remote_path = 8;
+ string token = 9; // só "dropbox": token de curta duração, só de escrita de conteúdo, na pasta do aplicativo
+ string upload_path = 10; // só "dropbox": caminho de destino
}
message UploadDone {
@@ -164,6 +166,7 @@ message UploadDone {
string remote_id = 10;
bool ok = 11;
string error = 12;
+ string dropbox_hash = 13; // content_hash do Dropbox
}
message UploadVerdict {
diff --git a/scripts/release.sh b/scripts/release.sh
index da7faec..cc5de02 100755
--- a/scripts/release.sh
+++ b/scripts/release.sh
@@ -1,12 +1,16 @@
#!/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.9 (precisa de "docker login ghcr.io" e do buildx)
+# Uso: ./scripts/release.sh 0.0.10 (precisa de "docker login ghcr.io" e do buildx)
set -e
-V="${1:?informe a versão, ex.: 0.0.9}"
+V="${1:?informe a versão, ex.: 0.0.10}"
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
+SEC=()
+if [ -n "${GOOGLE_CLIENT_SECRET_FILE:-}" ]; then SEC+=(--secret "id=google_client_secret,src=$GOOGLE_CLIENT_SECRET_FILE"); fi
+if [ -n "${GOOGLE_WEB_CLIENT_SECRET_FILE:-}" ]; then SEC+=(--secret "id=google_web_client_secret,src=$GOOGLE_WEB_CLIENT_SECRET_FILE"); fi
for t in server agent; do
- docker buildx build --platform linux/amd64,linux/arm64 --target "$t" --build-arg "VERSION=$V" \
+ docker buildx build "${SEC[@]}" --platform linux/amd64,linux/arm64 --target "$t" --build-arg "VERSION=$V" \
--provenance=mode=max --sbom=true \
-t "ghcr.io/$OWNER/corujabackup-$t:$V" -t "ghcr.io/$OWNER/corujabackup-$t:latest" --push .
done
diff --git a/site/Dockerfile b/site/Dockerfile
new file mode 100644
index 0000000..d108297
--- /dev/null
+++ b/site/Dockerfile
@@ -0,0 +1,5 @@
+# Site estático do Coruja Backup (página inicial, privacidade e termos), usado na tela de consentimento OAuth.
+FROM nginxinc/nginx-unprivileged:alpine
+COPY nginx.conf /etc/nginx/conf.d/default.conf
+COPY index.html privacidade.html termos.html oauth-callback.html oauth-callback.js logo-120.png logo-512.png logo.svg /usr/share/nginx/html/
+EXPOSE 8080
diff --git a/site/docker-compose.yml b/site/docker-compose.yml
new file mode 100644
index 0000000..6b467cd
--- /dev/null
+++ b/site/docker-compose.yml
@@ -0,0 +1,13 @@
+services:
+ coruja-site:
+ image: coruja-site:1.2.0
+ container_name: coruja-site
+ restart: always
+ read_only: true
+ cap_drop: [ALL]
+ security_opt: ["no-new-privileges:true"]
+ tmpfs: ["/tmp", "/var/cache/nginx"]
+ networks: [echelon]
+networks:
+ echelon:
+ external: true
diff --git a/site/index.html b/site/index.html
new file mode 100644
index 0000000..6468b87
--- /dev/null
+++ b/site/index.html
@@ -0,0 +1,19 @@
+
+
+Início · Coruja Backup
+
+Coruja Backup
+
Coruja Backup
+
Sistema de backup centralizado, em Docker e gerenciado por interface web. Um servidor orquestra tudo e agentes leves rodam nas máquinas protegidas. Código aberto, licença MIT.
+
Envio para a nuvem
+
O Coruja envia os arquivos de backup para a sua própria conta no Google Drive, OneDrive ou Dropbox, depois que você autoriza o acesso. Este endereço identifica o aplicativo de autorização usado nesse login.
+
+
diff --git a/site/logo-120.png b/site/logo-120.png
new file mode 100644
index 0000000..290960c
Binary files /dev/null and b/site/logo-120.png differ
diff --git a/site/logo-215.png b/site/logo-215.png
new file mode 100644
index 0000000..8c828d5
Binary files /dev/null and b/site/logo-215.png differ
diff --git a/site/logo-256.png b/site/logo-256.png
new file mode 100644
index 0000000..2418c0d
Binary files /dev/null and b/site/logo-256.png differ
diff --git a/site/logo-512.png b/site/logo-512.png
new file mode 100644
index 0000000..5b1cbc1
Binary files /dev/null and b/site/logo-512.png differ
diff --git a/site/logo-64.png b/site/logo-64.png
new file mode 100644
index 0000000..b401f02
Binary files /dev/null and b/site/logo-64.png differ
diff --git a/site/logo.svg b/site/logo.svg
new file mode 100644
index 0000000..b704231
--- /dev/null
+++ b/site/logo.svg
@@ -0,0 +1 @@
+
diff --git a/site/nginx.conf b/site/nginx.conf
new file mode 100644
index 0000000..6474ab7
--- /dev/null
+++ b/site/nginx.conf
@@ -0,0 +1,26 @@
+server {
+ listen 8080;
+ server_name _;
+ root /usr/share/nginx/html;
+ index index.html;
+ server_tokens off;
+ add_header X-Content-Type-Options nosniff always;
+ add_header X-Frame-Options DENY always;
+ add_header Referrer-Policy strict-origin-when-cross-origin always;
+ add_header Content-Security-Policy "default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" always;
+ location = / { try_files /index.html =404; }
+ location / { try_files $uri $uri.html =404; }
+ # retorno do login por popup: sem registro de acesso (a URL traz o código de uso único), sem cache e sem Referer
+ location ~ ^/oauth/(google|microsoft|dropbox)/callback$ {
+ access_log off;
+ default_type text/html;
+ add_header Cache-Control "no-store" always;
+ add_header Referrer-Policy no-referrer always;
+ add_header X-Content-Type-Options nosniff always;
+ add_header X-Frame-Options DENY always;
+ add_header Content-Security-Policy "default-src 'none'; script-src 'self'; style-src 'unsafe-inline'; img-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" always;
+ try_files /oauth-callback.html =404;
+ }
+ location = /oauth-callback.js { add_header Cache-Control "no-cache" always; add_header X-Content-Type-Options nosniff always; }
+ location = /healthz { access_log off; return 200 "ok\n"; }
+}
diff --git a/site/oauth-callback.html b/site/oauth-callback.html
new file mode 100644
index 0000000..acbb7ce
--- /dev/null
+++ b/site/oauth-callback.html
@@ -0,0 +1,9 @@
+
+
+
+Conectando · Coruja Backup
+
+
Conectando…
Aguarde um instante.
+
diff --git a/site/oauth-callback.js b/site/oauth-callback.js
new file mode 100644
index 0000000..5ca92be
--- /dev/null
+++ b/site/oauth-callback.js
@@ -0,0 +1,18 @@
+// Página de retorno do login (popup) do Coruja Backup. Não guarda nada: entrega o código à janela do Coruja que abriu este
+// popup, e só a ela (a origem vem no "state" e é conferida), usando postMessage. Nada é enviado a servidor algum.
+(function () {
+ var t = document.getElementById('t'), m = document.getElementById('m');
+ function fail(msg) { t.textContent = 'Não foi possível concluir'; m.textContent = msg; }
+ var q = new URLSearchParams(location.search);
+ var state = q.get('state') || '', code = q.get('code') || '', err = q.get('error') || '';
+ var i = state.indexOf('.'), origin = '';
+ try { origin = atob(state.slice(i + 1).replace(/-/g, '+').replace(/_/g, '/')); } catch (e) { origin = ''; }
+ history.replaceState(null, '', location.pathname); // tira o código da barra de endereço
+ if (i < 1 || !/^https?:\/\/(\[[0-9a-fA-F:]+\]|[A-Za-z0-9.\-]+)(:[0-9]{1,5})?$/.test(origin)) { fail('Resposta de login inválida. Feche esta janela e tente de novo no Coruja.'); return; }
+ if (!window.opener) { fail('Esta janela deve ser aberta pelo Coruja. Feche-a e clique em “Entrar com o Google” no Coruja.'); return; }
+ if (!code && !err) { fail('O provedor não devolveu o código. Feche esta janela e tente de novo.'); return; }
+ try { window.opener.postMessage({ type: 'coruja-oauth', state: state, code: code, error: err }, origin); } catch (e) { fail('Não foi possível falar com o Coruja.'); return; }
+ t.textContent = err ? 'Acesso não autorizado' : 'Conta autorizada';
+ m.textContent = err ? 'Você pode fechar esta janela.' : 'Você já pode fechar esta janela e voltar ao Coruja.';
+ setTimeout(function () { window.close(); }, 600);
+})();
diff --git a/site/privacidade.html b/site/privacidade.html
new file mode 100644
index 0000000..4759cf3
--- /dev/null
+++ b/site/privacidade.html
@@ -0,0 +1,28 @@
+
+
+Política de privacidade · Coruja Backup
+
+Coruja Backup
+
Política de privacidade
Atualizada em 26/11/2026.
+
Quem trata os seus dados
+
O Coruja Backup é um software auto-hospedado: ele roda nos servidores de quem o instala. Os autores do projeto não operam nenhum serviço que receba, armazene ou processe os seus arquivos, tokens ou dados pessoais.
+
O que o aplicativo acessa na sua conta
+
Google Drive: apenas o escopo drive.file, que permite ver e gerenciar somente os arquivos e pastas que o próprio Coruja criou, e o escopo de e-mail, para mostrar qual conta está conectada.
+
OneDrive/SharePoint:Files.ReadWrite, offline_access e User.Read.
+
Dropbox: pasta do aplicativo (App folder), com leitura e escrita de arquivos e identificação da conta.
+
Onde ficam os tokens e os arquivos
+
Os tokens de acesso e de renovação ficam cifrados (AES-256-GCM) no servidor Coruja de quem o instalou, nunca em servidores dos autores. Os backups vão do agente direto para a conta de nuvem do próprio usuário.
+
A página de retorno do login
+
Quando você conecta uma conta, o Google devolve você a coruja.henrique.tec.br/oauth/google/callback. Essa página só repassa, no seu navegador, um código de uso único à janela do Coruja que abriu o login (e somente a ela). Os tokens de acesso nunca passam por este servidor, que não registra nem guarda esse código.
+
Uso dos dados do Google
+
O uso e a transferência de informações recebidas das APIs do Google seguem a Política de Dados do Usuário dos Serviços de API do Google, incluindo os requisitos de Uso Limitado. Os dados são usados apenas para realizar e conferir os backups que o usuário configurou; não são vendidos, compartilhados com terceiros nem usados para publicidade.
O Coruja Backup é um software de código aberto, distribuído sob a licença MIT. Quem o instala é o responsável pela sua instalação, pelos seus servidores e pelos dados que protege.
+
2. Sem garantia
O software é fornecido “como está”, sem garantias de qualquer tipo. Backups devem ser testados: use a verificação e a restauração de teste que o próprio sistema oferece. Os autores não respondem por perda de dados ou por danos decorrentes do uso.
+
3. Contas de nuvem
Ao conectar uma conta, você autoriza o seu servidor Coruja a criar, ler e remover, na sua conta, os arquivos de backup que ele gerou, conforme a retenção que você configurar. Você é responsável por respeitar os termos do provedor (Google, Microsoft, Dropbox) e pode revogar o acesso a qualquer momento.
+
4. Uso aceitável
Não use o software para acessar sistemas ou dados sem autorização.