Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

appcheck #1375

Merged
merged 41 commits into from
Dec 20, 2024
Merged

appcheck #1375

merged 41 commits into from
Dec 20, 2024

Conversation

technoplato
Copy link
Collaborator

@technoplato technoplato commented Dec 18, 2024

replaces #1369

some android physical device qol improvements: https://www.loom.com/share/867a810a8df34a29bb45845d50e01a37

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced conditional logic in the Podfile to enhance build settings for specific targets.
    • Added new dependencies for Firebase integration and build properties management.
    • Implemented a polling mechanism for join group requests to improve user experience.
    • Added a new property for appCheckDebugToken in environment configurations.
    • Introduced utility functions for API URI management and Firebase App Check integration.
    • Added a script to facilitate APK transfer to connected Android devices.
  • Bug Fixes

    • Removed the synchronization group for Google Services, streamlining project configuration.
  • Chores

    • Restructured project groups for better organization related to Google Services.
    • Updated cocoapods version in build configurations.
    • Updated EXPO_ENV entries in development and preview configurations.
    • Enhanced error handling and security in API interactions by requiring appCheckToken.
    • Improved clarity in spam score computation logic.
    • Specified minimum required version of the Bundler gem for compatibility.
    • Updated logging functionality to simplify environment checks.

@technoplato technoplato requested a review from a team as a code owner December 18, 2024 20:58
Copy link
Contributor

coderabbitai bot commented Dec 18, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request introduces changes to the iOS project configuration, specifically in the project.pbxproj, Podfile, and eas.json files. Notably, the Google Services synchronization group is removed, and a new empty group is created. The Podfile adds a conditional block in the post_install section to set the DEFINES_MODULE build setting for specific targets. Additionally, the eas.json file updates the cocoapods version and modifies the EXPO_ENV entry in certain configurations. Other files, including utility and configuration files, also see updates to improve error handling and environment management.

Changes

File Change Summary
ios/Converse.xcodeproj/project.pbxproj - Removed PBXFileSystemSynchronizedRootGroup for Google Services
- Added empty PBXGroup for Google Services
- Removed fileSystemSynchronizedGroups attribute from Converse and ConverseNotificationExtension targets
ios/Podfile - Added conditional block in post_install to set DEFINES_MODULE to 'YES' for specific targets
- Introduced variable $RNFirebaseAsStaticFramework set to true in Converse target
eas.json - Updated cocoapods version from 1.14.3 to 1.16.2 in both development and production
- Updated env key with EXPO_ENV from "dev" to "preview" in development and preview configurations
queries/QueryKeys.ts - Updated multiple functions to use optional chaining for account parameter to prevent errors
screens/Navigation/Navigation.tsx - Removed import for ConversationTopic from @xmtp/react-native-sdk
utils/api.ts - Added FIREBASE_APP_CHECK_HEADER_KEY and updated appCheckToken to be a required parameter in AuthParams
app.config.ts - Removed import for PluginConfigTypeAndroid
- Introduced variable name for app name based on environment
- Added adaptiveIcon property in android configuration
- Added plugin @react-native-firebase/app-check
package.json - Added dependencies: @react-native-firebase/app, @react-native-firebase/app-check, and confirmed expo-build-properties
ios/Gemfile - Added minimum required version for Bundler gem
utils/apiConfig.ts - Introduced getApiUri function to determine API URI based on environment
utils/appCheck.ts - Added functions for integrating Firebase App Check: tryGetAppCheckToken and setupAppAttest
utils/getEnv.ts - Introduced environment management utilities: getEnv, Environments, isDev, isPreview, isProd
utils/logger.ts - Updated logging checks to use isDev instead of config
utils/capture-error.ts - Updated error logging condition to use isDev instead of config.env
utils/sentry.ts - Updated Sentry initialization condition to use isDev
utils/xmtpRN/messages.ts - Updated message handling logic to use isProd instead of config.env
scripts/android/sendApk.sh - Added new script to send APK to connected Android device
.gitignore - Added entry to ignore build-*.apk files

Possibly related PRs

  • fix: EAS Build Fixes #1099: The changes in the main PR regarding the removal and restructuring of the Google Services group in the project.pbxproj file may relate to the build process enhancements in this PR, which also involves project configuration adjustments.
  • feat: remove split screen stuff #1105: The removal of split-screen functionality in this PR could be indirectly related to the changes in project structure and organization in the main PR, as both involve adjustments to how components are managed.
  • fix: Group Admin Table  #1250: The updates to group management and permissions in this PR may connect with the changes in the main PR that involve restructuring project files and configurations, particularly if they affect how group services are integrated.
  • feat: React Native 75  #1268: The updates for React Native version 75 in this PR may relate to the main PR's changes in project configurations, as both involve ensuring compatibility with updated dependencies.
  • feat: Translations #1322: The enhancements to translation capabilities in this PR could be related to the changes in the main PR that involve project structure and localization, particularly if they affect how translations are managed across the application.
  • Feat: JWT Authentication #1340: The addition of JWT authentication in this PR may connect with the changes in the main PR regarding project configurations, especially if they impact how authentication services are integrated.
  • feat: DM Push Notifications and Native iOS Profile Updates  #1348: The modifications to loading logic in this PR may relate to the changes in the main PR that involve project structure and navigation, as both aim to improve user experience during loading states.
  • Ml/fix deeplink to groupchat #1395: The updates to deep linking functionality in this PR may connect with the changes in the main PR regarding project configurations, particularly if they affect how navigation and linking are handled within the application.

