From a4dcf461acd58d859ef6ebd006b19246a46497d4 Mon Sep 17 00:00:00 2001 From: Henrique Fagundes Date: Thu, 26 Nov 2026 07:39:09 -0300 Subject: [PATCH 01/12] docs: Fase 9 dividida em etapas (9a a 9d) Co-Authored-By: Claude Sonnet 5.5 --- docs/ROADMAP.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index d447b01..e2493cb 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -9,7 +9,11 @@ - [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 9 – Destinos de armazenamento (0.0.10):** entregue em etapas, cada uma testável sozinha: + - **9a · Modelo de destinos:** um job passa a ter uma lista de destinos (pasta local do agente + contas), cada um com retenção e conferência próprias; `Provider` ganha um tipo de sessão por protocolo. + - **9b · Compatíveis com S3** (AWS, MinIO, Wasabi, Backblaze): URLs pré-assinadas pelo Server, envio em partes (arquivos grandes), credenciais só no Server. + - **9c · Dropbox e SharePoint:** login por código no navegador (cartões com janela de login); SharePoint como biblioteca de documentos do OneDrive. + - **9d · Destinos diretos do agente:** SFTP e SMB (clientes Go nativos, credencial cifrada no Server e entregue ao agente), pasta local/volume do host (NFS e iSCSI montados 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. - [ ] **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. From eee184fedc755a30bc65d0e7424fc20ddfd45338 Mon Sep 17 00:00:00 2001 From: Henrique Fagundes Date: Thu, 26 Nov 2026 08:04:34 -0300 Subject: [PATCH 02/12] =?UTF-8?q?site:=20p=C3=A1gina=20inicial,=20privacid?= =?UTF-8?q?ade=20e=20termos=20para=20a=20tela=20de=20consentimento=20OAuth?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- site/Dockerfile | 5 +++++ site/docker-compose.yml | 13 +++++++++++++ site/index.html | 19 +++++++++++++++++++ site/logo-120.png | Bin 0 -> 3585 bytes site/logo-512.png | Bin 0 -> 16280 bytes site/logo.svg | 1 + site/nginx.conf | 14 ++++++++++++++ site/privacidade.html | 26 ++++++++++++++++++++++++++ site/termos.html | 18 ++++++++++++++++++ 9 files changed, 96 insertions(+) create mode 100644 site/Dockerfile create mode 100644 site/docker-compose.yml create mode 100644 site/index.html create mode 100644 site/logo-120.png create mode 100644 site/logo-512.png create mode 100644 site/logo.svg create mode 100644 site/nginx.conf create mode 100644 site/privacidade.html create mode 100644 site/termos.html diff --git a/site/Dockerfile b/site/Dockerfile new file mode 100644 index 0000000..0d9ddc2 --- /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 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..ec30bc3 --- /dev/null +++ b/site/docker-compose.yml @@ -0,0 +1,13 @@ +services: + coruja-site: + image: coruja-site:1.0.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 BackupCoruja 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.

+

Links

+
+ +
diff --git a/site/logo-120.png b/site/logo-120.png new file mode 100644 index 0000000000000000000000000000000000000000..290960c1c0e1e95bc70508ec4241c67319fe86db GIT binary patch literal 3585 zcmV+c4*v0pP)|;3BA~S{+hV01D%25MWDpd>BZN#PB#;>1iG&bB z!XwE|?!9NvA0ZkbH}@tvckh#UK7WO~&)wf2=X-zW?AJM4U?cOVE>D++cY!74EJKJX zQpyPkl8__-@pftr0$LC>BWVyqoUo*Z4Izn(nN;aB?d~f1%Ukg!r2HY0C4kYNAY4LXA$Ugwt!D}=)|d39 zf?gYZ*OW)I48!;@fw-?Pf-ZeTuti!tvG3U0Grjqm*&B&@IV)BhLTnO0zbEEbz~VlK=VBvrN5F`AsHp74x^PE^HTa(F6}JaX zxgD5jOKdLoAUI`O=AzxlUaIQ(upXG3``8R2#WrA+t--n2MV%1FqQdeuheI6@(%`vy zD<=rcDg@G^5}J!W2P+uk5b4+wRT$i7QitWo^eb*ZD|NFpc*LCNEF!uDCmc zh2^z=0gR7sWG*%`!SC_>nr^Phw{(-{<*Zl@tW*(|i=Bu`8L6|cRM!{pzv0ua|F}Nv zcoaxb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5b(jkUvApwMf2l^A#Vl$A(OYBcWAw6WE>kGt>)O+s!HZm{YmP@Jy>CHHoMoPY zv}4HC-C=Bu=emYk!@x2l)pscqiSwh2t*$bBIWfu(%Rmd*_+W83r=Wh5`j;KIkuSq9 zQhjIm*W-Os)G}3fv=Hg_5%mxVu%T^aaE5+&Ii21ttPA$V;t41c=6kQv(01%qRr=_* zJt*~sLPzgSI|N}3(}S#DwoCJwb`q+D`7ODwq}(4cI?!e~d$~vT7FwLX!YAzzb-WIW zQw3qnT*`J(= zFL9qxcdXW{1{c+j=aAA?WVil>wpN3*+!XB%n~e5p=^f40xmqOD=IfiLVWr?vrz`&7 znl3&ybC*D2ImKmbQ6n86WCN7hwUZ=T5;=U^afkR69YN<5xcCL7_3{acmTXc~eU8%Y zotQ)Ekk1v2_N4;fIxa8Ov_aXO+oBUL3B!sDc4g}UCDV$wf)SXG75SSA>GP zi6MA@=9gWn&myuN-s1YE+k43C8Rx7jTX(wSKgW&@sJwtqQW#ZKR9bU$TyaxBuHh>> z^cglYOAYKJ5&S!TGpaG;PAP=yUxQcfvv_i;>hZGjKyq;QLy(Gs#uNDC7q9<6$V8B} literal 0 HcmV?d00001 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..13227c8 --- /dev/null +++ b/site/nginx.conf @@ -0,0 +1,14 @@ +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; } + location = /healthz { access_log off; return 200 "ok\n"; } +} diff --git a/site/privacidade.html b/site/privacidade.html new file mode 100644 index 0000000..84ea3bd --- /dev/null +++ b/site/privacidade.html @@ -0,0 +1,26 @@ + + +Política de privacidade · Coruja Backup +
+
Coruja BackupCoruja 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.

+

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.

+

Revogar o acesso

+

Remova a conta de nuvem na interface do Coruja e revogue o acesso em myaccount.google.com/permissions (Google), account.live.com/consent/Manage (Microsoft) ou nas configurações de aplicativos do Dropbox.

+

Contato

Dúvidas: henrique.tec.br ou as issues do projeto.

+ +
diff --git a/site/termos.html b/site/termos.html new file mode 100644 index 0000000..cb3d307 --- /dev/null +++ b/site/termos.html @@ -0,0 +1,18 @@ + + +Termos de serviço · Coruja Backup +
+
Coruja BackupCoruja Backup
+

Termos de serviço

Atualizados em 26/11/2026.

+

1. O que é

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.

+

5. Privacidade

Veja a política de privacidade.

+ +
From 31a6222b9cc5d1942136dd7d7382df10bd25aaac Mon Sep 17 00:00:00 2001 From: Henrique Fagundes Date: Thu, 26 Nov 2026 08:41:49 -0300 Subject: [PATCH 03/12] =?UTF-8?q?Fase=209:=20aplicativo=20OAuth=20padr?= =?UTF-8?q?=C3=A3o=20do=20Google=20Drive=20embutido=20(segredo=20s=C3=B3?= =?UTF-8?q?=20na=20compila=C3=A7=C3=A3o)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/release.yml | 8 ++++++- CHANGELOG.md | 3 +++ Dockerfile | 6 ++++- docs/INSTALACAO.md | 2 +- docs/OPERACAO.md | 6 +++++ internal/cloud/defaults.go | 15 +++++++++++++ internal/cloudmgr/cloudmgr.go | 20 +++++++++++++++-- internal/e2e/e2e_test.go | 35 ++++++++++++++++++++++++++++++ internal/httpapi/handlers_cloud.go | 2 +- scripts/release.sh | 5 ++++- web/src/pages/Clouds.tsx | 26 +++++++++++++++------- 11 files changed, 113 insertions(+), 15 deletions(-) create mode 100644 internal/cloud/defaults.go diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b24de93..8ec0423 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -36,6 +36,8 @@ jobs: provenance: mode=max sbom: true build-args: VERSION=${{ steps.v.outputs.version }} + secrets: | + google_client_secret=${{ secrets.GOOGLE_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 +65,17 @@ 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) 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 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..322fd05 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ # Changelog +## [Não publicado] - Fase 9 +- **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..d1cd46e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -22,7 +22,11 @@ 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 \ + 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; \ + 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 ------------------------------------------------------------------------------------------------------------ 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/internal/cloud/defaults.go b/internal/cloud/defaults.go new file mode 100644 index 0000000..f9ba785 --- /dev/null +++ b/internal/cloud/defaults.go @@ -0,0 +1,15 @@ +package cloud + +// 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 != "" +} diff --git a/internal/cloudmgr/cloudmgr.go b/internal/cloudmgr/cloudmgr.go index 0300ba2..9ae3c2f 100644 --- a/internal/cloudmgr/cloudmgr.go +++ b/internal/cloudmgr/cloudmgr.go @@ -33,6 +33,8 @@ 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"` } type Manager struct { @@ -54,6 +56,12 @@ func New(st *store.Store, box *secrets.Box) *Manager { 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 { + 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: @@ -84,10 +92,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) @@ -431,3 +442,8 @@ 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) +} diff --git a/internal/e2e/e2e_test.go b/internal/e2e/e2e_test.go index 3057048..7e1fc88 100644 --- a/internal/e2e/e2e_test.go +++ b/internal/e2e/e2e_test.go @@ -516,3 +516,38 @@ 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") + } +} diff --git a/internal/httpapi/handlers_cloud.go b/internal/httpapi/handlers_cloud.go index 57e116b..24de01a 100644 --- a/internal/httpapi/handlers_cloud.go +++ b/internal/httpapi/handlers_cloud.go @@ -30,7 +30,7 @@ func (s *Server) listClouds(w http.ResponseWriter, r *http.Request, _ *ctxUser) n, _ := s.Store.JobsUsingCloud(r.Context(), a.ID) out = append(out, cloudView{a, n}) } - writeJSON(w, 200, map[string]any{"accounts": out}) + writeJSON(w, 200, map[string]any{"accounts": out, "defaults": map[string]bool{"gdrive": cloud.HasDefaultApp(cloud.TypeGDrive)}}) } func deviceView(d *cloud.Device) map[string]any { diff --git a/scripts/release.sh b/scripts/release.sh index da7faec..6803608 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -5,8 +5,11 @@ set -e V="${1:?informe a versão, ex.: 0.0.9}" 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 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/web/src/pages/Clouds.tsx b/web/src/pages/Clouds.tsx index 588f514..03e84f4 100644 --- a/web/src/pages/Clouds.tsx +++ b/web/src/pages/Clouds.tsx @@ -6,11 +6,12 @@ export default function Clouds({ me }: { me: User }) { const [accounts, setAccounts] = useState([]) const [err, setErr] = useState('') const [info, setInfo] = useState('') + const [hasDefault, setHasDefault] = useState(false) const [wizard, setWizard] = useState<{ id?: number; device?: DeviceInfo; name?: string } | null>(null) const isAdmin = me.role === 'admin' const load = useCallback(() => { - api<{ accounts: CloudAccount[] }>('GET', '/api/clouds').then((r) => { setAccounts(r.accounts); setErr('') }).catch((x) => setErr((x as ApiError).message)) + api<{ accounts: CloudAccount[]; defaults?: { gdrive?: boolean } }>('GET', '/api/clouds').then((r) => { setAccounts(r.accounts); setHasDefault(!!r.defaults?.gdrive); setErr('') }).catch((x) => setErr((x as ApiError).message)) }, []) useEffect(() => { load() }, [load]) @@ -74,31 +75,40 @@ export default function Clouds({ me }: { me: User }) { {wizard && { setWizard(null); load() }}> {wizard.device && wizard.id ? { setWizard(null); setInfo('Conta conectada com sucesso.'); load() }} /> - : { setWizard({ id, device, name }); load() }} />} + : { setWizard({ id, device, name }); load() }} />} } ) } -function NewAccount({ onCreated }: { onCreated: (id: number, device: DeviceInfo, name: string) => void }) { +function NewAccount({ onCreated, hasDefault }: { onCreated: (id: number, device: DeviceInfo, name: string) => void; hasDefault: boolean }) { const [f, setF] = useState({ type: 'onedrive', name: '', client_id: '', client_secret: '', tenant: '' }) + const [own, setOwn] = useState(false) const [err, setErr] = useState('') const [busy, setBusy] = useState(false) async function submit(e: FormEvent) { e.preventDefault(); setErr(''); setBusy(true) - try { const r = await api<{ id: number; device: DeviceInfo }>('POST', '/api/clouds', f); onCreated(r.id, r.device, f.name) } + try { const r = await api<{ id: number; device: DeviceInfo }>('POST', '/api/clouds', std ? { ...f, client_id: '', client_secret: '' } : f); onCreated(r.id, r.device, f.name) } catch (x) { setErr((x as ApiError).message) } finally { setBusy(false) } } const sel = 'w-full rounded-lg border border-border bg-surface px-3 py-2' const od = f.type === 'onedrive' + const std = f.type === 'gdrive' && hasDefault && !own // usa o aplicativo padrão do Coruja: nada a preencher return (
setF({ ...f, name: e.target.value })} required />
- setF({ ...f, client_id: e.target.value })} required /> - {od ? ( + {std && ( +
+ Vamos mostrar um código e um link do Google. Abra o link, digite o código e autorize a sua conta: não é preciso registrar aplicativo nem colar credenciais. O Coruja só enxerga os arquivos que ele mesmo criar.{' '} + +
+ )} + {f.type === 'gdrive' && hasDefault && own && } + {!std && setF({ ...f, client_id: e.target.value })} required />} + {std ? null : od ? (
setF({ ...f, tenant: e.target.value })} /> setF({ ...f, client_secret: e.target.value })} /> @@ -106,7 +116,7 @@ function NewAccount({ onCreated }: { onCreated: (id: number, device: DeviceInfo, ) : ( setF({ ...f, client_secret: e.target.value })} required /> )} -
+ {!std &&
Como obter o Client ID{od ? '' : ' e o Secret'} {od ? (
    @@ -124,7 +134,7 @@ function NewAccount({ onCreated }: { onCreated: (id: number, device: DeviceInfo,
  1. Copie o ID do cliente e a chave secreta. O acesso pedido é só drive.file: o Coruja Backup enxerga apenas os arquivos que ele mesmo cria.
)} -
+
} From 303c3a9f051f3819a273cd3a180b24f409feb4b0 Mon Sep 17 00:00:00 2001 From: Henrique Fagundes Date: Thu, 26 Nov 2026 09:02:51 -0300 Subject: [PATCH 04/12] =?UTF-8?q?Fase=209:=20login=20por=20popup=20(bot?= =?UTF-8?q?=C3=A3o=20=C3=BAnico)=20para=20o=20Google=20Drive,=20com=20p?= =?UTF-8?q?=C3=A1gina=20de=20retorno=20no=20site?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/release.yml | 3 + Dockerfile | 3 +- cmd/server/main.go | 4 + internal/cloud/cloudtest/fake.go | 23 ++++-- internal/cloud/defaults.go | 24 ++++++ internal/cloud/gdrive.go | 2 +- internal/cloud/oauth.go | 29 +++++++ internal/cloudmgr/cloudmgr.go | 127 ++++++++++++++++++++++++++++- internal/e2e/e2e_test.go | 92 +++++++++++++++++++++ internal/httpapi/handlers_cloud.go | 55 ++++++++++++- internal/httpapi/httpapi.go | 4 + internal/httpapi/httpapi_test.go | 9 ++ scripts/release.sh | 3 +- site/Dockerfile | 2 +- site/docker-compose.yml | 2 +- site/nginx.conf | 12 +++ site/oauth-callback.html | 9 ++ site/oauth-callback.js | 18 ++++ site/privacidade.html | 2 + web/src/pages/Clouds.tsx | 57 ++++++++++--- 20 files changed, 454 insertions(+), 26 deletions(-) create mode 100644 site/oauth-callback.html create mode 100644 site/oauth-callback.js diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8ec0423..68569d8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -38,6 +38,7 @@ jobs: 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 @@ -67,6 +68,7 @@ jobs: - 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 @@ -74,6 +76,7 @@ jobs: 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 "$LDF" \ -o "dist/coruja-${bin}-linux-${arch}" "./cmd/${bin}" diff --git a/Dockerfile b/Dockerfile index d1cd46e..b5921b8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -23,9 +23,10 @@ COPY internal ./internal COPY --from=web /src/internal/webui/dist ./internal/webui/dist ENV CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} # 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 \ +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 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/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 index f9ba785..a0c2b9f 100644 --- a/internal/cloud/defaults.go +++ b/internal/cloud/defaults.go @@ -1,5 +1,7 @@ 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 @@ -13,3 +15,25 @@ var ( 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" +) + +// HasWebApp informa se o login por popup (aplicativo da Web) está disponível para o tipo de nuvem. +func HasWebApp(typ string) bool { + return typ == TypeGDrive && DefaultGoogleWebClientID != "" && DefaultGoogleWebClientSecret != "" && OAuthBrokerURL != "" +} + +// BrokerRedirect devolve o endereço de retorno cadastrado no provedor para o tipo de nuvem. +func BrokerRedirect(typ string) string { + if typ == TypeGDrive { + return strings.TrimRight(OAuthBrokerURL, "/") + "/oauth/google/callback" + } + return "" +} diff --git a/internal/cloud/gdrive.go b/internal/cloud/gdrive.go index 1a01292..0a410bc 100644 --- a/internal/cloud/gdrive.go +++ b/internal/cloud/gdrive.go @@ -35,7 +35,7 @@ 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"} } func (g *GDrive) Type() string { return TypeGDrive } diff --git a/internal/cloud/oauth.go b/internal/cloud/oauth.go index 14d4f69..f77bd49 100644 --- a/internal/cloud/oauth.go +++ b/internal/cloud/oauth.go @@ -33,6 +33,7 @@ type OAuth struct { ClientID string ClientSecret string DeviceURL string + AuthURL string // fluxo com retorno (popup) TokenURL string Scope string HTTP *http.Client @@ -200,3 +201,31 @@ 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"}, + "access_type": {"offline"}, "prompt": {"consent"}, "include_granted_scopes": {"false"}} + 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 +} diff --git a/internal/cloudmgr/cloudmgr.go b/internal/cloudmgr/cloudmgr.go index 9ae3c2f..cbfe47f 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,7 @@ type Endpoints struct { MSDevice, MSToken string Graph string GDevice, GToken string + GAuth string GAPI, GUpload string } @@ -35,6 +41,8 @@ type AccountConfig struct { 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 { @@ -47,16 +55,27 @@ 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 + 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 { + 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.DefaultGoogleWebClientID, cloud.DefaultGoogleWebClientSecret + } 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") } @@ -74,6 +93,9 @@ 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 + } default: return nil, fmt.Errorf("tipo de nuvem desconhecido: %q", typ) } @@ -447,3 +469,104 @@ func (m *Manager) Open(ctx context.Context, accountID int64, folder, name string 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) { + 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 { + 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), 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 + } + cj, _ := json.Marshal(cfg) + sc, err := m.Box.Seal(string(cj)) + if err != nil { + return 0, err + } + id, err := m.Store.CreateCloud(ctx, p.Name, p.Typ, sc, "") + if 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 7e1fc88..0f55388 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" @@ -551,3 +555,91 @@ func TestGoogleDriveComAplicativoPadrao(t *testing.T) { 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 +} diff --git a/internal/httpapi/handlers_cloud.go b/internal/httpapi/handlers_cloud.go index 24de01a..c74ba60 100644 --- a/internal/httpapi/handlers_cloud.go +++ b/internal/httpapi/handlers_cloud.go @@ -30,7 +30,7 @@ func (s *Server) listClouds(w http.ResponseWriter, r *http.Request, _ *ctxUser) n, _ := s.Store.JobsUsingCloud(r.Context(), a.ID) out = append(out, cloudView{a, n}) } - writeJSON(w, 200, map[string]any{"accounts": out, "defaults": map[string]bool{"gdrive": cloud.HasDefaultApp(cloud.TypeGDrive)}}) + writeJSON(w, 200, map[string]any{"accounts": out, "defaults": map[string]any{"gdrive": cloud.HasDefaultApp(cloud.TypeGDrive), "gdrive_web": cloud.HasWebApp(cloud.TypeGDrive), "broker": strings.TrimRight(cloud.OAuthBrokerURL, "/")}}) } func deviceView(d *cloud.Device) map[string]any { @@ -162,3 +162,56 @@ 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"` + } + if !decode(w, r, &in) { + return + } + 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..84dc764 100644 --- a/internal/httpapi/httpapi.go +++ b/internal/httpapi/httpapi.go @@ -45,6 +45,8 @@ 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) + FinishWeb(ctx context.Context, state, code string) (int64, error) Open(ctx context.Context, accountID int64, folder, name string) (io.ReadCloser, int64, error) } @@ -142,6 +144,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..fcbea4f 100644 --- a/internal/httpapi/httpapi_test.go +++ b/internal/httpapi/httpapi_test.go @@ -561,6 +561,15 @@ 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) 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/scripts/release.sh b/scripts/release.sh index 6803608..144356b 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -7,7 +7,8 @@ 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_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 "${SEC[@]}" --platform linux/amd64,linux/arm64 --target "$t" --build-arg "VERSION=$V" \ --provenance=mode=max --sbom=true \ diff --git a/site/Dockerfile b/site/Dockerfile index 0d9ddc2..d108297 100644 --- a/site/Dockerfile +++ b/site/Dockerfile @@ -1,5 +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 logo-120.png logo-512.png logo.svg /usr/share/nginx/html/ +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 index ec30bc3..a942578 100644 --- a/site/docker-compose.yml +++ b/site/docker-compose.yml @@ -1,6 +1,6 @@ services: coruja-site: - image: coruja-site:1.0.0 + image: coruja-site:1.1.0 container_name: coruja-site restart: always read_only: true diff --git a/site/nginx.conf b/site/nginx.conf index 13227c8..61bdfc2 100644 --- a/site/nginx.conf +++ b/site/nginx.conf @@ -10,5 +10,17 @@ server { 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/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 + +
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 index 84ea3bd..4759cf3 100644 --- a/site/privacidade.html +++ b/site/privacidade.html @@ -17,6 +17,8 @@

O que o aplicativo acessa na sua conta

  • 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.

    Revogar o acesso

    diff --git a/web/src/pages/Clouds.tsx b/web/src/pages/Clouds.tsx index 03e84f4..191cb20 100644 --- a/web/src/pages/Clouds.tsx +++ b/web/src/pages/Clouds.tsx @@ -6,12 +6,12 @@ export default function Clouds({ me }: { me: User }) { const [accounts, setAccounts] = useState([]) const [err, setErr] = useState('') const [info, setInfo] = useState('') - const [hasDefault, setHasDefault] = useState(false) + const [defs, setDefs] = useState<{ gdrive?: boolean; gdrive_web?: boolean; broker?: string }>({}) const [wizard, setWizard] = useState<{ id?: number; device?: DeviceInfo; name?: string } | null>(null) const isAdmin = me.role === 'admin' const load = useCallback(() => { - api<{ accounts: CloudAccount[]; defaults?: { gdrive?: boolean } }>('GET', '/api/clouds').then((r) => { setAccounts(r.accounts); setHasDefault(!!r.defaults?.gdrive); setErr('') }).catch((x) => setErr((x as ApiError).message)) + api<{ accounts: CloudAccount[]; defaults?: { gdrive?: boolean; gdrive_web?: boolean; broker?: string } }>('GET', '/api/clouds').then((r) => { setAccounts(r.accounts); setDefs(r.defaults ?? {}); setErr('') }).catch((x) => setErr((x as ApiError).message)) }, []) useEffect(() => { load() }, [load]) @@ -75,38 +75,73 @@ export default function Clouds({ me }: { me: User }) { {wizard && { setWizard(null); load() }}> {wizard.device && wizard.id ? { setWizard(null); setInfo('Conta conectada com sucesso.'); load() }} /> - : { setWizard({ id, device, name }); load() }} />} + : { setWizard({ id, device, name }); load() }} onConnected={() => { setWizard(null); setInfo('Conta conectada com sucesso.'); load() }} />} }
    ) } -function NewAccount({ onCreated, hasDefault }: { onCreated: (id: number, device: DeviceInfo, name: string) => void; hasDefault: boolean }) { +function NewAccount({ onCreated, onConnected, defs }: { onCreated: (id: number, device: DeviceInfo, name: string) => void; onConnected: () => void; defs: { gdrive?: boolean; gdrive_web?: boolean; broker?: string } }) { const [f, setF] = useState({ type: 'onedrive', name: '', client_id: '', client_secret: '', tenant: '' }) - const [own, setOwn] = useState(false) + const [mode, setMode] = useState<'auto' | 'code' | 'own'>('auto') const [err, setErr] = useState('') const [busy, setBusy] = useState(false) + const gd = f.type === 'gdrive' + const web = gd && !!defs.gdrive_web && mode === 'auto' // botão único: popup do Google + const std = gd && !web && !!defs.gdrive && mode !== 'own' // aplicativo padrão com código de dispositivo + async function viaPopup() { + // abre o popup já no clique (senão o navegador bloqueia) e só depois descobre o endereço + const pop = window.open('', 'coruja-oauth', 'width=520,height=700') + if (!pop) { setErr('O navegador bloqueou a janela. Libere pop-ups para este endereço ou use o código.'); return } + try { + const r = await api<{ url: string; state: string }>('POST', '/api/clouds/oauth/begin', { name: f.name, type: f.type, origin: window.location.origin }) + pop.location.href = r.url + await new Promise((resolve, reject) => { + let settled = false + const end = (fn: () => void) => { if (settled) return; settled = true; window.removeEventListener('message', onMsg); clearInterval(timer); fn() } + const onMsg = (ev: MessageEvent) => { + if (ev.origin !== defs.broker || ev.data?.type !== 'coruja-oauth' || ev.data.state !== r.state) return + if (ev.data.error) return end(() => reject(new Error(ev.data.error === 'access_denied' ? 'Você não autorizou o acesso.' : `O Google recusou: ${ev.data.error}`))) + api('POST', '/api/clouds/oauth/finish', { state: r.state, code: ev.data.code }).then(() => end(resolve), (x) => end(() => reject(x))) + } + window.addEventListener('message', onMsg) + const timer = window.setInterval(() => { if (pop.closed) setTimeout(() => end(() => reject(new Error('A janela foi fechada antes de terminar.'))), 1500) }, 500) + }) + try { pop.close() } catch { /* já fechou */ } + onConnected() + } catch (x) { try { pop.close() } catch { /* ok */ } throw x } + } async function submit(e: FormEvent) { e.preventDefault(); setErr(''); setBusy(true) - try { const r = await api<{ id: number; device: DeviceInfo }>('POST', '/api/clouds', std ? { ...f, client_id: '', client_secret: '' } : f); onCreated(r.id, r.device, f.name) } - catch (x) { setErr((x as ApiError).message) } finally { setBusy(false) } + try { + if (web) { await viaPopup(); return } + const r = await api<{ id: number; device: DeviceInfo }>('POST', '/api/clouds', std ? { ...f, client_id: '', client_secret: '' } : f) + onCreated(r.id, r.device, f.name) + } catch (x) { setErr((x as ApiError).message) } finally { setBusy(false) } } const sel = 'w-full rounded-lg border border-border bg-surface px-3 py-2' const od = f.type === 'onedrive' - const std = f.type === 'gdrive' && hasDefault && !own // usa o aplicativo padrão do Coruja: nada a preencher return (
    setF({ ...f, name: e.target.value })} required />
    + {web && ( +
    + Uma janela do Google vai abrir para você entrar e autorizar. O Coruja só enxerga os arquivos que ele mesmo criar.{' '} + + {' · '} + +
    + )} {std && (
    Vamos mostrar um código e um link do Google. Abra o link, digite o código e autorize a sua conta: não é preciso registrar aplicativo nem colar credenciais. O Coruja só enxerga os arquivos que ele mesmo criar.{' '} - +
    )} - {f.type === 'gdrive' && hasDefault && own && } + {gd && (defs.gdrive || defs.gdrive_web) && mode !== 'auto' && } {!std && setF({ ...f, client_id: e.target.value })} required />} {std ? null : od ? (
    @@ -136,7 +171,7 @@ function NewAccount({ onCreated, hasDefault }: { onCreated: (id: number, device: )} } - + ) } From 1983cda4c822734f6717d7add75c505797dd31a5 Mon Sep 17 00:00:00 2001 From: Henrique Fagundes Date: Thu, 26 Nov 2026 09:12:31 -0300 Subject: [PATCH 05/12] web: esconde Client ID/segredo no modo de login por popup Co-Authored-By: Claude Sonnet 5.5 --- web/src/pages/Clouds.tsx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/web/src/pages/Clouds.tsx b/web/src/pages/Clouds.tsx index 191cb20..d8f6fd8 100644 --- a/web/src/pages/Clouds.tsx +++ b/web/src/pages/Clouds.tsx @@ -89,6 +89,7 @@ function NewAccount({ onCreated, onConnected, defs }: { onCreated: (id: number, const gd = f.type === 'gdrive' const web = gd && !!defs.gdrive_web && mode === 'auto' // botão único: popup do Google const std = gd && !web && !!defs.gdrive && mode !== 'own' // aplicativo padrão com código de dispositivo + const noCreds = web || std // nada de ID/segredo para preencher async function viaPopup() { // abre o popup já no clique (senão o navegador bloqueia) e só depois descobre o endereço const pop = window.open('', 'coruja-oauth', 'width=520,height=700') @@ -142,8 +143,8 @@ function NewAccount({ onCreated, onConnected, defs }: { onCreated: (id: number,
    )} {gd && (defs.gdrive || defs.gdrive_web) && mode !== 'auto' && } - {!std && setF({ ...f, client_id: e.target.value })} required />} - {std ? null : od ? ( + {!noCreds && setF({ ...f, client_id: e.target.value })} required />} + {noCreds ? null : od ? (
    setF({ ...f, tenant: e.target.value })} /> setF({ ...f, client_secret: e.target.value })} /> @@ -151,7 +152,7 @@ function NewAccount({ onCreated, onConnected, defs }: { onCreated: (id: number, ) : ( setF({ ...f, client_secret: e.target.value })} required /> )} - {!std &&
    + {!noCreds &&
    Como obter o Client ID{od ? '' : ' e o Secret'} {od ? (
      From 38aa2e8456399f949b67e3da8e5d03b3c093a47a Mon Sep 17 00:00:00 2001 From: Henrique Fagundes Date: Thu, 26 Nov 2026 09:24:54 -0300 Subject: [PATCH 06/12] =?UTF-8?q?web:=20tela=20de=20escolha=20de=20destino?= =?UTF-8?q?=20com=20=C3=ADcones=20(Google=20Drive,=20OneDrive,=20Dropbox?= =?UTF-8?q?=20e=20previstos)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- web/src/icons.tsx | 67 ++++++++++++++++++++++++++++++++ web/src/pages/Clouds.tsx | 82 ++++++++++++++++++++++++++++++++++------ 2 files changed, 138 insertions(+), 11 deletions(-) create mode 100644 web/src/icons.tsx diff --git a/web/src/icons.tsx b/web/src/icons.tsx new file mode 100644 index 0000000..5574ef3 --- /dev/null +++ b/web/src/icons.tsx @@ -0,0 +1,67 @@ +import type { ReactNode } from 'react' + +// Ícones simples (desenhados para este projeto) dos serviços de armazenamento. Cada um cabe em 48×48. +type P = { size?: number } +const wrap = (size: number, children: ReactNode, label: string) => ( + {children} +) + +export const GoogleDriveIcon = ({ size = 40 }: P) => wrap(size, <> + + + +, 'Google Drive') + +export const OneDriveIcon = ({ size = 40 }: P) => wrap(size, <> + + + +, 'OneDrive (Microsoft)') + +export const DropboxIcon = ({ size = 40 }: P) => wrap(size, + + + +, 'Dropbox') + +export const S3Icon = ({ size = 40 }: P) => wrap(size, <> + + + +, 'Amazon S3 e compatíveis') + +export const B2Icon = ({ size = 40 }: P) => wrap(size, <> + + +, 'Backblaze B2') + +export const BoxIcon = ({ size = 40 }: P) => wrap(size, <> + + box +, 'Box') + +export const MegaIcon = ({ size = 40 }: P) => wrap(size, <> + + +, 'MEGA') + +export const PCloudIcon = ({ size = 40 }: P) => wrap(size, <> + + +, 'pCloud') + +export const SftpIcon = ({ size = 40 }: P) => wrap(size, <> + + + +, 'Servidor SFTP') + +export const SmbIcon = ({ size = 40 }: P) => wrap(size, <> + + + +, 'Pasta de rede (SMB/NFS)') + +export const CLOUD_ICON: Record ReactNode> = { + gdrive: GoogleDriveIcon, onedrive: OneDriveIcon, dropbox: DropboxIcon, s3: S3Icon, b2: B2Icon, box: BoxIcon, mega: MegaIcon, pcloud: PCloudIcon, sftp: SftpIcon, smb: SmbIcon, +} diff --git a/web/src/pages/Clouds.tsx b/web/src/pages/Clouds.tsx index d8f6fd8..f78ebc3 100644 --- a/web/src/pages/Clouds.tsx +++ b/web/src/pages/Clouds.tsx @@ -1,13 +1,67 @@ import { FormEvent, useCallback, useEffect, useRef, useState } from 'react' import { CLOUD_LABEL, CloudAccount, DeviceInfo, User, api, ApiError, fmtBytes, fmtDate } from '../api' import { Badge, Button, Card, CopyBox, ErrorBox, Field, Input, Modal } from '../ui' +import { CLOUD_ICON } from '../icons' + +// Catálogo de destinos. ok = disponível; soon = em construção (colorido); off = previsto (cinza). +type Prov = { id: string; label: string; hint: string; state: 'ok' | 'soon' | 'off' } +const PROVIDERS: { group: string; items: Prov[] }[] = [ + { group: 'Nuvem', items: [ + { id: 'gdrive', label: 'Google Drive', hint: 'Entre com a sua conta Google', state: 'ok' }, + { id: 'onedrive', label: 'OneDrive', hint: 'Microsoft pessoal ou corporativo', state: 'ok' }, + { id: 'dropbox', label: 'Dropbox', hint: 'Entre com a sua conta Dropbox', state: 'soon' }, + { id: 's3', label: 'Amazon S3', hint: 'AWS, MinIO, Wasabi…', state: 'off' }, + { id: 'b2', label: 'Backblaze B2', hint: 'Armazenamento econômico', state: 'off' }, + { id: 'box', label: 'Box', hint: 'Armazenamento corporativo', state: 'off' }, + { id: 'mega', label: 'MEGA', hint: 'Armazenamento cifrado', state: 'off' }, + { id: 'pcloud', label: 'pCloud', hint: 'Armazenamento europeu', state: 'off' }, + ] }, + { group: 'Servidores e rede', items: [ + { id: 'sftp', label: 'SFTP', hint: 'Servidor por SSH', state: 'off' }, + { id: 'smb', label: 'Pasta de rede', hint: 'SMB, NFS, iSCSI', state: 'off' }, + ] }, +] +const PROV_BY_ID = Object.fromEntries(PROVIDERS.flatMap((g) => g.items).map((p) => [p.id, p])) + +function ProviderIcon({ id, size = 40 }: { id: string; size?: number }) { + const I = CLOUD_ICON[id] + return I ? I({ size }) : null +} + +function ProviderGrid({ onPick }: { onPick: (id: string) => void }) { + return ( +
      +

      Escolha onde guardar os backups.

      + {PROVIDERS.map((g) => ( +
      +

      {g.group}

      +
      + {g.items.map((p) => { + const on = p.state === 'ok' + return ( + + ) + })} +
      +
      + ))} +
      + ) +} export default function Clouds({ me }: { me: User }) { const [accounts, setAccounts] = useState([]) const [err, setErr] = useState('') const [info, setInfo] = useState('') const [defs, setDefs] = useState<{ gdrive?: boolean; gdrive_web?: boolean; broker?: string }>({}) - const [wizard, setWizard] = useState<{ id?: number; device?: DeviceInfo; name?: string } | null>(null) + const [wizard, setWizard] = useState<{ id?: number; device?: DeviceInfo; name?: string; type?: string } | null>(null) const isAdmin = me.role === 'admin' const load = useCallback(() => { @@ -48,9 +102,12 @@ export default function Clouds({ me }: { me: User }) { return (
      -
      -
      {a.name}
      -
      {CLOUD_LABEL[a.type]}{a.account_label && ` · ${a.account_label}`}
      +
      + +
      +
      {a.name}
      +
      {CLOUD_LABEL[a.type]}{a.account_label && ` · ${a.account_label}`}
      +
      {a.status === 'connected' ? Conectada : a.status === 'error' ? Erro : Aguardando autorização}
      @@ -72,17 +129,18 @@ export default function Clouds({ me }: { me: User }) { })}
      - {wizard && { setWizard(null); load() }}> + {wizard && { setWizard(null); load() }}> {wizard.device && wizard.id ? { setWizard(null); setInfo('Conta conectada com sucesso.'); load() }} /> - : { setWizard({ id, device, name }); load() }} onConnected={() => { setWizard(null); setInfo('Conta conectada com sucesso.'); load() }} />} + : !wizard.type ? setWizard({ type })} /> + : setWizard({})} defs={defs} onCreated={(id, device, name) => { setWizard({ id, device, name }); load() }} onConnected={() => { setWizard(null); setInfo('Conta conectada com sucesso.'); load() }} />} }
    ) } -function NewAccount({ onCreated, onConnected, defs }: { onCreated: (id: number, device: DeviceInfo, name: string) => void; onConnected: () => void; defs: { gdrive?: boolean; gdrive_web?: boolean; broker?: string } }) { - const [f, setF] = useState({ type: 'onedrive', name: '', client_id: '', client_secret: '', tenant: '' }) +function NewAccount({ type, onBack, onCreated, onConnected, defs }: { type: string; onBack: () => void; onCreated: (id: number, device: DeviceInfo, name: string) => void; onConnected: () => void; defs: { gdrive?: boolean; gdrive_web?: boolean; broker?: string } }) { + const [f, setF] = useState({ type, name: '', client_id: '', client_secret: '', tenant: '' }) const [mode, setMode] = useState<'auto' | 'code' | 'own'>('auto') const [err, setErr] = useState('') const [busy, setBusy] = useState(false) @@ -124,10 +182,12 @@ function NewAccount({ onCreated, onConnected, defs }: { onCreated: (id: number, const od = f.type === 'onedrive' return (
    -
    - - setF({ ...f, name: e.target.value })} required /> +
    + +
    {PROV_BY_ID[type]?.label}
    {PROV_BY_ID[type]?.hint}
    +
    + setF({ ...f, name: e.target.value })} required /> {web && (
    Uma janela do Google vai abrir para você entrar e autorizar. O Coruja só enxerga os arquivos que ele mesmo criar.{' '} From 20bef6bd117d9c8c60f0d7d73e727b0eb30318c0 Mon Sep 17 00:00:00 2001 From: Henrique Fagundes Date: Thu, 26 Nov 2026 09:59:45 -0300 Subject: [PATCH 07/12] =?UTF-8?q?Fase=209:=20login=20por=20popup=20do=20On?= =?UTF-8?q?eDrive=20(cliente=20p=C3=BAblico)=20e=20retorno=20do=20site=20p?= =?UTF-8?q?ara=20Microsoft=20e=20Dropbox?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- internal/cloud/defaults.go | 30 +++++++++++++++++++++-- internal/cloud/gdrive.go | 3 ++- internal/cloud/oauth.go | 9 ++++--- internal/cloud/onedrive.go | 4 +++- internal/cloudmgr/cloudmgr.go | 2 +- internal/e2e/e2e_test.go | 38 ++++++++++++++++++++++++++++++ internal/httpapi/handlers_cloud.go | 2 +- site/docker-compose.yml | 2 +- site/nginx.conf | 2 +- web/src/pages/Clouds.tsx | 22 +++++++++-------- 10 files changed, 93 insertions(+), 21 deletions(-) diff --git a/internal/cloud/defaults.go b/internal/cloud/defaults.go index a0c2b9f..0c09b2d 100644 --- a/internal/cloud/defaults.go +++ b/internal/cloud/defaults.go @@ -25,15 +25,41 @@ var ( 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" + // HasWebApp informa se o login por popup (aplicativo da Web) está disponível para o tipo de nuvem. func HasWebApp(typ string) bool { - return typ == TypeGDrive && DefaultGoogleWebClientID != "" && DefaultGoogleWebClientSecret != "" && OAuthBrokerURL != "" + if OAuthBrokerURL == "" { + return false + } + switch typ { + case TypeGDrive: + return DefaultGoogleWebClientID != "" && DefaultGoogleWebClientSecret != "" + case TypeOneDrive: + return DefaultMicrosoftClientID != "" + } + 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, "" + } + return "", "" } // BrokerRedirect devolve o endereço de retorno cadastrado no provedor para o tipo de nuvem. func BrokerRedirect(typ string) string { - if typ == TypeGDrive { + switch typ { + case TypeGDrive: return strings.TrimRight(OAuthBrokerURL, "/") + "/oauth/google/callback" + case TypeOneDrive: + return strings.TrimRight(OAuthBrokerURL, "/") + "/oauth/microsoft/callback" } return "" } diff --git a/internal/cloud/gdrive.go b/internal/cloud/gdrive.go index 0a410bc..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", AuthURL: "https://accounts.google.com/o/oauth2/v2/auth", 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/oauth.go b/internal/cloud/oauth.go index f77bd49..feab198 100644 --- a/internal/cloud/oauth.go +++ b/internal/cloud/oauth.go @@ -33,7 +33,8 @@ type OAuth struct { ClientID string ClientSecret string DeviceURL string - AuthURL string // fluxo com retorno (popup) + 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 @@ -205,8 +206,10 @@ func (ts *TokenSource) Access(ctx context.Context) (string, error) { // 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"}, - "access_type": {"offline"}, "prompt": {"consent"}, "include_granted_scopes": {"false"}} + "state": {state}, "code_challenge": {challenge}, "code_challenge_method": {"S256"}} + for k, v := range o.AuthExtra { + q[k] = v + } return o.AuthURL + "?" + q.Encode() } 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 cbfe47f..5f829d9 100644 --- a/internal/cloudmgr/cloudmgr.go +++ b/internal/cloudmgr/cloudmgr.go @@ -74,7 +74,7 @@ func (m *Manager) oauth(typ string, cfg AccountConfig) (*cloud.OAuth, error) { 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.DefaultGoogleWebClientID, cloud.DefaultGoogleWebClientSecret + 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") diff --git a/internal/e2e/e2e_test.go b/internal/e2e/e2e_test.go index 0f55388..d2f532e 100644 --- a/internal/e2e/e2e_test.go +++ b/internal/e2e/e2e_test.go @@ -643,3 +643,41 @@ func mustParse(t *testing.T, s string) *url.URL { } 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)) + } +} diff --git a/internal/httpapi/handlers_cloud.go b/internal/httpapi/handlers_cloud.go index c74ba60..d73d831 100644 --- a/internal/httpapi/handlers_cloud.go +++ b/internal/httpapi/handlers_cloud.go @@ -30,7 +30,7 @@ func (s *Server) listClouds(w http.ResponseWriter, r *http.Request, _ *ctxUser) n, _ := s.Store.JobsUsingCloud(r.Context(), a.ID) out = append(out, cloudView{a, n}) } - writeJSON(w, 200, map[string]any{"accounts": out, "defaults": map[string]any{"gdrive": cloud.HasDefaultApp(cloud.TypeGDrive), "gdrive_web": cloud.HasWebApp(cloud.TypeGDrive), "broker": strings.TrimRight(cloud.OAuthBrokerURL, "/")}}) + 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), "broker": strings.TrimRight(cloud.OAuthBrokerURL, "/")}}) } func deviceView(d *cloud.Device) map[string]any { diff --git a/site/docker-compose.yml b/site/docker-compose.yml index a942578..6b467cd 100644 --- a/site/docker-compose.yml +++ b/site/docker-compose.yml @@ -1,6 +1,6 @@ services: coruja-site: - image: coruja-site:1.1.0 + image: coruja-site:1.2.0 container_name: coruja-site restart: always read_only: true diff --git a/site/nginx.conf b/site/nginx.conf index 61bdfc2..6474ab7 100644 --- a/site/nginx.conf +++ b/site/nginx.conf @@ -11,7 +11,7 @@ server { 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/callback { + location ~ ^/oauth/(google|microsoft|dropbox)/callback$ { access_log off; default_type text/html; add_header Cache-Control "no-store" always; diff --git a/web/src/pages/Clouds.tsx b/web/src/pages/Clouds.tsx index f78ebc3..fe95dfb 100644 --- a/web/src/pages/Clouds.tsx +++ b/web/src/pages/Clouds.tsx @@ -21,6 +21,7 @@ const PROVIDERS: { group: string; items: Prov[] }[] = [ { id: 'smb', label: 'Pasta de rede', hint: 'SMB, NFS, iSCSI', state: 'off' }, ] }, ] +type Defs = { gdrive?: boolean; gdrive_web?: boolean; onedrive_web?: boolean; broker?: string } const PROV_BY_ID = Object.fromEntries(PROVIDERS.flatMap((g) => g.items).map((p) => [p.id, p])) function ProviderIcon({ id, size = 40 }: { id: string; size?: number }) { @@ -60,12 +61,12 @@ export default function Clouds({ me }: { me: User }) { const [accounts, setAccounts] = useState([]) const [err, setErr] = useState('') const [info, setInfo] = useState('') - const [defs, setDefs] = useState<{ gdrive?: boolean; gdrive_web?: boolean; broker?: string }>({}) + const [defs, setDefs] = useState({}) const [wizard, setWizard] = useState<{ id?: number; device?: DeviceInfo; name?: string; type?: string } | null>(null) const isAdmin = me.role === 'admin' const load = useCallback(() => { - api<{ accounts: CloudAccount[]; defaults?: { gdrive?: boolean; gdrive_web?: boolean; broker?: string } }>('GET', '/api/clouds').then((r) => { setAccounts(r.accounts); setDefs(r.defaults ?? {}); setErr('') }).catch((x) => setErr((x as ApiError).message)) + api<{ accounts: CloudAccount[]; defaults?: Defs }>('GET', '/api/clouds').then((r) => { setAccounts(r.accounts); setDefs(r.defaults ?? {}); setErr('') }).catch((x) => setErr((x as ApiError).message)) }, []) useEffect(() => { load() }, [load]) @@ -139,13 +140,15 @@ export default function Clouds({ me }: { me: User }) { ) } -function NewAccount({ type, onBack, onCreated, onConnected, defs }: { type: string; onBack: () => void; onCreated: (id: number, device: DeviceInfo, name: string) => void; onConnected: () => void; defs: { gdrive?: boolean; gdrive_web?: boolean; broker?: string } }) { +function NewAccount({ type, onBack, onCreated, onConnected, defs }: { type: string; onBack: () => void; onCreated: (id: number, device: DeviceInfo, name: string) => void; onConnected: () => void; defs: Defs }) { const [f, setF] = useState({ type, name: '', client_id: '', client_secret: '', tenant: '' }) const [mode, setMode] = useState<'auto' | 'code' | 'own'>('auto') const [err, setErr] = useState('') const [busy, setBusy] = useState(false) const gd = f.type === 'gdrive' - const web = gd && !!defs.gdrive_web && mode === 'auto' // botão único: popup do Google + const od0 = f.type === 'onedrive' + const web = ((gd && !!defs.gdrive_web) || (od0 && !!defs.onedrive_web)) && mode === 'auto' // botão único: popup do provedor + const who = od0 ? 'a Microsoft' : 'o Google' // com artigo: "com a Microsoft", "com o Google" const std = gd && !web && !!defs.gdrive && mode !== 'own' // aplicativo padrão com código de dispositivo const noCreds = web || std // nada de ID/segredo para preencher async function viaPopup() { @@ -160,7 +163,7 @@ function NewAccount({ type, onBack, onCreated, onConnected, defs }: { type: stri const end = (fn: () => void) => { if (settled) return; settled = true; window.removeEventListener('message', onMsg); clearInterval(timer); fn() } const onMsg = (ev: MessageEvent) => { if (ev.origin !== defs.broker || ev.data?.type !== 'coruja-oauth' || ev.data.state !== r.state) return - if (ev.data.error) return end(() => reject(new Error(ev.data.error === 'access_denied' ? 'Você não autorizou o acesso.' : `O Google recusou: ${ev.data.error}`))) + if (ev.data.error) return end(() => reject(new Error(ev.data.error === 'access_denied' ? 'Você não autorizou o acesso.' : `O provedor recusou: ${ev.data.error}`))) api('POST', '/api/clouds/oauth/finish', { state: r.state, code: ev.data.code }).then(() => end(resolve), (x) => end(() => reject(x))) } window.addEventListener('message', onMsg) @@ -190,9 +193,8 @@ function NewAccount({ type, onBack, onCreated, onConnected, defs }: { type: stri setF({ ...f, name: e.target.value })} required /> {web && (
    - Uma janela do Google vai abrir para você entrar e autorizar. O Coruja só enxerga os arquivos que ele mesmo criar.{' '} - - {' · '} + Uma janela {od0 ? 'da Microsoft' : 'do Google'} vai abrir para você entrar e autorizar.{od0 ? '' : ' O Coruja só enxerga os arquivos que ele mesmo criar.'}{' '} + {gd && defs.gdrive && <>{' · '}}
    )} @@ -202,7 +204,7 @@ function NewAccount({ type, onBack, onCreated, onConnected, defs }: { type: stri
    )} - {gd && (defs.gdrive || defs.gdrive_web) && mode !== 'auto' && } + {((gd && (defs.gdrive || defs.gdrive_web)) || (od0 && defs.onedrive_web)) && mode !== 'auto' && } {!noCreds && setF({ ...f, client_id: e.target.value })} required />} {noCreds ? null : od ? (
    @@ -232,7 +234,7 @@ function NewAccount({ type, onBack, onCreated, onConnected, defs }: { type: stri )} } - + ) } From d4555d8ed35034b3618388c74d58bcf426c8b28d Mon Sep 17 00:00:00 2001 From: Henrique Fagundes Date: Thu, 26 Nov 2026 10:10:30 -0300 Subject: [PATCH 08/12] site: logo 215px para o registro do aplicativo Microsoft Co-Authored-By: Claude Sonnet 5.5 --- site/logo-215.png | Bin 0 -> 7829 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 site/logo-215.png diff --git a/site/logo-215.png b/site/logo-215.png new file mode 100644 index 0000000000000000000000000000000000000000..8c828d5a872c34f6c18d268dc8814ab1036d7f89 GIT binary patch literal 7829 zcmXw81ymH@+a9_b1*99Kmk{ZYkOrlfSU^FVC8ed2?vU>8T41RKlt!dPx{*dY|NHyS z`Och~JLf$2ea{q_u0V?vfV?Bl2b-KS$0D`>I?x{_eI8kuM1dMWb>1$EOesDz$hip>RGy6U`XJI-|7hhY%@K|!N%2!00MfHv z%+Trgb5P=8$y2H*4FI40Y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~EP>?jGW>_X+`Zr3yoZ>)JYFcddb8??#gJ0~Lrj&gLy6o$>ZX*QZ=lLxoBE{Ol! a6V?-oCg)GQURI>e47^p)cvB;19`rwMzZEe6 literal 0 HcmV?d00001 From 754f8137becad06df553b22bec414fabde36dbd7 Mon Sep 17 00:00:00 2001 From: Henrique Fagundes Date: Thu, 26 Nov 2026 10:35:58 -0300 Subject: [PATCH 09/12] =?UTF-8?q?site:=20=C3=ADcones=2064=20e=20256=20px?= =?UTF-8?q?=20para=20o=20aplicativo=20do=20Dropbox?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- site/logo-256.png | Bin 0 -> 7629 bytes site/logo-64.png | Bin 0 -> 1866 bytes 2 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 site/logo-256.png create mode 100644 site/logo-64.png diff --git a/site/logo-256.png b/site/logo-256.png new file mode 100644 index 0000000000000000000000000000000000000000..2418c0dc8a50b5f00fe6d5a67f6443d9c0e3eec8 GIT binary patch literal 7629 zcmaJ`by!r-*T1_gT?+^-xJWC~C=JpGNF&{;G)N<{t1OL#q;v@=($clGf|MdHjdXV` zyzB4z{{24pkD2G*nK_>`=gjBKJttC2Ly44#o(KQ{QWa$d9RL7fyC8r758Ie}l)S(; zc-E>)3c&5ZC%3gY5daw8swl|n`ep9?@ekDfJ%ztN-}pE&h&3K&)M?EW4-i>VP-@?) zGBzpWi6}Gf84n$)uPt+Nsr_j@KRwtM%tm1n9YL%!ukW(e8%>Euv2$0mF(Xk>0_Hc| zi7xLyG_GM-Azf*2S-c))N_?Bg@BvpLUQF%m0#3K}Dg7sWApy25X`(!Pn_ z=eH!m*R+l4@rX49;5aR!Uk$mZeG={FdA1r6;@vmj zo#8s#aTy&+hNi7~+?Hw??PW2jXD5~RniO3v`#_kG=MP-81W?qf{Jx=8w=H^^Y38Lh zhjIotI3CJB*V8isFBtRx0Kyf$)KKRgxRxTwINjvds-2O3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k&?n$FDTy=Jh2xY!IskD-m>qD|-L!vD$H&y`RtcjUfAt0uL(cCPD@{cwUzm z<}bW7PWm`SulWEgO^G~X3g~r3g++!!J?@3vwYh?N?*WV?sk1!I4S}y`Yd<9_+M#-9HQPxOR2f$S(7@r#(BkTb56NV2NDpWT{}lU zy#BCM-Km}*LKq1dand;L`c5O--XYe0S1=5jrYdG*xMe#ol&$I&eMg5dx8h$7#N9{Y zP8$G!ENg(r*3tm$(-^AMw(7quvm4&HQILi*X8@P|gQoQ4?3bKF?mRZz^zKr0GKK36 z1RDj!aD22Mh3Jg!^YavJ%};n#)}M-o5dDjVyE-%bk+UGSdRgks0vm=*!g>?Xbk?A5 z9Az*RpGnTXl5N%-#~x>dB=_WczAPq>h_e)xug}T*(L;5$($P|JaxnSgR@dw|9p~ST R0&IO2P*K!SD3`N*`+ubIaYq0E literal 0 HcmV?d00001 diff --git a/site/logo-64.png b/site/logo-64.png new file mode 100644 index 0000000000000000000000000000000000000000..b401f029ae069c9a1ee592c999bf2e485d348288 GIT binary patch literal 1866 zcmV-Q2etT#P)J|p51Ml&tG@%z2D#c-rsrLbI#o>m>*HTVrPjIwn~r{Xk;VF1Ckb? zjV5D27n17;&S;XOb*%?4%qJ3a9V>HHJq5fB+^5QAR1vgG!e#$ItSoK`K zW*C2wur{IwqlP?h)3xuOX+O{rdL%3X1|(e1JkNoH)kMGdbZu{IJbY{*JY7?j7_NUV^^3QY=`8*3vmLy)TpM0Tuw#0*KU1|*x& z{`84YaM*Rljuuax-Qb6hx0sbDYxAEoI}feC#&5Sbk-hX&vmq>#nL5sIo^Imt`@2lX zFr5H^f~;X`o@ro1VXu`irg$K~kGGy}U`5W5r8t%n0FdOER3@BRmqmkuGvy%E(f7NrTWIUghb z!TpH1;CCiknhPz>g}rb)6OFskJC8?1Zw6&ez~+36g!12onGZz7C6Q46du+}}mFvx- zBmu&aLHvXJ34P6Q^TrT2Z-kBs#Al_PkgiN`1tm?uUbro&J`;=GT?zt)Qd^*m5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xcJ8OLPXHGwXW^W)0z;QfE!V_7J0k~`DlI18+Cy@!v^kko&)tZ zU93ZJE_&V~PQ7mErS+bg+Ry`YemuRQsCvuP*HtSb=PhywXqB4WQ-87M$Qmb7O04B>(^b07*qoM6N<$ Ef(fRZjsO4v literal 0 HcmV?d00001 From d962212a98b1f43fc01d299f889423b853d47064 Mon Sep 17 00:00:00 2001 From: Henrique Fagundes Date: Thu, 26 Nov 2026 10:52:06 -0300 Subject: [PATCH 10/12] =?UTF-8?q?Fase=209:=20conector=20do=20Dropbox,=20re?= =?UTF-8?q?autoriza=C3=A7=C3=A3o=20por=20popup=20e=20corre=C3=A7=C3=A3o=20?= =?UTF-8?q?do=20arquivo=20divergente=20que=20ficava=20na=20nuvem?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 3 + docs/SEGURANCA.md | 4 + internal/agentcore/core.go | 8 +- internal/agentsrv/agentsrv.go | 4 +- internal/cloud/cloud.go | 8 +- internal/cloud/cloudtest/dropbox.go | 222 +++++++++++++++++++++ internal/cloud/defaults.go | 9 + internal/cloud/dropbox.go | 296 ++++++++++++++++++++++++++++ internal/cloud/dropbox_test.go | 44 +++++ internal/cloud/hash.go | 7 +- internal/cloud/oauth.go | 23 +++ internal/cloudmgr/cloudmgr.go | 73 +++++-- internal/e2e/e2e_test.go | 77 ++++++++ internal/httpapi/handlers_cloud.go | 30 +-- internal/httpapi/httpapi.go | 2 + internal/httpapi/httpapi_test.go | 4 + internal/notify/service_test.go | 2 +- internal/pb/agent.pb.go | 37 +++- internal/uploader/dropbox.go | 170 ++++++++++++++++ internal/uploader/dropbox_test.go | 52 +++++ internal/uploader/uploader.go | 26 ++- proto/coruja/v1/agent.proto | 5 +- web/src/api.ts | 4 +- web/src/pages/Clouds.tsx | 63 +++--- 24 files changed, 1101 insertions(+), 72 deletions(-) create mode 100644 internal/cloud/cloudtest/dropbox.go create mode 100644 internal/cloud/dropbox.go create mode 100644 internal/cloud/dropbox_test.go create mode 100644 internal/uploader/dropbox.go create mode 100644 internal/uploader/dropbox_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 322fd05..52b427e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,9 @@ # Changelog ## [Não publicado] - Fase 9 +- **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 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/defaults.go b/internal/cloud/defaults.go index 0c09b2d..1b8f5ba 100644 --- a/internal/cloud/defaults.go +++ b/internal/cloud/defaults.go @@ -28,6 +28,9 @@ var ( // 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 == "" { @@ -38,6 +41,8 @@ func HasWebApp(typ string) bool { return DefaultGoogleWebClientID != "" && DefaultGoogleWebClientSecret != "" case TypeOneDrive: return DefaultMicrosoftClientID != "" + case TypeDropbox: + return DefaultDropboxAppKey != "" } return false } @@ -49,6 +54,8 @@ func WebAppCreds(typ string) (id, secret string) { return DefaultGoogleWebClientID, DefaultGoogleWebClientSecret case TypeOneDrive: return DefaultMicrosoftClientID, "" + case TypeDropbox: + return DefaultDropboxAppKey, "" } return "", "" } @@ -60,6 +67,8 @@ func BrokerRedirect(typ string) string { 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/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 feab198..46bac1e 100644 --- a/internal/cloud/oauth.go +++ b/internal/cloud/oauth.go @@ -232,3 +232,26 @@ func (o *OAuth) ExchangeCode(ctx context.Context, code, verifier, redirect strin } 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/cloudmgr/cloudmgr.go b/internal/cloudmgr/cloudmgr.go index 5f829d9..3ce4bef 100644 --- a/internal/cloudmgr/cloudmgr.go +++ b/internal/cloudmgr/cloudmgr.go @@ -30,6 +30,9 @@ type Endpoints struct { Graph string GDevice, GToken string GAuth string + DBXToken string + DBXAPI string + DBXContent string GAPI, GUpload string } @@ -60,6 +63,7 @@ type Manager struct { type pendingWeb struct { Name, Typ, Origin, Verifier string + AccountID int64 // != 0: reautorização de uma conta existente Expires time.Time } @@ -96,6 +100,11 @@ func (m *Manager) oauth(typ string, cfg AccountConfig) (*cloud.OAuth, error) { 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) } @@ -314,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) } @@ -374,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 @@ -412,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 { @@ -477,13 +500,39 @@ 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 { + if accs, e := m.Store.ListClouds(ctx); e == nil && accountID == 0 { for _, a := range accs { if a.Name == name { return "", "", store.ErrDuplicate @@ -515,7 +564,7 @@ func (m *Manager) BeginWeb(ctx context.Context, name, typ, origin string) (login 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), Expires: now.Add(10 * time.Minute)} + 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 } @@ -546,14 +595,16 @@ func (m *Manager) FinishWeb(ctx context.Context, state, code string) (int64, err if err != nil { return 0, err } - cj, _ := json.Marshal(cfg) - sc, err := m.Box.Seal(string(cj)) - if err != nil { - return 0, err - } - id, err := m.Store.CreateCloud(ctx, p.Name, p.Typ, sc, "") - 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)) diff --git a/internal/e2e/e2e_test.go b/internal/e2e/e2e_test.go index d2f532e..de7d275 100644 --- a/internal/e2e/e2e_test.go +++ b/internal/e2e/e2e_test.go @@ -681,3 +681,80 @@ func TestOneDriveLoginPorPopup(t *testing.T) { 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 d73d831..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, "defaults": map[string]any{"gdrive": cloud.HasDefaultApp(cloud.TypeGDrive), "gdrive_web": cloud.HasWebApp(cloud.TypeGDrive), "onedrive_web": cloud.HasWebApp(cloud.TypeOneDrive), "broker": strings.TrimRight(cloud.OAuthBrokerURL, "/")}}) + 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 { @@ -170,19 +171,26 @@ func (s *Server) beginCloudWeb(w http.ResponseWriter, r *http.Request, cu *ctxUs return } var in struct { - Name string `json:"name"` - Type string `json:"type"` - Origin string `json:"origin"` + 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 } - 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 + 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) } - 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 diff --git a/internal/httpapi/httpapi.go b/internal/httpapi/httpapi.go index 84dc764..161e4dc 100644 --- a/internal/httpapi/httpapi.go +++ b/internal/httpapi/httpapi.go @@ -46,6 +46,8 @@ type CloudAdmin interface { 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) } diff --git a/internal/httpapi/httpapi_test.go b/internal/httpapi/httpapi_test.go index fcbea4f..9c02135 100644 --- a/internal/httpapi/httpapi_test.go +++ b/internal/httpapi/httpapi_test.go @@ -564,6 +564,10 @@ 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") 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/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/web/src/api.ts b/web/src/api.ts index 8cb9ed9..b7a3d50 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -67,11 +67,11 @@ export const ENGINE_LABEL: Record = { mysql: 'MySQL', mariadb: ' export const ENGINE_PORT: Record = { mysql: 3306, mariadb: 3306, postgres: 5432, mongodb: 27017 } export type CloudAccount = { - id: number; name: string; type: 'onedrive' | 'gdrive'; status: 'pending' | 'connected' | 'error'; account_label: string + id: number; name: string; type: 'onedrive' | 'gdrive' | 'dropbox'; popup?: boolean; status: 'pending' | 'connected' | 'error'; account_label: string quota_total: number; quota_used: number; quota_checked_at: string | null; last_error: string; created_at: string; jobs: number } export type DeviceInfo = { user_code: string; verification_uri: string; expires_at: string; interval: number } -export const CLOUD_LABEL = { onedrive: 'OneDrive', gdrive: 'Google Drive' } as const +export const CLOUD_LABEL = { onedrive: 'OneDrive', gdrive: 'Google Drive', dropbox: 'Dropbox' } as const export const PHASE: Record = { archiving: 'Compactando', uploading: 'Enviando para a nuvem', verifying: 'Conferindo' } export const CRON_PRESETS: { label: string; cron: string }[] = [ diff --git a/web/src/pages/Clouds.tsx b/web/src/pages/Clouds.tsx index fe95dfb..3c9fbb1 100644 --- a/web/src/pages/Clouds.tsx +++ b/web/src/pages/Clouds.tsx @@ -9,7 +9,7 @@ const PROVIDERS: { group: string; items: Prov[] }[] = [ { group: 'Nuvem', items: [ { id: 'gdrive', label: 'Google Drive', hint: 'Entre com a sua conta Google', state: 'ok' }, { id: 'onedrive', label: 'OneDrive', hint: 'Microsoft pessoal ou corporativo', state: 'ok' }, - { id: 'dropbox', label: 'Dropbox', hint: 'Entre com a sua conta Dropbox', state: 'soon' }, + { id: 'dropbox', label: 'Dropbox', hint: 'Entre com a sua conta Dropbox', state: 'ok' }, { id: 's3', label: 'Amazon S3', hint: 'AWS, MinIO, Wasabi…', state: 'off' }, { id: 'b2', label: 'Backblaze B2', hint: 'Armazenamento econômico', state: 'off' }, { id: 'box', label: 'Box', hint: 'Armazenamento corporativo', state: 'off' }, @@ -21,7 +21,7 @@ const PROVIDERS: { group: string; items: Prov[] }[] = [ { id: 'smb', label: 'Pasta de rede', hint: 'SMB, NFS, iSCSI', state: 'off' }, ] }, ] -type Defs = { gdrive?: boolean; gdrive_web?: boolean; onedrive_web?: boolean; broker?: string } +type Defs = { gdrive?: boolean; gdrive_web?: boolean; onedrive_web?: boolean; dropbox_web?: boolean; broker?: string } const PROV_BY_ID = Object.fromEntries(PROVIDERS.flatMap((g) => g.items).map((p) => [p.id, p])) function ProviderIcon({ id, size = 40 }: { id: string; size?: number }) { @@ -57,6 +57,28 @@ function ProviderGrid({ onPick }: { onPick: (id: string) => void }) { ) } +// Login por popup: abre a janela já no clique (senão o navegador bloqueia), pede o endereço ao Server, espera o código que +// a página de retorno entrega por postMessage (só aceita a origem do intermediário) e conclui no Server. +async function popupLogin(body: Record, broker: string) { + const pop = window.open('', 'coruja-oauth', 'width=520,height=700') + if (!pop) throw new Error('O navegador bloqueou a janela. Libere pop-ups para este endereço e tente de novo.') + try { + const r = await api<{ url: string; state: string }>('POST', '/api/clouds/oauth/begin', { ...body, origin: window.location.origin }) + pop.location.href = r.url + await new Promise((resolve, reject) => { + let settled = false + const end = (fn: () => void) => { if (settled) return; settled = true; window.removeEventListener('message', onMsg); clearInterval(timer); fn() } + const onMsg = (ev: MessageEvent) => { + if (ev.origin !== broker || ev.data?.type !== 'coruja-oauth' || ev.data.state !== r.state) return + if (ev.data.error) return end(() => reject(new Error(ev.data.error === 'access_denied' ? 'Você não autorizou o acesso.' : `O provedor recusou: ${ev.data.error}`))) + api('POST', '/api/clouds/oauth/finish', { state: r.state, code: ev.data.code }).then(() => end(resolve), (x) => end(() => reject(x))) + } + window.addEventListener('message', onMsg) + const timer = window.setInterval(() => { if (pop.closed) setTimeout(() => end(() => reject(new Error('A janela foi fechada antes de terminar.'))), 1500) }, 500) + }) + } finally { try { pop.close() } catch { /* já fechou */ } } +} + export default function Clouds({ me }: { me: User }) { const [accounts, setAccounts] = useState([]) const [err, setErr] = useState('') @@ -81,6 +103,10 @@ export default function Clouds({ me }: { me: User }) { } catch (x) { setErr((x as ApiError).message) } } async function reauth(a: CloudAccount) { + if (a.popup) { + try { await popupLogin({ account_id: a.id, type: a.type }, defs.broker ?? ''); setErr(''); setInfo(`"${a.name}" reautorizada.`); load() } catch (x) { setInfo(''); setErr((x as Error).message) } + return + } try { const r = await api<{ device: DeviceInfo }>('POST', `/api/clouds/${a.id}/reauthorize`); setWizard({ id: a.id, device: r.device, name: a.name }) } catch (x) { setErr((x as ApiError).message) } } @@ -147,31 +173,14 @@ function NewAccount({ type, onBack, onCreated, onConnected, defs }: { type: stri const [busy, setBusy] = useState(false) const gd = f.type === 'gdrive' const od0 = f.type === 'onedrive' - const web = ((gd && !!defs.gdrive_web) || (od0 && !!defs.onedrive_web)) && mode === 'auto' // botão único: popup do provedor - const who = od0 ? 'a Microsoft' : 'o Google' // com artigo: "com a Microsoft", "com o Google" + const dbx = f.type === 'dropbox' // só existe pelo popup + const web = dbx || (((gd && !!defs.gdrive_web) || (od0 && !!defs.onedrive_web)) && mode === 'auto') // botão único: popup do provedor + const who = dbx ? 'o Dropbox' : od0 ? 'a Microsoft' : 'o Google' // com artigo: "com a Microsoft", "com o Google" const std = gd && !web && !!defs.gdrive && mode !== 'own' // aplicativo padrão com código de dispositivo const noCreds = web || std // nada de ID/segredo para preencher async function viaPopup() { - // abre o popup já no clique (senão o navegador bloqueia) e só depois descobre o endereço - const pop = window.open('', 'coruja-oauth', 'width=520,height=700') - if (!pop) { setErr('O navegador bloqueou a janela. Libere pop-ups para este endereço ou use o código.'); return } - try { - const r = await api<{ url: string; state: string }>('POST', '/api/clouds/oauth/begin', { name: f.name, type: f.type, origin: window.location.origin }) - pop.location.href = r.url - await new Promise((resolve, reject) => { - let settled = false - const end = (fn: () => void) => { if (settled) return; settled = true; window.removeEventListener('message', onMsg); clearInterval(timer); fn() } - const onMsg = (ev: MessageEvent) => { - if (ev.origin !== defs.broker || ev.data?.type !== 'coruja-oauth' || ev.data.state !== r.state) return - if (ev.data.error) return end(() => reject(new Error(ev.data.error === 'access_denied' ? 'Você não autorizou o acesso.' : `O provedor recusou: ${ev.data.error}`))) - api('POST', '/api/clouds/oauth/finish', { state: r.state, code: ev.data.code }).then(() => end(resolve), (x) => end(() => reject(x))) - } - window.addEventListener('message', onMsg) - const timer = window.setInterval(() => { if (pop.closed) setTimeout(() => end(() => reject(new Error('A janela foi fechada antes de terminar.'))), 1500) }, 500) - }) - try { pop.close() } catch { /* já fechou */ } - onConnected() - } catch (x) { try { pop.close() } catch { /* ok */ } throw x } + await popupLogin({ name: f.name, type: f.type }, defs.broker ?? '') + onConnected() } async function submit(e: FormEvent) { e.preventDefault(); setErr(''); setBusy(true) @@ -179,7 +188,7 @@ function NewAccount({ type, onBack, onCreated, onConnected, defs }: { type: stri if (web) { await viaPopup(); return } const r = await api<{ id: number; device: DeviceInfo }>('POST', '/api/clouds', std ? { ...f, client_id: '', client_secret: '' } : f) onCreated(r.id, r.device, f.name) - } catch (x) { setErr((x as ApiError).message) } finally { setBusy(false) } + } catch (x) { setErr((x as Error).message) } finally { setBusy(false) } } const sel = 'w-full rounded-lg border border-border bg-surface px-3 py-2' const od = f.type === 'onedrive' @@ -193,9 +202,9 @@ function NewAccount({ type, onBack, onCreated, onConnected, defs }: { type: stri setF({ ...f, name: e.target.value })} required /> {web && (
    - Uma janela {od0 ? 'da Microsoft' : 'do Google'} vai abrir para você entrar e autorizar.{od0 ? '' : ' O Coruja só enxerga os arquivos que ele mesmo criar.'}{' '} + Uma janela {dbx ? 'do Dropbox' : od0 ? 'da Microsoft' : 'do Google'} vai abrir para você entrar e autorizar.{od0 ? '' : dbx ? ' O Coruja só enxerga a própria pasta dentro do seu Dropbox (Aplicativos › Coruja Backup).' : ' O Coruja só enxerga os arquivos que ele mesmo criar.'}{' '} {gd && defs.gdrive && <>{' · '}} - + {!dbx && }
    )} {std && ( From 5ca47c34ad8a21ad38a1515ac3e369d5b69ccba9 Mon Sep 17 00:00:00 2001 From: Henrique Fagundes Date: Thu, 26 Nov 2026 10:59:04 -0300 Subject: [PATCH 11/12] =?UTF-8?q?web:=20n=C3=A3o=20acusar=20janela=20fecha?= =?UTF-8?q?da=20enquanto=20o=20Server=20conclui=20o=20login=20por=20popup?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- web/src/pages/Clouds.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/web/src/pages/Clouds.tsx b/web/src/pages/Clouds.tsx index 3c9fbb1..f09d048 100644 --- a/web/src/pages/Clouds.tsx +++ b/web/src/pages/Clouds.tsx @@ -67,14 +67,18 @@ async function popupLogin(body: Record, broker: string) { pop.location.href = r.url await new Promise((resolve, reject) => { let settled = false + let received = false // o código já chegou: a janela pode fechar, só falta o Server concluir const end = (fn: () => void) => { if (settled) return; settled = true; window.removeEventListener('message', onMsg); clearInterval(timer); fn() } const onMsg = (ev: MessageEvent) => { if (ev.origin !== broker || ev.data?.type !== 'coruja-oauth' || ev.data.state !== r.state) return + if (received) return + received = true + clearInterval(timer) if (ev.data.error) return end(() => reject(new Error(ev.data.error === 'access_denied' ? 'Você não autorizou o acesso.' : `O provedor recusou: ${ev.data.error}`))) api('POST', '/api/clouds/oauth/finish', { state: r.state, code: ev.data.code }).then(() => end(resolve), (x) => end(() => reject(x))) } window.addEventListener('message', onMsg) - const timer = window.setInterval(() => { if (pop.closed) setTimeout(() => end(() => reject(new Error('A janela foi fechada antes de terminar.'))), 1500) }, 500) + const timer = window.setInterval(() => { if (pop.closed) setTimeout(() => { if (!received) end(() => reject(new Error('A janela foi fechada antes de terminar.'))) }, 1500) }, 500) }) } finally { try { pop.close() } catch { /* já fechou */ } } } From 2dead5494a4fb280130b9078a30a4a6acd48c482 Mon Sep 17 00:00:00 2001 From: Henrique Fagundes Date: Thu, 26 Nov 2026 11:09:44 -0300 Subject: [PATCH 12/12] =?UTF-8?q?vers=C3=A3o=200.0.10?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 2 +- Dockerfile | 6 +++--- README.md | 8 ++++---- VERSION | 2 +- deploy/docker-compose.agent.yml | 2 +- deploy/docker-compose.server.yml | 2 +- docker-compose.dev.example.yml | 2 +- docs/ROADMAP.md | 11 ++++------- internal/version/version.go | 2 +- scripts/release.sh | 4 ++-- web/package.json | 2 +- web/src/App.tsx | 2 +- 12 files changed, 21 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 52b427e..61dc201 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## [Não publicado] - Fase 9 +## [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. diff --git a/Dockerfile b/Dockerfile index b5921b8..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 @@ -32,7 +32,7 @@ RUN --mount=type=secret,id=google_client_secret --mount=type=secret,id=google_we # --- Server ------------------------------------------------------------------------------------------------------------ FROM alpine:3.21 AS server -ARG VERSION=0.0.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" \ @@ -48,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/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/ROADMAP.md b/docs/ROADMAP.md index e2493cb..2da8dcc 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -9,13 +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):** entregue em etapas, cada uma testável sozinha: - - **9a · Modelo de destinos:** um job passa a ter uma lista de destinos (pasta local do agente + contas), cada um com retenção e conferência próprias; `Provider` ganha um tipo de sessão por protocolo. - - **9b · Compatíveis com S3** (AWS, MinIO, Wasabi, Backblaze): URLs pré-assinadas pelo Server, envio em partes (arquivos grandes), credenciais só no Server. - - **9c · Dropbox e SharePoint:** login por código no navegador (cartões com janela de login); SharePoint como biblioteca de documentos do OneDrive. - - **9d · Destinos diretos do agente:** SFTP e SMB (clientes Go nativos, credencial cifrada no Server e entregue ao agente), pasta local/volume do host (NFS e iSCSI montados 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/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/scripts/release.sh b/scripts/release.sh index 144356b..cc5de02 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -1,8 +1,8 @@ #!/bin/sh # Publicação manual das imagens multi-arquitetura (o fluxo normal é o workflow "Release", disparado pela tag vX.Y.Z). -# Uso: ./scripts/release.sh 0.0.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 diff --git a/web/package.json b/web/package.json index 6ca79b8..01b774d 100644 --- a/web/package.json +++ b/web/package.json @@ -1,7 +1,7 @@ { "name": "coruja-backup-web", "private": true, - "version": "0.0.9", + "version": "0.0.10", "type": "module", "scripts": { "dev": "vite", diff --git a/web/src/App.tsx b/web/src/App.tsx index 2d67f8d..1db8e5e 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -30,7 +30,7 @@ export default function App() { const [theme, setTheme] = useState('coruja') const [phase, setPhase] = useState('loading') const [me, setMe] = useState(null) - const [version, setVersion] = useState('0.0.9') + const [version, setVersion] = useState('0.0.10') const route = useRoute() const loadBrand = useCallback(() => {