Skip to content

fix: Harden mobile OAuth, Android cleartext config, and tracking contracts#21

Closed
BLACKBARGS wants to merge 10 commits intomainfrom
feat/orderhub-frontend
Closed

fix: Harden mobile OAuth, Android cleartext config, and tracking contracts#21
BLACKBARGS wants to merge 10 commits intomainfrom
feat/orderhub-frontend

Conversation

@BLACKBARGS
Copy link
Copy Markdown
Collaborator

🎯 Objetivo

Endurecer o fluxo de autenticação/OAuth mobile-first, corrigir riscos reais de produção no Android e no backend, separar comportamento demo de contrato de produção no tracking, eliminar vulnerabilidade transitiva sinalizada no pipeline e consolidar a documentação do snapshot atual.

📝 Descrição

Este PR consolida uma rodada de hardening full stack com foco em segurança, clareza de contrato e readiness de produto.

No backend:

  • separa callbacks web e nativos no fluxo OAuth, mantendo o backend como centro do processo
  • mantém o login Google mobile em Google -> API callback HTTPS -> deep link -> /auth/mobile/exchange
  • endurece a validação de returnUrl e callbacks nativos com allowlist dedicada
  • adiciona/ajusta testes para callback OAuth mobile, exchange code -> JWT e regras de validação
  • corrige a semântica de tracking:
    • GetTrackableOrdersAsync volta a representar apenas pedidos realmente rastreáveis, com TrackingCode
    • o fluxo demo foi separado para continuar avançando pedidos seedados sem contaminar o contrato do worker
  • ajusta a migration de perfil para não preencher DisplayName com string vazia, usando um valor válido por padrão
  • simplifica a validação do OAuthStateProtector e adiciona cobertura unitária
  • fixa a dependência transitiva vulnerável System.Security.Cryptography.Xml

No frontend/mobile:

  • mantém a UX mobile-first com deep links nativos para auth e vínculo de conta Google
  • remove a liberação global de cleartext no Android release
  • restringe android:usesCleartextTraffic e networkSecurityConfig aos source sets debug/profile
  • preserva o uso de HTTP local apenas para desenvolvimento (10.0.2.2 e IP da máquina)

Na documentação:

  • atualiza changelog, auditoria, checklist de segurança, README raiz e README do cliente
  • registra de forma explícita:
    • a diferença entre tracking demo e tracking rastreável
    • a política de cleartext apenas em builds de desenvolvimento
    • as decisões e riscos residuais do fluxo mobile/OAuth

🔗 Issue Relacionada

N/A

🧪 Testes

  • Testes unitários adicionados/atualizados
  • Testes de integração adicionados/atualizados
  • Todos os testes estão passando localmente
  • Cobertura de código mantida ou melhorada

Testes e validações executados:

  • dotnet test tests/OrderHub.Infrastructure.UnitTests/OrderHub.Infrastructure.UnitTests.csproj --no-restore -p:UseAppHost=false
  • dotnet test tests/OrderHub.Application.UnitTests/OrderHub.Application.UnitTests.csproj --no-restore -p:UseAppHost=false
  • dotnet test tests/OrderHub.Api.IntegrationTests/OrderHub.Api.IntegrationTests.csproj --no-restore -p:UseAppHost=false
  • flutter test test/auth_callback_page_test.dart test/deep_link_routes_test.dart test/api_client_test.dart test/spacing_tokens_test.dart
  • .\gradlew.bat :app:processDebugMainManifest :app:processProfileMainManifest :app:processReleaseMainManifest
  • dotnet list package --vulnerable --include-transitive

📋 Checklist

  • Código segue as convenções do projeto
  • Documentação atualizada (se necessário)
  • Sem warnings de compilação
  • Sem vulnerabilidades de segurança
  • Branch atualizada com main
  • Commit messages seguem convenção (feat/fix/docs/etc)

Observação:

  • o item de warnings ficou desmarcado porque o build Android ainda emite warnings de plugins/dependências terceiras durante o merge de manifests e tasks do Gradle, embora o build tenha passado com sucesso

📸 Screenshots (se aplicável)

Mudanças visuais relevantes já foram validadas nas telas responsivas/mobile compactas.
Se necessário, anexar no PR:

  • dashboard/home em viewport estreita
  • fluxo de callback mobile
  • perfil com vínculo de conta Google

🚀 Como Testar

  1. Validar backend e segurança:

    • rodar:
      • dotnet test tests/OrderHub.Infrastructure.UnitTests/OrderHub.Infrastructure.UnitTests.csproj --no-restore -p:UseAppHost=false
      • dotnet test tests/OrderHub.Application.UnitTests/OrderHub.Application.UnitTests.csproj --no-restore -p:UseAppHost=false
      • dotnet test tests/OrderHub.Api.IntegrationTests/OrderHub.Api.IntegrationTests.csproj --no-restore -p:UseAppHost=false
      • dotnet list package --vulnerable --include-transitive
    • confirmar que não há pacotes vulneráveis reportados
  2. Validar Android local vs release:

    • rodar:
      • cd orderhub_client/android
      • .\gradlew.bat :app:processDebugMainManifest :app:processProfileMainManifest :app:processReleaseMainManifest
    • confirmar que:
      • debug/profile incluem usesCleartextTraffic=true e networkSecurityConfig
      • release não inclui cleartext nem config de desenvolvimento
  3. Validar comportamento funcional:

    • subir API e app mobile/web localmente
    • testar login Google mobile com deep link + POST /auth/mobile/exchange
    • testar vínculo de conta Google adicional
    • chamar POST /orders/test/run-tracking-cycle e confirmar que o endpoint demo continua avançando pedidos seedados
    • confirmar que o worker usa apenas o caminho de pedidos realmente rastreáveis