Suggested reviewers

  • alexrisch
  • thierryskoda

Poem

🐰 In Xcode's realm, a change takes flight,
Google Services group, no longer tight
Modules defined with careful care,
A rabbit's build config, beyond compare! 🛠️
Synchronization shifts, project anew
Hopping along, with changes in view! 🐇

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between be5749d and 184a1d7.

📒 Files selected for processing (9)
  • .gitignore (1 hunks)
  • app.config.ts (1 hunks)
  • package.json (3 hunks)
  • scripts/android/sendApk.sh (1 hunks)
  • utils/api.ts (9 hunks)
  • utils/apiConfig.ts (1 hunks)
  • utils/capture-error.ts (1 hunks)
  • utils/sentry.ts (1 hunks)
  • utils/xmtpRN/messages.ts (2 hunks)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@technoplato technoplato changed the base branch from ml/appcheck to release/3.0.0 December 18, 2024 20:59
@technoplato technoplato requested a review from a team as a code owner December 18, 2024 20:59
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
ios/Podfile (1)

72-77: LGTM: Module definition fix looks correct

The addition of DEFINES_MODULE = 'YES' for specific targets is a standard fix for Swift/Objective-C interoperability issues in React Native projects. This change should help resolve build errors related to module imports.

Note that this configuration ensures proper module interfaces for the specified targets. If you encounter similar build issues with other targets in the future, you may need to add them to this list.

ios/Converse.xcodeproj/project.pbxproj (1)

Line range hint 1-1: Overall Assessment of Build Pipeline Fixes

The changes address two potential build issues:

  1. Swift/Objective-C module interface problems via DEFINES_MODULE settings
  2. Google Services configuration management via project group restructuring

While the changes look reasonable for fixing build issues, please:

  1. Test the build pipeline with these changes
  2. Verify that Firebase/Google services continue to work as expected
  3. Consider adding comments in the code explaining why these changes were necessary to help future maintainers

Consider creating a troubleshooting guide in your documentation that covers:

  • Common build issues and their solutions
  • Steps to properly configure Google Services
  • Module definition requirements for different target types
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 29fa001 and 0029bbe.

⛔ Files ignored due to path filters (1)
  • ios/Podfile.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • ios/Converse.xcodeproj/project.pbxproj (1 hunks)
  • ios/Podfile (1 hunks)
🔇 Additional comments (1)
ios/Converse.xcodeproj/project.pbxproj (1)

141-147: Verify Google Services configuration after group restructuring

The change replaces the synchronized Google Services group with a regular empty group. While this might help with build issues, we should ensure that:

  1. Required Google Services configuration files are still properly included in the build
  2. Firebase/Google services functionality is not affected

If you're experiencing issues with Google Services synchronization:

  1. Ensure GoogleService-Info.plist is properly added to the project
  2. Verify Firebase initialization in your AppDelegate
  3. Consider documenting the reason for removing the synchronized group to help with future maintenance
✅ Verification successful

Google Services configuration is properly maintained despite group restructuring

The verification shows that while the Google Services group was changed to a regular group, the essential configuration is still properly maintained:

  • GoogleService-Info.plist is present in the iOS directory
  • The plist file is correctly referenced in the project.pbxproj with proper build phase entries
  • It's included in the Resources build phase for both main target and extension

The restructuring of the group appears to be a harmless organizational change that doesn't impact the actual Firebase configuration.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for Google Services configuration files and references

# Check for GoogleService-Info.plist
echo "Checking for GoogleService-Info.plist..."
fd "GoogleService-Info.plist"

# Check for Firebase configuration in the project
echo "Checking Firebase configuration..."
rg -l "FirebaseApp.configure"

Length of output: 258


Script:

#!/bin/bash
# Let's check the actual content of project.pbxproj for more context about Google Services references

# Check for any Google Services related entries in project.pbxproj
echo "Checking project.pbxproj for Google Services references..."
rg -A 5 "Google Services" "ios/Converse.xcodeproj/project.pbxproj"

# Check for Firebase related imports or configurations in source files
echo "Checking for Firebase usage in source files..."
rg -l "import Firebase|import FirebaseCore"

# Check if GoogleService-Info.plist is referenced in build phases
echo "Checking build phases for GoogleService-Info.plist..."
rg "GoogleService-Info.plist" "ios/Converse.xcodeproj/project.pbxproj"

Length of output: 1790

Copy link
Contributor

github-actions bot commented Dec 18, 2024

Performance Comparison Report

  • Current: 9c78e92 - 2024-12-20 19:40:49Z
  • Baseline: release/3.0.0 (9df24dc) - 2024-12-20 19:39:03Z

Significant Changes To Duration

There are no entries

Meaningless Changes To Duration

Show entries
Name Type Duration Count
Avatar Image 10 runs render 1.0 ms → 1.3 ms (+0.3 ms, +30.0%) 🔴 1 → 1
Avatar Image 50 runs render 1.1 ms → 1.1 ms (+0.0 ms, +1.8%) 1 → 1
Empty Avatar 10 runs render 0.9 ms → 0.9 ms 1 → 1
Empty Avatar 50 runs render 0.8 ms → 0.8 ms (-0.0 ms, -2.4%) 1 → 1
Text Component with color prop - 10 runs render 0.2 ms → 0.4 ms (+0.2 ms, +100.0%) 🔴 1 → 1
Text Component with default props - 10 runs render 0.4 ms → 0.2 ms (-0.2 ms, -50.0%) 🟢 1 → 1
Text Component with translation key - 10 runs render 0.2 ms → 0.2 ms 1 → 1
Text Component with weight and size - 10 runs render 0.0 ms → 0.2 ms (+0.2 ms, +Infinity%) 🔴 1 → 1
Show details
Name Type Duration Count
Avatar Image 10 runs render Baseline
Mean: 1.0 ms
Stdev: 0.0 ms (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1
Warmup runs: 2

Current
Mean: 1.3 ms
Stdev: 0.5 ms (37.2%)
Runs: 1 1 2 1 1 2 1 1 2 1
Warmup runs: 2
Baseline
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1
Render issues:

Current
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1
Render issues:
Avatar Image 50 runs render Baseline
Mean: 1.1 ms
Stdev: 0.4 ms (34.4%)
Runs: 1 1 2 1 1 2 1 1 1 1 1 2 1 2 1 1 1 1 1 1 2 1 1 1 1 2 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1
Warmup runs: 1

Current
Mean: 1.1 ms
Stdev: 0.4 ms (30.7%)
Runs: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 2 1 1 1 1 2 2 1 1 1 1 1 1 2 1 2 1 1 1 1 1 1 1 1 1 1 2 1 1 1
Warmup runs: 2
Baseline
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Render issues:

Current
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Render issues:
Empty Avatar 10 runs render Baseline
Mean: 0.9 ms
Stdev: 0.3 ms (35.1%)
Runs: 1 1 1 1 1 1 1 0 1 1
Warmup runs: 3

Current
Mean: 0.9 ms
Stdev: 0.3 ms (35.1%)
Runs: 1 1 1 1 1 1 1 1 0 1
Warmup runs: 3
Baseline
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1
Render issues:

Current
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1
Render issues:
Empty Avatar 50 runs render Baseline
Mean: 0.8 ms
Stdev: 0.4 ms (47.3%)
Runs: 1 1 1 1 1 0 1 0 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0
Warmup runs: 1

Current
Mean: 0.8 ms
Stdev: 0.4 ms (50.5%)
Runs: 1 0 1 1 1 1 0 1 0 1 1 1 0 1 1 0 1 1 1 1 0 1 0 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1
Warmup runs: 1
Baseline
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Render issues:

Current
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Render issues:
Text Component with color prop - 10 runs render Baseline
Mean: 0.2 ms
Stdev: 0.4 ms (210.8%)
Runs: 0 1 0 1 0 0 0 0 0 0
Warmup runs: 0

Current
Mean: 0.4 ms
Stdev: 0.5 ms (129.1%)
Runs: 1 1 0 0 0 0 1 0 0 1
Warmup runs: 1
Baseline
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1
Render issues:

Current
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1
Render issues:
Text Component with default props - 10 runs render Baseline
Mean: 0.4 ms
Stdev: 0.5 ms (129.1%)
Runs: 0 1 1 0 1 0 1 0 0 0
Warmup runs: 1

Current
Mean: 0.2 ms
Stdev: 0.4 ms (210.8%)
Runs: 0 0 0 1 0 1 0 0 0 0
Warmup runs: 0
Baseline
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1
Render issues:

Current
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1
Render issues:
Text Component with translation key - 10 runs render Baseline
Mean: 0.2 ms
Stdev: 0.4 ms (210.8%)
Runs: 0 0 0 0 0 1 0 0 0 1
Warmup runs: 1

Current
Mean: 0.2 ms
Stdev: 0.4 ms (210.8%)
Runs: 0 0 0 0 0 1 0 0 1 0
Warmup runs: 0
Baseline
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1
Render issues:

Current
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1
Render issues:
Text Component with weight and size - 10 runs render Baseline
Mean: 0.0 ms
Stdev: 0.0 ms (NaN%)
Runs: 0 0 0 0 0 0 0 0 0 0
Warmup runs: 0

Current
Mean: 0.2 ms
Stdev: 0.4 ms (210.8%)
Runs: 0 1 1 0 0 0 0 0 0 0
Warmup runs: 0
Baseline
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1
Render issues:

Current
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1
Render issues:

Render Count Changes

There are no entries

Render Issues

There are no entries

Added Scenarios

There are no entries

Removed Scenarios

There are no entries

Generated by 🚫 dangerJS against 184a1d7

utils/mmkv.ts Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (6)
utils/api.ts (3)

215-216: Acquire token earlier if possible.

Retrieving the appCheckToken within getXmtpApiHeaders is reasonable. If this function is invoked repeatedly, consider caching the token if it has a valid TTL or transitions rarely to reduce overhead.


217-223: Comprehensive fallback or user messaging.

The error message emphasizes potential tampering, which is excellent from a security standpoint. You might also consider providing user-friendly instructions for reinstalls or updates if they see this message.


395-399: Follow up on TODO comment.

A TODO mentions request is “401ing after ephemeral account creation.” This is presumably a known bug. Consider opening a separate issue to track progress and avoid losing sight of it.

queries/QueryKeys.ts (2)

61-61: Double-check queries for missing accounts.

If an account genuinely can be null, consider returning a fallback query key or skipping the fetch entirely to avoid no-op requests.


73-73: Ensure pinned frames handle no account states.

When account is missing, you might short-circuit. This can avoid potential server calls that will fail anyway.

screens/Navigation/Navigation.tsx (1)

51-51: Button usage.

Check that the new Button is used consistently with the design system. If not used or not fully integrated, remove it to avoid confusion.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 80e5789 and 8a41db6.

⛔ Files ignored due to path filters (1)
  • ios/Podfile.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • queries/QueryKeys.ts (3 hunks)
  • screens/Navigation/Navigation.tsx (2 hunks)
  • utils/api.ts (8 hunks)
🔇 Additional comments (15)
utils/api.ts (6)

33-33: Ensure clarity with constant naming.

The introduction of FIREBASE_APP_CHECK_HEADER_KEY clarifies the header’s purpose. Good practice would be to ensure consistent naming conventions (e.g., “APP_CHECK_HEADER_KEY”) across other files that utilize this constant, if any.


37-37: Confirm import usage and side effects.

The tryGetAppCheckToken import addresses your app integrity checks. Verify that its usage doesn’t introduce additional asynchronous overhead in all contexts, especially if it is called frequently or in performance-critical flows.


149-149: Appropriate header assignment.

You are appending the appCheckToken to the FIREBASE_APP_CHECK_HEADER_KEY. Ensure the token is sanitized or validated before sending to prevent potential security issues if the token is user-supplied in the future.


201-201: Augmented type clarity.

Defining [FIREBASE_APP_CHECK_HEADER_KEY]: string in XmtpApiHeaders clarifies that a valid string token is always expected. Make sure consumers are aware of the mandatory nature of appCheckToken.


238-239: Review destructuring style consistency.

You’re spreading installationKeySignature here. Confirm consistent usage in other areas to keep the code base uniform.


547-547: Assess potential edge cases.

Using await getXmtpApiHeaders(address) is consistent with other calls. Confirm that address cannot be undefined or null, or wrap calls in conditionals if the address can be empty.

queries/QueryKeys.ts (7)

33-33: Safe chaining for .toLowerCase().

Using optional chaining avoids runtime errors. Ensure that query consumers gracefully handle the case when account is null/undefined (e.g., no logged-in user).


39-39: Confirm uniform usage across keys.

You’re using optional chaining in conversationQueryKey as well. This is coherent with the pattern applied in other keys.


56-56: Consistent naming and approach.

Again, applying account?.toLowerCase() helps keep the logic consistent. Make sure that the rest of your code handles an empty account string or undefined properly.


67-67: Group members query key consistency.

The same optional chaining approach is present. This is consistent with your overall change.


89-89: Permissions key usage.

Tying group permissions to the optional-chained account is consistent. Verify that other areas calling groupPermissionsQueryKey do not rely on a guaranteed lowercase string.


101-101: Join request key approach.

Same pattern as above. Possibly add fallback or early exit if account is undefined, preventing wasted lookups.


105-105: Pending requests behavior.

Again, the optional chaining is consistent. Confirm that the rest of the code handles undefined account or returns an empty array instead of attempting an API call.

screens/Navigation/Navigation.tsx (2)

5-6: Added React Hooks and RN components.

The introduction of useEffect, useState, View, and Text suggests potential UI changes. Verify that these additions are necessary for your new or existing logic. If you planned refactors that never fully materialized, consider removing unused imports to reduce code size.


53-53: Leverage logger for consistent debug logs.

Using logger is a good practice. Ensure that sensitive or personally identifiable info is not logged inadvertently, especially in production.

utils/api.ts Show resolved Hide resolved
utils/api.ts Show resolved Hide resolved
utils/api.ts Show resolved Hide resolved
queries/QueryKeys.ts Show resolved Hide resolved
screens/Navigation/Navigation.tsx Outdated Show resolved Hide resolved
@technoplato technoplato changed the title attempting to fix build issues in piepline appcheck - ios Dec 19, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (2)
features/GroupInvites/joinGroup/JoinGroup.client.ts (2)

Line range hint 132-186: Enhance error handling and retry strategy

The polling implementation could be improved in two ways:

  1. Add try-catch for network failures during polling
  2. Implement exponential backoff for retries
     while (attemptsToRetryJoinGroup < GROUP_JOIN_REQUEST_POLL_MAX_ATTEMPTS) {
       logger.debug(
         `[liveAttemptToJoinGroup] Polling attempt ${
           attemptsToRetryJoinGroup + 1
         } of ${GROUP_JOIN_REQUEST_POLL_MAX_ATTEMPTS}`
       );
-      const joinRequestData = await getGroupJoinRequest(joinRequestId);
+      try {
+        const joinRequestData = await getGroupJoinRequest(joinRequestId);
+      } catch (error) {
+        logger.error(`[liveAttemptToJoinGroup] Network error during polling: ${error}`);
+        // Continue polling despite network error
+        attemptsToRetryJoinGroup += 1;
+        const backoffMs = GROUP_JOIN_REQUEST_POLL_INTERVAL_MS * Math.pow(2, attemptsToRetryJoinGroup);
+        await wait(backoffMs);
+        continue;
+      }

       if (joinRequestData.status !== "PENDING") {

Line range hint 293-294: Fix TypeScript type issues in test fixtures

There are several @ts-expect-error comments indicating type mismatches in the test fixtures. These should be properly typed rather than suppressed.

Consider creating proper type definitions for the test fixtures:

type ConversationFixture = Pick<Conversation, 
  | 'id' 
  | 'createdAt' 
  | 'members' 
  | 'topic' 
  | 'isGroupActive' 
  | 'state' 
  | 'creatorInboxId'
  | 'name'
  | 'addedByInboxId'
  | 'imageUrlSquare'
  | 'description'
>;

const createConversationFixture = (props: Partial<ConversationFixture>): Conversation => {
  return {
    id: 'default-id' as ConversationId,
    createdAt: new Date().getTime(),
    members: async () => [],
    topic: 'default-topic' as ConversationTopic,
    isGroupActive: true,
    state: 'allowed',
    creatorInboxId: async () => '0xabc' as InboxId,
    name: 'Default Group',
    addedByInboxId: '0x123' as InboxId,
    imageUrlSquare: 'https://example.com',
    description: 'Default Description',
    ...props
  } as Conversation;
};

Also applies to: 386-387, 486-487

🧹 Nitpick comments (2)
features/GroupInvites/joinGroup/JoinGroup.client.ts (1)

27-30: Consider making polling configuration environment-specific

The polling constants could be moved to a configuration file to allow different values for different environments (e.g., development, staging, production).

-const GROUP_JOIN_REQUEST_POLL_MAX_ATTEMPTS = 10;
-const GROUP_JOIN_REQUEST_POLL_INTERVAL_MS = 1000;
+import { config } from '@/config';
+
+const GROUP_JOIN_REQUEST_POLL_MAX_ATTEMPTS = config.groupJoin.maxAttempts ?? 10;
+const GROUP_JOIN_REQUEST_POLL_INTERVAL_MS = config.groupJoin.intervalMs ?? 1000;
config.ts (1)

Line range hint 73-128: Consider adding runtime configuration validation.

The configuration structure is well-organized, but consider adding runtime validation to ensure all required Firebase App Check configurations are present and correctly typed. This could help catch configuration issues early, especially for the new appCheckDebugToken property.

Example approach:

type Config = {
  // ... other config types
  appCheckDebugToken: string | undefined;
};

function validateConfig(config: Config): void {
  if (__DEV__ && !config.appCheckDebugToken) {
    console.warn('Missing appCheckDebugToken in development environment');
  }
  // Add other validation rules
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 26398a4 and 16ff4f5.

⛔ Files ignored due to path filters (3)
  • ios/Gemfile.lock is excluded by !**/*.lock
  • ios/Podfile.lock is excluded by !**/*.lock
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (6)
  • app.config.ts (1 hunks)
  • config.ts (3 hunks)
  • eas.json (2 hunks)
  • features/GroupInvites/joinGroup/JoinGroup.client.ts (1 hunks)
  • ios/Gemfile (1 hunks)
  • package.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • package.json
  • eas.json
  • app.config.ts
🔇 Additional comments (6)
config.ts (4)

94-94: LGTM! Correctly disabled debug token in preview environment.

Setting appCheckDebugToken to undefined in preview environment is the right approach to ensure debug tokens are not used outside development.


128-128: LGTM! Correctly disabled debug token in production environment.

Setting appCheckDebugToken to undefined in production environment is the right approach to ensure debug tokens are never used in production.


73-75: Verify Firebase App Check debug token usage.

The implementation correctly handles platform-specific debug tokens for development. However, ensure that:

  1. These debug tokens are only used in development builds
  2. The environment variables are properly secured and not committed to version control

Let's verify the environment variables usage:

✅ Verification successful

Firebase App Check debug tokens are properly secured

The implementation follows security best practices:

  • Debug tokens are only accessed via environment variables with the EXPO_PUBLIC_ prefix
  • All .env* files are properly gitignored
  • The .xcode.env file that is versioned doesn't contain any sensitive tokens
  • Debug tokens are only used in the development configuration, not in preview or production environments
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if debug tokens are accidentally committed
rg -g '!*.md' "FIREBASE_APP_CHECK_DEBUG_TOKEN"

# Check for any .env files that might contain these tokens
fd -H "\.env.*$"

Length of output: 239


Script:

#!/bin/bash
# Check the content of .xcode.env to ensure it doesn't contain debug tokens
cat ios/.xcode.env

# Check if the debug tokens are used only in development configuration
rg -B 5 -A 5 "FIREBASE_APP_CHECK_DEBUG_TOKEN"

# Check for any gitignore patterns related to env files
cat .gitignore | grep -i "env"

Length of output: 1121


132-132: Verify the usage of exported getConfig function.

The function is now exported, likely to support Firebase App Check integration. Let's verify its usage across the codebase.

✅ Verification successful

Let me verify the usage of the exported getConfig function with one more check to ensure we have a complete picture.

This will help us confirm:

  1. Any direct usage of getConfig() function
  2. How it's being used in appCheck.ts where we found the named import

Export of getConfig function is correctly implemented and used

The verification shows that:

  1. The getConfig function is exported and used as the default export (export default getConfig())
  2. It's properly imported and used in utils/appCheck.ts for Firebase App Check configuration
  3. Other files import the default export (the result of getConfig()), which is the expected pattern
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for direct imports of getConfig
rg "import.*\{.*getConfig.*\}.*from.*['\"].*config['\"]"

# Check for potential usage through default import
rg "import.*config.*from.*['\"].*config['\"]"

Length of output: 2342


Script:

#!/bin/bash
# Check for direct usage of getConfig function
rg "getConfig\(\)"

# Check the implementation in appCheck.ts where it's explicitly imported
cat utils/appCheck.ts

Length of output: 1798

ios/Gemfile (2)

3-4: LGTM! Good practice adding bundler version requirement.

Adding the minimum bundler version requirement is a proactive measure to ensure compatibility with Ruby 3.3.x, which is especially important given the Firebase-related changes in the project.


4-4: Verify bundler version in CI/CD environment.

Ensure that your CI/CD environment has a compatible bundler version (>= 2.4.0) to prevent potential build issues.

✅ Verification successful

Let me try to check the CI/CD configuration files more broadly to find any Ruby or bundler-related setup.


Let me try one more search specifically for Ruby and bundler setup in the iOS directory.


Let me try one final check to look for Ruby-related configuration in the iOS directory.


Based on the output from the searches, I can see that the project has a Gemfile.lock that shows bundler 2.6.1 is being used, which is already higher than the required version (>= 2.4.0) specified in the Gemfile. Additionally, the CI/CD workflows shown in the GitHub Actions configurations don't directly interact with Ruby/bundler as they use EAS (Expo Application Services) for building.

The bundler version requirement is already satisfied in the project.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the current bundler version in package.json scripts or GitHub Actions workflow files

# Check for bundler version specifications in GitHub Actions workflow files
echo "Checking GitHub Actions workflow files for bundler version:"
fd -e yml -e yaml . .github/workflows/ --exec grep -l "bundler"

# Check for bundle commands in package.json scripts
echo "Checking package.json for bundle-related scripts:"
fd package.json -x jq -r '.scripts | to_entries | .[] | select(.value | contains("bundle"))'

Length of output: 396


Script:

#!/bin/bash
# Check for any CI configuration files that might contain Ruby or bundler setup
echo "Checking CI configuration files:"
fd -e yml -e yaml . .github/workflows/ -x cat {}

# Check if there are any other CI configuration files
echo -e "\nChecking for other CI config files:"
fd -e yml -e yaml . -x echo {}

# Check Ruby version files
echo -e "\nChecking Ruby version files:"
fd -g "*ruby*" -g "*gemfile*" -g ".ruby-version" -X cat {}

Length of output: 19267


Script:

#!/bin/bash
# Check for Ruby and bundler setup in iOS directory
echo "Checking iOS directory for Ruby and bundler setup:"
fd . ios/ -x cat {}

# Check for any EAS build configuration that might handle Ruby setup
echo -e "\nChecking EAS configuration:"
fd eas.json -x cat {}

Length of output: 66699


Script:

#!/bin/bash
# Check for Ruby and bundler setup in iOS directory, focusing on specific files
echo "Checking iOS Ruby configuration:"
fd -t f -e rb -e gemfile -e lock . ios/ -x cat {}

# Check for any Ruby version file
echo -e "\nChecking for Ruby version file:"
fd -t f -g ".ruby-version" . -x cat {}

Length of output: 69084

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🔭 Outside diff range comments (1)
utils/logger.ts (1)

Line range hint 41-45: Add error handling for file operations.

The file operations (writeFile, appendFile) should include error handling to gracefully handle potential I/O failures.

Consider wrapping file operations in try-catch blocks:

 export const rotateLoggingFile = async () => {
+  try {
     if (loggingFilePath && (await RNFS.exists(loggingFilePath))) {
       await RNFS.unlink(loggingFilePath);
     }
     const tempDir = RNFS.TemporaryDirectoryPath;
     loggingFilePath = path.join(tempDir, `${uuidv4()}.converse.log.txt`);
     const appVersion = Constants.expoConfig?.version;
     const buildNumber =
       Platform.OS === "ios"
         ? Constants.expoConfig?.ios?.buildNumber
         : Constants.expoConfig?.android?.versionCode;
     await RNFS.writeFile(
       loggingFilePath,
       `Converse ${Platform.OS} logs - v${appVersion} (${buildNumber})\n\n`
     );
+  } catch (error) {
+    console.error('Failed to rotate log file:', error);
+    // Consider sending this to Sentry
+    sentryTrackError('Log rotation failed', error);
+  }
 };

Similarly for the append operation in converseTransport:

   if (!loggingFilePath) {
     await rotateLoggingFile();
   }
+  try {
     await RNFS.appendFile(loggingFilePath, `${props.msg}\n`, "utf8");
+  } catch (error) {
+    console.error('Failed to append to log file:', error);
+    sentryTrackError('Log append failed', error);
+  }

Also applies to: 66-69

🧹 Nitpick comments (5)
utils/getEnv.ts (1)

28-34: Consider caching the environment value

The current implementation calls getEnv() multiple times through the exported constants, which could lead to unnecessary environment checks.

Consider caching the environment value:

+const currentEnv = (() => {
+  const isExpoEnvDev = process.env.EXPO_ENV === "dev";
+  if (__DEV__ || isExpoEnvDev) {
+    return Environments.dev;
+  } else if (Constants.expoConfig?.extra?.ENV === "preview") {
+    return Environments.preview;
+  } else {
+    return Environments.prod;
+  }
+})();

-export const getEnv = (): Environment => {
+export const getEnv = (): Environment => currentEnv;
utils/appCheck.ts (1)

17-18: Remove commented code

There's commented out code that appears to be an alternative implementation. Either use it or remove it.

utils/apiConfig.ts (1)

69-73: Enhance process.env type declaration

The current type declaration is too permissive. Consider adding specific environment variable types.

declare const process: {
  env: {
    EXPO_PUBLIC_DEV_API_URI: string;
    EXPO_PUBLIC_PROD_API_URI?: string;
    NODE_ENV: 'development' | 'production' | 'test';
    // Add other environment variables
  };
};
config.ts (2)

76-78: Add validation for Firebase App Check debug tokens.

While the implementation correctly handles platform-specific tokens, consider adding validation for the environment variables to fail fast if they're not properly configured.

Consider adding validation in the dev environment:

     appCheckDebugToken: isAndroid
-      ? process.env.EXPO_PUBLIC_FIREBASE_APP_CHECK_DEBUG_TOKEN_ANDROID
-      : process.env.EXPO_PUBLIC_FIREBASE_APP_CHECK_DEBUG_TOKEN_IOS,
+      ? process.env.EXPO_PUBLIC_FIREBASE_APP_CHECK_DEBUG_TOKEN_ANDROID || 
+        (function() { 
+          throw new Error('Missing Android App Check debug token in dev environment');
+        })()
+      : process.env.EXPO_PUBLIC_FIREBASE_APP_CHECK_DEBUG_TOKEN_IOS ||
+        (function() {
+          throw new Error('Missing iOS App Check debug token in dev environment');
+        })(),

Also applies to: 97-97, 131-131


135-141: Add type safety for environment configuration.

Consider adding type guards to ensure type safety when working with environment configurations.

Consider this improvement:

+type EnvConfig = typeof ENV[keyof typeof ENV];
+
+function isValidEnv(env: unknown): env is EnvConfig {
+  return env === ENV.dev || env === ENV.preview || env === ENV.prod;
+}
+
 export const getConfig = () => {
+  let config: EnvConfig;
   if (isDev) {
-    return ENV.dev;
+    config = ENV.dev;
   } else if (isPreview) {
-    return ENV.preview;
+    config = ENV.preview;
   } else {
-    return ENV.prod;
+    config = ENV.prod;
   }
+  if (!isValidEnv(config)) {
+    throw new Error('Invalid environment configuration');
+  }
+  return config;
 };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bab6fb1 and be5749d.

📒 Files selected for processing (7)
  • app.config.ts (4 hunks)
  • config.ts (5 hunks)
  • package.json (2 hunks)
  • utils/apiConfig.ts (1 hunks)
  • utils/appCheck.ts (1 hunks)
  • utils/getEnv.ts (1 hunks)
  • utils/logger.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • package.json
  • app.config.ts
🔇 Additional comments (4)
utils/appCheck.ts (2)

26-44: Verify secure handling of debug tokens

The implementation includes debug tokens for development. This requires careful handling to ensure these tokens don't leak into production.

Let's verify the configuration:

✅ Verification successful

Let me check the config.ts file to understand how the debug tokens are handled.


Debug tokens are properly secured in the configuration

The implementation safely handles debug tokens through environment variables with proper environment segregation:

  • Debug tokens are only enabled in development environment
  • Preview and production environments explicitly set appCheckDebugToken to undefined
  • Debug tokens are sourced from environment variables (EXPO_PUBLIC_FIREBASE_APP_CHECK_DEBUG_TOKEN_ANDROID and EXPO_PUBLIC_FIREBASE_APP_CHECK_DEBUG_TOKEN_IOS)
  • The __DEV__ flag in appCheck.ts ensures debug provider is only used in development
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential debug token leaks in configuration files
rg -g '!node_modules' -g '!.git' -i 'appCheckDebugToken'

# Check EAS configuration
fd -g 'eas.json' -x cat {} | jq '.builds'

Length of output: 373


Script:

#!/bin/bash
# Check the implementation of debug tokens in config
cat config.ts

# Also check for any environment-specific configuration files
fd -g '*.env*' -x cat {}

Length of output: 4519


12-18: Address open questions in comments

The comments contain important questions about the implementation that should be addressed:

  1. "Do we need/want to use the limited use token?"
  2. "What endpoints are protected with app check?"

These decisions could have security implications.

Let's check the backend implementation:

✅ Verification successful

Use Limited Use Token for Enhanced Security

Based on the codebase analysis, I can provide clear answers to the implementation questions:

  1. "Do we need/want to use the limited use token?" - Yes, the limited use token should be used. The code currently uses getLimitedUseToken() which is the correct choice as it provides better security by limiting token reuse.

  2. "What endpoints are protected?" - The implementation shows App Check is used to protect:

  • Authentication endpoint /api/authenticate
  • All API requests through the api utility, as tokens are required in headers

The current implementation is secure because:

  • App Check is properly initialized with platform-specific providers (Play Integrity for Android, App Attest for iOS)
  • Debug tokens are only enabled in development
  • Token auto-refresh is enabled
  • API requests fail gracefully if App Check token is missing
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check the referenced middleware implementation
gh api repos/ephemeraHQ/converse-backend/contents/api/middlewares.ts | jq -r '.content' | base64 -d | grep -A 10 "app check"

Length of output: 246


Script:

#!/bin/bash
# Let's check the current repository for App Check implementation details
rg -A 5 "appCheck" --type ts

Length of output: 4406


Script:

#!/bin/bash
# Search for Firebase App Check configuration
rg -A 5 "getLimitedUseToken|getToken" --type ts

Length of output: 398


Script:

#!/bin/bash
# Look for any documentation about App Check setup
fd README.md | xargs cat | grep -i "app check" -A 5

Length of output: 53

utils/logger.ts (1)

13-13: LGTM! Environment check refactoring improves code organization.

The change to use isDev from a dedicated environment utility improves code organization by centralizing environment management.

Also applies to: 57-57

config.ts (1)

5-6: LGTM! API configuration modularization improves code organization.

Moving API URI configuration to a dedicated module improves maintainability and separation of concerns.

Also applies to: 57-58

utils/getEnv.ts Show resolved Hide resolved
utils/apiConfig.ts Outdated Show resolved Hide resolved
utils/apiConfig.ts Outdated Show resolved Hide resolved
@technoplato technoplato changed the title appcheck - ios appcheck Dec 20, 2024
@@ -13,7 +13,7 @@
"ios": "expo run:ios",
"run:ios": "EXPO_ENV=dev expo run:ios",
"postinstall": "patch-package && node scripts/wasm.js && husky install && cross-os postinstall",
"start": "EXPO_ENV=dev expo start",
"start": "EXPO_ENV=dev expo start --scheme converse-dev",
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

physical device runs weren't working without this

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

this file fixes connecting to converse-backend on LAN via physical device

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

i'll do better type validation on env later, just wanted to get this cleaned up for now

@@ -5,6 +5,7 @@
"android": "EXPO_ENV=dev expo run:android",
"android:build:dev": "eas build -p android --profile development --local",
"android:reverse": "adb reverse tcp:8081 tcp:8081 && adb reverse tcp:9875 tcp:9875",
"android:sendApk": "./scripts/android/sendApk.sh",
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

some android physical device qol improvements: https://www.loom.com/share/867a810a8df34a29bb45845d50e01a37

@technoplato technoplato merged commit 13b0666 into release/3.0.0 Dec 20, 2024
6 of 7 checks passed
@technoplato technoplato deleted the ml/appcheck-build-fix-trials branch December 20, 2024 19:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants