fix: Harden mobile OAuth, Android cleartext config, and tracking contracts#21
Closed
BLACKBARGS wants to merge 10 commits intomainfrom
Closed
fix: Harden mobile OAuth, Android cleartext config, and tracking contracts#21BLACKBARGS wants to merge 10 commits intomainfrom
BLACKBARGS wants to merge 10 commits intomainfrom
Conversation
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.
SummarySummary
CoverageOrderHub.Api - 53.8%
OrderHub.Application - 74%
OrderHub.Domain - 90%
OrderHub.Infrastructure - 24.3%
OrderHub.Worker - 71.1%
|
There was a problem hiding this comment.
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; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
🎯 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:
Google -> API callback HTTPS -> deep link -> /auth/mobile/exchangereturnUrle callbacks nativos com allowlist dedicadaGetTrackableOrdersAsyncvolta a representar apenas pedidos realmente rastreáveis, comTrackingCodeDisplayNamecom string vazia, usando um valor válido por padrãoOAuthStateProtectore adiciona cobertura unitáriaSystem.Security.Cryptography.XmlNo frontend/mobile:
android:usesCleartextTrafficenetworkSecurityConfigaos source setsdebug/profile10.0.2.2e IP da máquina)Na documentação:
🔗 Issue Relacionada
N/A
🧪 Testes
Testes e validações executados:
dotnet test tests/OrderHub.Infrastructure.UnitTests/OrderHub.Infrastructure.UnitTests.csproj --no-restore -p:UseAppHost=falsedotnet test tests/OrderHub.Application.UnitTests/OrderHub.Application.UnitTests.csproj --no-restore -p:UseAppHost=falsedotnet test tests/OrderHub.Api.IntegrationTests/OrderHub.Api.IntegrationTests.csproj --no-restore -p:UseAppHost=falseflutter 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:processReleaseMainManifestdotnet list package --vulnerable --include-transitive📋 Checklist
mainObservação:
📸 Screenshots (se aplicável)
Mudanças visuais relevantes já foram validadas nas telas responsivas/mobile compactas.
Se necessário, anexar no PR:
🚀 Como Testar
Validar backend e segurança:
dotnet test tests/OrderHub.Infrastructure.UnitTests/OrderHub.Infrastructure.UnitTests.csproj --no-restore -p:UseAppHost=falsedotnet test tests/OrderHub.Application.UnitTests/OrderHub.Application.UnitTests.csproj --no-restore -p:UseAppHost=falsedotnet test tests/OrderHub.Api.IntegrationTests/OrderHub.Api.IntegrationTests.csproj --no-restore -p:UseAppHost=falsedotnet list package --vulnerable --include-transitiveValidar Android local vs release:
cd orderhub_client/android.\gradlew.bat :app:processDebugMainManifest :app:processProfileMainManifest :app:processReleaseMainManifestdebug/profileincluemusesCleartextTraffic=trueenetworkSecurityConfigreleasenão inclui cleartext nem config de desenvolvimentoValidar comportamento funcional:
POST /auth/mobile/exchangePOST /orders/test/run-tracking-cyclee confirmar que o endpoint demo continua avançando pedidos seedados🔄 Impacto
📚 Documentação Adicional
Docs/changelog-2026-04-16.mdDocs/mobile-oauth-notes-2026-04-16.mdDocs/production-audit-2026-04-16.mdDocs/security-deploy-checklist.mdDocs/production-readiness-checklist.mdDocs/ADR/0004-auth-oauth-security-hardening-and-compatible-rollout.mdDocs/ADR/0005-worker-hardening-and-operational-dashboard-home.mdDocs/ADR/0006-production-readiness-and-real-worker-cutover.mdDocs/ADR/0007-worker-production-identity-and-bootstrap-removal.mdPara os Revisores
Áreas de foco:
DisplayNameDúvidas/Decisões:
POST /orders/test/run-tracking-cyclecontinua avançando pedidos ativos seedados semTrackingCodepor decisão intencional de UX/demo; isso não representa o contrato usado pelo workerdebug/profilepara desenvolvimento local; release deve operar em HTTPS