🔄 Impacto

  • Breaking change (mudança que quebra compatibilidade)
  • Nova funcionalidade (non-breaking change que adiciona funcionalidade)
  • Bug fix (non-breaking change que corrige um problema)
  • Refatoração (mudança de código que não altera funcionalidade)
  • Documentação
  • Outro: hardening de segurança e readiness operacional

📚 Documentação Adicional

  • Docs/changelog-2026-04-16.md
  • Docs/mobile-oauth-notes-2026-04-16.md
  • Docs/production-audit-2026-04-16.md
  • Docs/security-deploy-checklist.md
  • Docs/production-readiness-checklist.md
  • Docs/ADR/0004-auth-oauth-security-hardening-and-compatible-rollout.md
  • Docs/ADR/0005-worker-hardening-and-operational-dashboard-home.md
  • Docs/ADR/0006-production-readiness-and-real-worker-cutover.md
  • Docs/ADR/0007-worker-production-identity-and-bootstrap-removal.md

Para os Revisores

Áreas de foco:

  • fluxo OAuth mobile e validação de callbacks nativos
  • hardening do Android release contra cleartext global
  • separação entre tracking demo e tracking rastreável
  • ajuste da migration de DisplayName
  • correção da dependência vulnerável e cobertura de testes

Dúvidas/Decisões:

  • o endpoint demo POST /orders/test/run-tracking-cycle continua avançando pedidos ativos seedados sem TrackingCode por decisão intencional de UX/demo; isso não representa o contrato usado pelo worker
  • cleartext HTTP permanece apenas em debug/profile para desenvolvimento local; release deve operar em HTTPS
  • a checklist de warnings ficou conservadora porque os warnings atuais vêm de plugins Android/Flutter terceiros, não de erro de build do projeto

Enables flexible enum storage by converting platform and status to strings with custom parsing for human-friendly and numeric values, improving data migration and compatibility.

Configures permissive CORS policy to support integration with a Flutter frontend client, facilitating cross-origin API access during development.

Updates ignore rules to exclude Flutter build artifacts from version control.
Integrates Google OAuth sign-in to the client and API, allowing users to authenticate with their Google accounts. Refactors email parsing and order import flow to support normalized message models, enabling more reliable extraction of order IDs, shipment IDs, and tracking codes. Prevents order status regression from out-of-order emails, and adds notification infrastructure to inform users of updates from both email imports and tracking cycles. Updates database schema to support external references and notifications, enhances UI with notification polling, and improves test coverage.

Relates to #41
Details new columns and indices added to support product changes,
including the introduction of persistent user notifications and schema
migrations to align the database with domain requirements.
- Implemented OrdersEmptyState widget for displaying empty order states.
- Created README.md for test instructions and structure.
- Added unit tests for API error mapping, dashboard functionality, login page, and user notifications.
- Developed TestApiClient for simulating API responses in tests.
- Introduced integration tests for Google authentication flow and user notification service.
- Implemented ProfileAvatarBadge widget for displaying user avatars with initials fallback.
- Created WelcomePage with responsive layout, action cards, and hero section.
- Added profile_page.dart and welcome_page.dart exports for easier access.
- Developed profile_page_test.dart to ensure profile updates and avatar uploads work correctly.
- Documented architectural decision regarding user profile persistence, local avatar storage, and Google multi-account support.
- Introduced GoogleConnectRequest and UpdateProfileRequest contracts for API interactions.
- Implemented LocalAvatarStorageService for handling avatar uploads and deletions.
- Created migration for adding user profile fields and supporting multiple Google accounts.
- Added unit tests for GoogleConnectionService to validate OAuth flow and account management.
…tion

- Create AuthRateLimitOptions and ReturnUrlSecurityOptions classes for configuration.
- Implement ReturnUrlValidator service to normalize and validate return URLs.
- Add a migration to remove the AvatarUrl column from the users table.
- Introduce StartupSecurityValidator to ensure secure API and worker configurations.
- Implement integration tests for Notifications and Orders controllers.
- Add unit tests for ReturnUrlValidator, EmailImportWorker, and UserNotificationRepository.
- Create MockTrackingService for testing order status advancement.
…ation

- Implemented app callback routes for handling Google Sign-In and profile connection callbacks.
- Created deep link handling for initial URI and stream of URIs.
- Added spacing tokens for consistent UI spacing across the app.
- Developed tests for API client, authentication callback, deep link routes, and flow lab page.
- Introduced a new batch script for running the Android app with network debugging.
- Added mobile authentication exchange request and service for handling auth codes.
- Established return URL security policy to validate allowed origins and native callbacks.
- Created integration tests for Google OAuth native callbacks and root endpoint responses.
@github-actions
Copy link
Copy Markdown

Summary

Summary
Generated on: 04/16/2026 - 12:31:20
Coverage date: 04/16/2026 - 12:31:07 - 04/16/2026 - 12:31:17
Parser: MultiReport (4x Cobertura)
Assemblies: 5
Classes: 86
Files: 91
Line coverage: 43.9% (1791 of 4072)
Covered lines: 1791
Uncovered lines: 2281
Coverable lines: 4072
Total lines: 6945
Branch coverage: 54.6% (587 of 1074)
Covered branches: 587
Total branches: 1074
Method coverage: Feature is only available for sponsors
Tag: 27_24510289285

Coverage

OrderHub.Api - 53.8%
Name Line Branch
OrderHub.Api 53.8% 56.7%
OrderHub.Api.Contracts.GoogleConnectRequest 0%
OrderHub.Api.Contracts.GoogleConnectResponse 0%
OrderHub.Api.Contracts.ImportOrdersResponse 0%
OrderHub.Api.Contracts.ImportTestOrdersRequest 0%
OrderHub.Api.Contracts.LoginRequest 100%
OrderHub.Api.Contracts.MobileAuthExchangeRequest 100%
OrderHub.Api.Contracts.RegisterRequest 100%
OrderHub.Api.Contracts.SeedTestOrdersResponse 100%
OrderHub.Api.Contracts.SimulateEmailBatchRequest 0%
OrderHub.Api.Contracts.SimulateEmailBatchResponse 0%
OrderHub.Api.Contracts.TrackOrdersResponse 100%
OrderHub.Api.Contracts.UpdateProfileRequest 100%
OrderHub.Api.Controllers.AuthController 74% 100%
OrderHub.Api.Controllers.GoogleIntegrationsController 23.9% 26.1%
OrderHub.Api.Controllers.NotificationsController 100%
OrderHub.Api.Controllers.OrdersController 28.3% 0%
OrderHub.Api.Options.AuthRateLimitOptions 100%
OrderHub.Api.Options.ReturnUrlSecurityOptions 100%
OrderHub.Api.Services.CurrentUserProvider 77.7% 50%
OrderHub.Api.Services.MobileAuthCompletionCodeService 93.7% 75%
OrderHub.Api.Services.ReturnUrlSecurityPolicy 83% 73.2%
OrderHub.Api.Services.ReturnUrlValidator 96.6% 95.4%
OrderHub.Api.Swagger.JwtSecurityOperationFilter 0% 0%
Program 81.6% 75%
OrderHub.Application - 74%
Name Line Branch
OrderHub.Application 74% 68.8%
OrderHub.Application.Extensions.OrderExtensions 85% 78.5%
OrderHub.Application.Models.AuthResult 100%
OrderHub.Application.Models.AuthToken 100%
OrderHub.Application.Models.ConnectedAccountDto 50%
OrderHub.Application.Models.GoogleOAuthExchangeResult 100%
OrderHub.Application.Models.GoogleOAuthState 71.4% 50%
OrderHub.Application.Models.GoogleSignInCompletionResult 100%
OrderHub.Application.Models.NormalizedEmailMessage 93.2% 85%
OrderHub.Application.Models.OrderDto 100%
OrderHub.Application.Models.ParsedOrderEmail 100%
OrderHub.Application.Models.UserNotificationDto 100%
OrderHub.Application.Models.UserProfileDto 100%
OrderHub.Application.Parsers.AmazonOrderParser 0% 0%
OrderHub.Application.Parsers.MercadoLivreOrderParser 95.9% 71.4%
OrderHub.Application.Parsers.RegexOrderParserBase 100% 83.3%
OrderHub.Application.Services.AuthService 100% 100%
OrderHub.Application.Services.DemoOrderScenarioService 20.6% 12.5%
OrderHub.Application.Services.EmailOrderImporter 92.8% 70%
OrderHub.Application.Services.GoogleAuthenticationService 100% 95.4%
OrderHub.Application.Services.GoogleConnectionService 66.3% 42.8%
OrderHub.Application.Services.OrderService 44.4% 0%
OrderHub.Application.Services.OrderStatusUpdater 100% 100%
OrderHub.Application.Services.UserNotificationService 100% 100%
OrderHub.Domain - 90%
Name Line Branch
OrderHub.Domain 90% 78.4%
OrderHub.Domain.Entities.ConnectedAccount 80.2% 50%
OrderHub.Domain.Entities.Order 97.1% 82.5%
OrderHub.Domain.Entities.User 84.8% 54.5%
OrderHub.Domain.Entities.UserNotification 100% 100%
OrderHub.Infrastructure - 24.3%
Name Line Branch
OrderHub.Infrastructure 24.3% 35.3%
OrderHub.Infrastructure.DependencyInjection 91.3% 50%
OrderHub.Infrastructure.Migrations.AddOrderExternalReferences 0%
OrderHub.Infrastructure.Migrations.AddUserNotifications 0%
OrderHub.Infrastructure.Migrations.AddUserProfileAndGoogleMultiAccountSuppo
rt
0%
OrderHub.Infrastructure.Migrations.AddUsersAndConnectedAccounts 0%
OrderHub.Infrastructure.Migrations.InitialCreate 0%
OrderHub.Infrastructure.Migrations.OrderHubDbContextModelSnapshot 0%
OrderHub.Infrastructure.Migrations.RemoveUserAvatar 0%
OrderHub.Infrastructure.Options.GmailOptions 0%
OrderHub.Infrastructure.Options.GoogleOAuthOptions 100%
OrderHub.Infrastructure.Options.JwtOptions 100%
OrderHub.Infrastructure.Persistence.Configurations.ConnectedAccountConfigur
ation
100%
OrderHub.Infrastructure.Persistence.Configurations.OrderConfiguration 67.1% 21%
OrderHub.Infrastructure.Persistence.Configurations.UserConfiguration 100%
OrderHub.Infrastructure.Persistence.Configurations.UserNotificationConfigur
ation
100%
OrderHub.Infrastructure.Persistence.OrderHubDbContext 100%
OrderHub.Infrastructure.Persistence.OrderHubDbContextFactory 0% 0%
OrderHub.Infrastructure.Repositories.ConnectedAccountRepository 64.8%
OrderHub.Infrastructure.Repositories.OrderRepository 73.5% 100%
OrderHub.Infrastructure.Repositories.UnitOfWork 97.3% 90%
OrderHub.Infrastructure.Repositories.UserNotificationRepository 100% 100%
OrderHub.Infrastructure.Repositories.UserRepository 100%
OrderHub.Infrastructure.Services.ConnectedAccountGmailEmailReader 5.8% 0%
OrderHub.Infrastructure.Services.DataProtectionSecretProtector 75%
OrderHub.Infrastructure.Services.GmailApiEmailReader 0% 0%
OrderHub.Infrastructure.Services.GmailMessageContentExtractor 78.5% 57.2%
OrderHub.Infrastructure.Services.GoogleOAuthClient 30% 12.5%
OrderHub.Infrastructure.Services.JwtTokenGenerator 95.6% 50%
OrderHub.Infrastructure.Services.MockTrackingService 70% 50%
OrderHub.Infrastructure.Services.OAuthStateProtector 89.4% 70%
OrderHub.Infrastructure.Services.Pbkdf2PasswordHasher 70.5% 50%
OrderHub.Infrastructure.Startup.StartupSecurityValidator 72.7% 63.6%
OrderHub.Worker - 71.1%
Name Line Branch
OrderHub.Worker 71.1% 63.6%
OrderHub.Worker.Configuration.EmailImportWorkerOptions 100%
OrderHub.Worker.EmailImportWorker 86.2% 70%
Program 0% 0%

@BLACKBARGS BLACKBARGS self-assigned this Apr 16, 2026
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Este PR faz um hardening full stack (API/Worker/Flutter) focado em OAuth mobile-first, validação de returnUrl, remoção de cleartext em Android release, separação explícita de tracking demo vs tracking “rastreável” e adição de notificações + perfil persistido.

Changes:

  • Backend: endurece OAuth/returnUrl (origem completa + callbacks nativos), adiciona rate limiting em auth e implementa code exchange mobile.
  • Worker/Infra: reforça validações de startup em ambientes não-dev, ajusta tracking demo e adiciona suporte a notificações persistidas.
  • Frontend: amplia cobertura de testes e estrutura de deep links; Android passa a permitir cleartext apenas em debug/profile (com configs dedicadas).

Reviewed changes

Copilot reviewed 206 out of 257 changed files in this pull request and generated 8 comments.

Show a summary per file
File Description
tests/OrderHub.Application.UnitTests/Services/AuthServiceTests.cs Ajusta mocks do UoW e adiciona asserts/testes para DisplayName e update de perfil.
tests/OrderHub.Application.UnitTests/Parsers/MercadoLivreOrderParserTests.cs Adiciona testes do parser Mercado Livre com email real + formato mock.
tests/OrderHub.Application.UnitTests/OrderHub.Application.UnitTests.csproj Inclui referência ao projeto Worker para suportar novos testes/dependências.
tests/OrderHub.Api.IntegrationTests/Services/ReturnUrlSecurityPolicyTests.cs Adiciona testes de allowlist de origem/porta e callbacks nativos.
tests/OrderHub.Api.IntegrationTests/OrderHubWebApplicationFactoryExtensions.cs Helpers para configurar allowlists e fake do Google OAuth em testes.
tests/OrderHub.Api.IntegrationTests/OrderHubWebApplicationFactory.cs Hardening do setup de DbContext em integração removendo registros do provider de produção.
tests/OrderHub.Api.IntegrationTests/FakeGoogleOAuthClient.cs Implementa fake do client Google OAuth para integração.
tests/OrderHub.Api.IntegrationTests/Controllers/RootEndpointTests.cs Smoke test do endpoint raiz fora de Development.
tests/OrderHub.Api.IntegrationTests/Controllers/OrdersControllerTests.cs Testa seed demo e ciclo demo de tracking sem TrackingCode.
tests/OrderHub.Api.IntegrationTests/Controllers/NotificationsControllerTests.cs Testa paginação/limite e ordenação de notificações.
tests/OrderHub.Api.IntegrationTests/Controllers/GoogleOAuthNativeCallbackTests.cs Testa callback nativo + exchange mobile e fluxo de connect no mobile.
tests/OrderHub.Api.IntegrationTests/Controllers/AuthGoogleStartTests.cs Testa validação de returnUrl e redirects do start do Google.
src/OrderHub.Worker/appsettings.json Remove defaults inseguros (connection string, mock emails) e zera valores.
src/OrderHub.Worker/appsettings.Development.json Ajusta seed de emails mock (ex.: remove rastreio do exemplo Amazon).
src/OrderHub.Worker/Program.cs Valida segurança no startup e registra UserNotificationService.
src/OrderHub.Worker/Configuration/EmailImportWorkerOptions.cs Remove defaults “Mock”/GUID fixo e usa Guid.Empty/string vazia.
src/OrderHub.Infrastructure/Startup/StartupSecurityValidator.cs Novo validador central de segurança de startup (API e Worker).
src/OrderHub.Infrastructure/Services/OAuthStateProtector.cs Troca state simples (Guid) por state estruturado (JSON protegido).
src/OrderHub.Infrastructure/Services/MockTrackingService.cs Separa tracking demo: avança status mesmo sem TrackingCode.
src/OrderHub.Infrastructure/Services/GmailApiEmailReader.cs Retorna NormalizedEmailMessage e usa extractor dedicado.
src/OrderHub.Infrastructure/Repositories/UserNotificationRepository.cs Implementa repositório de notificações com limite seguro e ordenação.
src/OrderHub.Infrastructure/Repositories/UnitOfWork.cs Inclui Notifications no UoW.
src/OrderHub.Infrastructure/Repositories/OrderRepository.cs Separa “ativos” vs “rastreáveis” e adiciona buscas por IDs externos.
src/OrderHub.Infrastructure/Repositories/ConnectedAccountRepository.cs Suporta multi-contas: busca por provider+externalUserId e lista por provider.
src/OrderHub.Infrastructure/Persistence/OrderHubDbContext.cs Adiciona DbSet<UserNotification>.
src/OrderHub.Infrastructure/Persistence/Configurations/UserNotificationConfiguration.cs Mapeia tabela user_notifications + índices + FKs.
src/OrderHub.Infrastructure/Persistence/Configurations/UserConfiguration.cs Torna DisplayName obrigatório e com max length.
src/OrderHub.Infrastructure/Persistence/Configurations/OrderConfiguration.cs Conversions robustas para enums + adiciona IDs externos e índices.
src/OrderHub.Infrastructure/Persistence/Configurations/ConnectedAccountConfiguration.cs Índice único por (Provider, ExternalUserId) para ownership cross-user.
src/OrderHub.Infrastructure/OrderHub.Infrastructure.csproj Adiciona referência a System.Security.Cryptography.Xml.
src/OrderHub.Infrastructure/Migrations/OrderHubDbContextModelSnapshot.cs Atualiza snapshot com notificações, displayName e IDs externos.
src/OrderHub.Infrastructure/Migrations/20260415024009_RemoveUserAvatar.cs Migration remove AvatarUrl da tabela users.
src/OrderHub.Infrastructure/Migrations/20260414051505_AddUserProfileAndGoogleMultiAccountSupport.cs Migration adiciona DisplayName e índices de multi-account Google.
src/OrderHub.Infrastructure/Migrations/20260413233216_AddUserNotifications.cs Migration cria tabela user_notifications.
src/OrderHub.Infrastructure/Migrations/20260413230200_AddOrderExternalReferences.cs Migration adiciona ExternalOrderId/ExternalShipmentId e índices.
src/OrderHub.Infrastructure/DependencyInjection.cs Exige connection string configurada e registra repo de notificações.
src/OrderHub.Infrastructure/AssemblyInfo.cs Exponibiliza internals para testes de infraestrutura.
src/OrderHub.Domain/Repositories/IUserNotificationRepository.cs Novo contrato de repo para notificações.
src/OrderHub.Domain/Repositories/IUnitOfWork.cs Inclui Notifications no UoW.
src/OrderHub.Domain/Repositories/IOrderRepository.cs Expande contrato: ativos/rastreáveis + buscas por IDs externos.
src/OrderHub.Domain/Repositories/IConnectedAccountRepository.cs Ajusta contrato para multi-contas e novas queries.
src/OrderHub.Domain/Entities/UserNotification.cs Nova entidade de notificações com validação de campos.
src/OrderHub.Domain/Entities/User.cs Adiciona DisplayName, default name e UpdateProfile.
src/OrderHub.Domain/Entities/Order.cs Adiciona IDs externos, ApplyImport e regras anti-regressão de status.
src/OrderHub.Application/Services/UserNotificationService.cs Serviço para listar e enfileirar notificações.
src/OrderHub.Application/Services/OrderStatusUpdater.cs Separa update “rastreável” vs “demo” e gera notificações por status change.
src/OrderHub.Application/Services/GoogleConnectionService.cs Suporta multi-contas Google e valida ownership por externalUserId.
src/OrderHub.Application/Services/AuthService.cs Suporta DisplayName no profile e adiciona update de perfil.
src/OrderHub.Application/Parsers/RegexOrderParserBase.cs Helpers de extração + suporte a NormalizedEmailMessage.
src/OrderHub.Application/Parsers/MercadoLivreOrderParser.cs Parser mais robusto: sinais por sender/link + IDs externos + status heurístico.
src/OrderHub.Application/Parsers/AmazonOrderParser.cs Parser refeito para mensagens normalizadas, IDs externos e origem padronizada.
src/OrderHub.Application/Models/UserProfileDto.cs Inclui DisplayName no DTO de perfil.
src/OrderHub.Application/Models/UserNotificationDto.cs Novo DTO de notificações.
src/OrderHub.Application/Models/ParsedOrderEmail.cs Novo modelo intermediário para parse de emails.
src/OrderHub.Application/Models/NormalizedEmailMessage.cs Modelo normalizado com headers/links/searchable content.
src/OrderHub.Application/Models/GoogleSignInCompletionResult.cs Resultado estruturado para conclusão de sign-in.
src/OrderHub.Application/Models/GoogleOAuthState.cs State tipado para flows connect/sign-in e validações.
src/OrderHub.Application/Abstractions/IOrderParser.cs Contrato do parser passa a usar message normalizada + Origin + retorno estruturado.
src/OrderHub.Application/Abstractions/IOAuthStateProtector.cs Atualiza contrato para state tipado.
src/OrderHub.Application/Abstractions/IGmailEmailReader.cs Atualiza contrato para retornar mensagens normalizadas.
src/OrderHub.Application/Abstractions/IConnectedGmailEmailReader.cs Atualiza contrato para retornar mensagens normalizadas por usuário.
src/OrderHub.Api/appsettings.json Adiciona seção Security (ReturnUrl + AuthRateLimit).
src/OrderHub.Api/appsettings.Development.json Configura callbacks nativos permitidos em dev.
src/OrderHub.Api/Services/ReturnUrlValidator.cs Normalização/validação centralizada de returnUrl (web + native).
src/OrderHub.Api/Services/MobileAuthCompletionCodeService.cs Emite/consome códigos temporários para exchange mobile.
src/OrderHub.Api/Properties/launchSettings.json Ajusta launch (Swagger + bind 0.0.0.0) para debug em rede.
src/OrderHub.Api/Program.cs Rate limiter, CORS por policy, root endpoint non-dev e hardening de startup.
src/OrderHub.Api/Options/ReturnUrlSecurityOptions.cs Options para allowlist de origens/callbacks nativos/loopback/legacy hosts.
src/OrderHub.Api/Options/AuthRateLimitOptions.cs Options do rate limiting de auth.
src/OrderHub.Api/Controllers/OrdersController.cs Adiciona endpoints demo (seed/simulate/run tracking) e ajusta import Gmail.
src/OrderHub.Api/Controllers/NotificationsController.cs Novo endpoint autenticado de listagem de notificações.
src/OrderHub.Api/Controllers/AuthController.cs Add exchange mobile, start Google com returnUrl validation e update profile.
src/OrderHub.Api/Contracts/UpdateProfileRequest.cs Contrato do update de perfil.
src/OrderHub.Api/Contracts/TrackOrdersResponse.cs Resposta do ciclo demo de tracking.
src/OrderHub.Api/Contracts/SimulateEmailBatchResponse.cs Resposta da simulação de batch de emails.
src/OrderHub.Api/Contracts/SimulateEmailBatchRequest.cs Request da simulação de batch.
src/OrderHub.Api/Contracts/SeedTestOrdersResponse.cs Resposta do seed demo.
src/OrderHub.Api/Contracts/MobileAuthExchangeRequest.cs Request do exchange mobile (código).
src/OrderHub.Api/Contracts/GoogleConnectRequest.cs Request para conectar Google com ReturnUrl opcional.
run-android-network-debug.bat Helper para rodar app em device na rede com API em host IP.
orderhub_client/web/manifest.json Manifest web do Flutter.
orderhub_client/web/index.html Index web do Flutter.
orderhub_client/test/widget_test.dart Teste shell do login (widget).
orderhub_client/test/welcome_page_test.dart Teste de layout responsivo welcome page.
orderhub_client/test/spacing_tokens_test.dart “Lint test” garantindo tokens de espaçamento em páginas alvo.
orderhub_client/test/notification_history_sheet_test.dart Teste de layout do bottom sheet de notificações.
orderhub_client/test/notification_center_test.dart Testes do centro de notificações (dedupe e batches stale).
orderhub_client/test/login_page_test.dart Testes de login/registro/erros amigáveis + responsividade.
orderhub_client/test/frontend_helpers_test.dart Testes de helpers de callback, rotas iniciais e parsers de URI.
orderhub_client/test/flow_lab_page_test.dart Teste de layout da FlowLabPage.
orderhub_client/test/deep_link_routes_test.dart Testes de resolução de deep links para rotas internas.
orderhub_client/test/auth_callback_page_test.dart Testes do callback (exchange mobile + redirect profile google).
orderhub_client/test/api_error_mapper_test.dart Testes do mapper de erros de API para mensagens amigáveis.
orderhub_client/test/api_client_test.dart Testa construção do start Google com callback deep link no mobile.
orderhub_client/test/README.md Documenta como rodar suites e grupos de testes do front.
orderhub_client/pubspec.yaml Define deps do Flutter (dio, router, riverpod, notifications, links).
orderhub_client/lib/welcome_page.dart Re-export para rota pública do welcome.
orderhub_client/lib/profile_page.dart Re-export para rota pública do profile.
orderhub_client/lib/login_page.dart Re-export para rota pública do login.
orderhub_client/lib/features/profile/presentation/pages/google_connect_callback_page.dart Tela de callback do connect Google no app e parser de URI.
orderhub_client/lib/features/profile/domain/connected_google_account.dart Modelo de conta Google conectada + parsing JSON.
orderhub_client/lib/features/orders/presentation/widgets/orders_empty_state.dart Widget de empty state para pedidos.
orderhub_client/lib/features/orders/domain/user_profile.dart Modelo de profile (com display name) para o app.
orderhub_client/lib/features/orders/domain/order_summary.dart Modelo de resumo de pedido para UI.
orderhub_client/lib/features/orders/domain/order_status_bucket.dart Buckets de status para home/categorias.
orderhub_client/lib/features/notifications/presentation/widgets/notification_history_sheet.dart Bottom sheet de histórico de notificações.
orderhub_client/lib/features/notifications/domain/app_notification_item.dart Modelo de notificação (parsing JSON + fallback id).
orderhub_client/lib/deep_link_stub.dart Stub de deep links (não-IO).
orderhub_client/lib/deep_link_io.dart Implementação IO via app_links.
orderhub_client/lib/dashboard_page.dart Re-export para rota pública do dashboard.
orderhub_client/lib/core/theme/app_theme.dart Tema dark (Material 3) consolidado.
orderhub_client/lib/core/theme/app_spacing.dart Tokens de spacing.
orderhub_client/lib/core/navigation/app_callback_routes.dart Consts + helpers para deep links e callbacks.
orderhub_client/lib/core/feedback/app_feedback.dart Snackbars padronizados para feedback.
orderhub_client/lib/core/errors/app_exception.dart Exceção com mensagem para usuário + fallback genérico.
orderhub_client/lib/browser_redirect_web.dart Redirect web via window.location.assign.
orderhub_client/lib/browser_redirect_stub.dart Stub para plataformas sem redirect.
orderhub_client/lib/browser_redirect_io.dart Redirect IO via url_launcher.
orderhub_client/lib/auth_callback_page.dart Re-export do callback auth.
orderhub_client/lib/app_notification_service.dart Serviço de notificações locais (Android/iOS) com canal.
orderhub_client/ios/RunnerTests/RunnerTests.swift Boilerplate de testes iOS.
orderhub_client/ios/Runner/SceneDelegate.swift SceneDelegate para múltiplas scenes (Flutter embedding).
orderhub_client/ios/Runner/Runner-Bridging-Header.h Header bridging para plugins iOS.
orderhub_client/ios/Runner/Info.plist Config iOS incluindo URL scheme orderhub.
orderhub_client/ios/Runner/Base.lproj/Main.storyboard Storyboard principal iOS.
orderhub_client/ios/Runner/Base.lproj/LaunchScreen.storyboard Launch screen iOS.
orderhub_client/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md Doc de assets do launch screen iOS.
orderhub_client/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json Conteúdo do asset do launch screen iOS.
orderhub_client/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json Conteúdo do app icon iOS.
orderhub_client/ios/Runner/AppDelegate.swift AppDelegate adaptado para registro do engine implícito.
orderhub_client/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings Settings do workspace iOS.
orderhub_client/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist Checks do workspace iOS.
orderhub_client/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme Scheme do Xcode.
orderhub_client/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings Settings do project workspace iOS.
orderhub_client/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist Checks do project workspace iOS.
orderhub_client/ios/Flutter/Release.xcconfig Config Release para iOS.
orderhub_client/ios/Flutter/Debug.xcconfig Config Debug para iOS.
orderhub_client/ios/Flutter/AppFrameworkInfo.plist Info.plist do framework Flutter iOS.
orderhub_client/ios/.gitignore Ignora artefatos iOS/Pods/DerivedData.
orderhub_client/integration_test/app_flow_test.dart Teste de integração do fluxo (login -> dashboard -> ações demo).
orderhub_client/devtools_options.yaml Config do DevTools.
orderhub_client/android/settings.gradle.kts PluginManagement + versões AGP/Kotlin + loader Flutter.
orderhub_client/android/gradlew.bat Gradle wrapper (Windows).
orderhub_client/android/gradle/wrapper/gradle-wrapper.properties Fixa Gradle 8.14.
orderhub_client/android/gradle.properties Flags Gradle e AndroidX.
orderhub_client/android/build.gradle.kts Config buildDir e clean.
orderhub_client/android/app/src/profile/res/xml/network_security_config.xml Permite cleartext em profile.
orderhub_client/android/app/src/profile/AndroidManifest.xml Permite cleartext e networkSecurityConfig em profile.
orderhub_client/android/app/src/main/res/values/styles.xml Styles base Android.
orderhub_client/android/app/src/main/res/values-night/styles.xml Styles night Android.
orderhub_client/android/app/src/main/res/drawable/launch_background.xml Splash background Android.
orderhub_client/android/app/src/main/res/drawable-v21/launch_background.xml Splash background Android v21.
orderhub_client/android/app/src/main/kotlin/com/example/orderhub_client/MainActivity.kt MainActivity do app.
orderhub_client/android/app/src/main/AndroidManifest.xml Manifest main com intent-filters para deep links.
orderhub_client/android/app/src/debug/res/xml/network_security_config.xml Permite cleartext em debug.
orderhub_client/android/app/src/debug/AndroidManifest.xml Permite cleartext e networkSecurityConfig em debug.
orderhub_client/android/app/build.gradle.kts Config Android app + desugaring + Flutter plugin.
orderhub_client/android/.gitignore Ignora artefatos Android/keystore/local.properties.
orderhub_client/analysis_options.yaml Lints do Flutter/Dart.
orderhub_client/.metadata Metadata do Flutter tool (snapshot de revision).
orderhub_client/.gitignore Ignora artefatos do Flutter/Android/iOS.
Docs/mobile-oauth-notes-2026-04-16.md Documento consolidando desenho OAuth mobile-first + próximos passos.
Docs/changelog-2026-04-16.md Changelog do snapshot com mudanças de hardening.
Docs/ADR/0007-worker-production-identity-and-bootstrap-removal.md ADR sobre identidade do worker em produção (direção futura).
Docs/ADR/0006-production-readiness-and-real-worker-cutover.md ADR de readiness para cutover do worker real.
Docs/ADR/0005-worker-hardening-and-operational-dashboard-home.md ADR do hardening do worker + home operacional.
Docs/ADR/0004-auth-oauth-security-hardening-and-compatible-rollout.md ADR do hardening de auth/OAuth e rollout compatível.
Docs/ADR/0003-profile-avatar-and-google-multi-account.md ADR de profile sem avatar + multi-contas Google.
Directory.Packages.props Fixa versão do System.Security.Cryptography.Xml.
Files not reviewed (6)
  • orderhub_client/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata: Language not supported
  • orderhub_client/ios/Runner.xcworkspace/contents.xcworkspacedata: Language not supported
  • src/OrderHub.Infrastructure/Migrations/20260413230200_AddOrderExternalReferences.Designer.cs: Language not supported
  • src/OrderHub.Infrastructure/Migrations/20260413233216_AddUserNotifications.Designer.cs: Language not supported
  • src/OrderHub.Infrastructure/Migrations/20260414051505_AddUserProfileAndGoogleMultiAccountSupport.Designer.cs: Language not supported
  • src/OrderHub.Infrastructure/Migrations/20260415024009_RemoveUserAvatar.Designer.cs: Language not supported

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +117 to +133
private static string BuildDefaultDisplayName(string email)
{
var localPart = email.Split('@', 2, StringSplitOptions.TrimEntries)[0];

if (string.IsNullOrWhiteSpace(localPart))
{
return "OrderHub User";
}

var normalized = localPart.Replace('.', ' ').Replace('_', ' ').Trim();
return string.IsNullOrWhiteSpace(normalized)
? "OrderHub User"
: string.Join(
' ',
normalized.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Select(static part => char.ToUpperInvariant(part[0]) + part[1..]));
}
Comment on lines +93 to +97
[AllowAnonymous]
[HttpGet("google/start")]
[ProducesResponseType(StatusCodes.Status302Found)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
public ActionResult StartGoogleSignIn([FromQuery] string? returnUrl)
Comment on lines +39 to +48
.IsRequired();

builder.Property(order => order.ExternalShipmentId)
.HasMaxLength(128)
.IsRequired();

builder.HasIndex(order => order.UserId);
builder.HasIndex(order => order.TrackingCode);
builder.HasIndex(order => new { order.UserId, order.ExternalOrderId });
builder.HasIndex(order => new { order.UserId, order.ExternalShipmentId });
Comment on lines +47 to +48
builder.HasIndex(order => new { order.UserId, order.ExternalOrderId });
builder.HasIndex(order => new { order.UserId, order.ExternalShipmentId });
Comment on lines +7 to 10
"launchBrowser": true,
"launchUrl": "swagger",
"commandLineArgs": "--urls http://0.0.0.0:5280",
"applicationUrl": "http://localhost:5280",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "https://localhost:7155;http://localhost:5280",
"applicationUrl": "https://localhost:7155;http://0.0.0.0:5280",
Comment on lines +10 to +11
public string BuildAuthorizationUrl(string state) => authorizationUrl;

Comment on lines +7 to +18
public sealed class MobileAuthCompletionCodeService(IMemoryCache cache)
{
private static readonly TimeSpan CodeLifetime = TimeSpan.FromMinutes(2);

public string IssueCode(AuthResult authResult)
{
ArgumentNullException.ThrowIfNull(authResult);

var code = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
cache.Set(GetCacheKey(code), authResult, CodeLifetime);
return code;
}
@BLACKBARGS BLACKBARGS closed this Apr 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants