Skip to content

Conversation

@0xFirekeeper
Copy link
Member

@0xFirekeeper 0xFirekeeper commented Sep 25, 2025

Introduces native macOS OAuth browser integration via a new MacBrowser implementation, including native plugin, bridging code, and build instructions. Updates browser selection logic to support macOS standalone builds and refactors platform detection to treat macOS as a mobile runtime for authentication flows.


PR-Codex overview

This PR introduces a MacBrowser implementation for the Thirdweb Unity SDK, enhancing OAuth support on macOS. It includes the addition of a native bridge using libMacBrowser.dylib, updates to various scripts, and improvements in handling mobile platform detection.

Detailed summary

  • Added MacBrowser class for OAuth login on macOS.
  • Introduced libMacBrowser.dylib for native functionality.
  • Updated ThirdwebManagerBase.cs to use IsMobileRuntime() for mobile detection.
  • Enhanced error handling in authentication sessions.
  • Provided detailed rebuild instructions in README.md.
  • Updated metadata files with new guid and fileFormatVersion.

✨ Ask PR-Codex anything about this PR by commenting with /codex {your question}

Summary by CodeRabbit

  • New Features

    • Added native macOS authentication support for standalone builds, enabling OAuth/login via the system web authentication session.
    • Introduced a macOS browser implementation used automatically on macOS standalone.
  • Improvements

    • Unified platform detection to better route “mobile-like” login behavior on macOS standalone.
    • Enhanced login flow with clearer result handling and cancellation support across iOS and macOS.
  • Bug Fixes

    • Added defensive checks to prevent null/dangling session issues and surface initialization failures.
  • Documentation

    • Added build instructions for the macOS native bridge and universal binary creation.

Introduces native macOS OAuth browser integration via a new MacBrowser implementation, including native plugin, bridging code, and build instructions. Updates browser selection logic to support macOS standalone builds and refactors platform detection to treat macOS as a mobile runtime for authentication flows.
@coderabbitai
Copy link

coderabbitai bot commented Sep 25, 2025

Walkthrough

Introduces a macOS native bridge (Objective‑C++) wrapping ASWebAuthenticationSession, Unity plugin metadata, and a universal dylib. Updates Unity runtime to use MacBrowser on Standalone macOS, extends browser flow and interop in iOS/macOS C# code, and centralizes mobile runtime detection via a new IsMobileRuntime method.

Changes

Cohort / File(s) Summary
macOS Plugin: native bridge, binary, metadata, docs
Assets/Thirdweb/Plugins/macOS/* (macOS.meta, MacBrowser.mm, MacBrowser.mm.meta, libMacBrowser.dylib.meta, README.md, README.md.meta)
Adds Objective‑C++ wrapper for ASWebAuthenticationSession with C-callable APIs; supplies Unity PluginImporter configs for platforms; documents build steps for universal libMacBrowser.dylib; adds folder and file meta.
Unity runtime: browser integration
Assets/Thirdweb/Runtime/Unity/Browser/CrossPlatformUnityBrowser.cs, Assets/Thirdweb/Runtime/Unity/Browser/iOSBrowser.cs
Routes UNITY_STANDALONE_OSX to MacBrowser implementation; expands interop for macOS (__DLLEntry name switch), adds MacBrowser and IOSBrowser classes implementing IThirdwebBrowser; improves session init checks, disposal safety, and completion handling.
Runtime: platform detection
Assets/Thirdweb/Runtime/Unity/ThirdwebManagerBase.cs
Adds protected virtual IsMobileRuntime that returns true on OSXPlayer or Application.isMobilePlatform; replaces prior isMobilePlatform checks in login flows.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant Unity as Unity (C#)
  participant Browser as MacBrowser (C#)
  participant Native as libMacBrowser.dylib (ObjC++)
  participant ASWeb as ASWebAuthenticationSession
  User->>Unity: Trigger Login (Standalone macOS)
  Unity->>Browser: Login(url, scheme, redirect)
  Browser->>Native: InitWithURL(url, scheme, callback*)
  note right of Native: Stores C callback<br/>creates ASWebAuthenticationSession
  Browser->>Native: Start()
  Native->>ASWeb: start()
  ASWeb-->>Native: completion(url?, error?)
  Native-->>Browser: callback(urlStr, errorCode)
  Browser->>Unity: BrowserResult(success|canceled|error)
  Unity-->>User: Login result

  opt Cancellation
    Unity->>Browser: Cancel()
    Browser->>Native: Cancel()
    ASWeb-->>Native: completion(nil, canceled)
    Native-->>Browser: callback(nil, canceled)
    Browser->>Unity: BrowserResult(canceled)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.69% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title specifically describes the introduction of macOS OAuth browser support and integrating it into the platform detection and browser selection logic, which directly reflects the primary functionality added in this changeset.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch firekeeper/mac-auth

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@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: 4

🧹 Nitpick comments (7)
Assets/Thirdweb/Plugins/macOS/README.md (1)

9-15: Fix invalid clang flag and ensure consistent macOS build commands.

  • -ObjC++ is not a valid clang flag; use -fobjc-arc (if ARC is desired). The .mm extension already selects Objective‑C++.
  • Keep -framework Cocoa -framework AuthenticationServices.

Apply:

-clang++ -std=c++17 -ObjC++ -fmodules -Wall -Werror -arch arm64 -framework Cocoa -framework AuthenticationServices -dynamiclib MacBrowser.mm -o /tmp/libMacBrowser_arm64.dylib
-clang++ -std=c++17 -ObjC++ -fmodules -Wall -Werror -arch x86_64 -framework Cocoa -framework AuthenticationServices -dynamiclib MacBrowser.mm -o /tmp/libMacBrowser_x86_64.dylib
+clang++ -std=c++17 -fobjc-arc -fmodules -Wall -Werror -arch arm64   -framework Cocoa -framework AuthenticationServices -dynamiclib MacBrowser.mm -o /tmp/libMacBrowser_arm64.dylib
+clang++ -std=c++17 -fobjc-arc -fmodules -Wall -Werror -arch x86_64 -framework Cocoa -framework AuthenticationServices -dynamiclib MacBrowser.mm -o /tmp/libMacBrowser_x86_64.dylib
Assets/Thirdweb/Runtime/Unity/ThirdwebManagerBase.cs (2)

455-462: Centralizing isMobile via IsMobileRuntime is good—verify downstream expectations.

Passing macOS as “mobile” changes OAuth/SIWE URL and redirect handling. Ensure wallet flows and deep-link handling expect this on macOS.

If divergence is needed, consider a separate IsEmbeddedBrowserRuntime() or an explicit macOS flag to avoid conflating with true mobile.


601-609: Treating OSXPlayer as “mobile” is a product choice—document or gate it.

Return true for macOS affects all isMobile flows. Add a short comment or a config toggle to make this intentional and adjustable.

 protected virtual bool IsMobileRuntime()
 {
-    if (Application.platform == RuntimePlatform.OSXPlayer)
-    {
-        return true;
-    }
+    // Treat macOS standalone as "mobile" to use ASWebAuthenticationSession-style flows.
+    if (Application.platform == RuntimePlatform.OSXPlayer) return true;
     return Application.isMobilePlatform;
 }
Assets/Thirdweb/Runtime/Unity/Browser/iOSBrowser.cs (4)

46-53: Dispose safety is good—consider native release to avoid leaks.

If native allocates, consider exposing and calling a Release/Dispose P/Invoke to free native memory on Dispose() (in addition to Cancel()).

Can you confirm MacBrowser.mm frees its session object on cancel/completion?


80-88: Completion callback dictionary: consider cleanup after callback.

You rely on Dispose to remove entries; if Dispose is delayed, the dictionary may retain callbacks longer than needed. Optionally remove in OnAuthenticationSessionCompleted after invoking the callback.

 if (CompletionCallbacks.TryGetValue(session, out var callback))
 {
     callback?.Invoke(callbackUrl, new ASWebAuthenticationSessionError((ASWebAuthenticationSessionErrorCode)errorCode, errorMessage));
+    CompletionCallbacks.Remove(session);
 }

105-115: Use RunContinuationsAsynchronously and dispose cancellation registration.

Prevents inline continuation reentrancy and avoids leaking the registration.

-            _taskCompletionSource = new TaskCompletionSource<BrowserResult>();
+            _taskCompletionSource = new TaskCompletionSource<BrowserResult>(TaskCreationOptions.RunContinuationsAsynchronously);
...
-            cancellationToken.Register(() =>
-            {
-                _taskCompletionSource?.TrySetCanceled();
-            });
+            using var ctr = cancellationToken.Register(() => _taskCompletionSource?.TrySetCanceled());

Apply similarly to the MacBrowser Login method.


151-210: MacBrowser implementation mirrors iOS cleanly—apply the same TCS/cancellation improvements.

Mirror the RunContinuationsAsynchronously and disposable cancellation registration changes here too.

-            _taskCompletionSource = new TaskCompletionSource<BrowserResult>();
+            _taskCompletionSource = new TaskCompletionSource<BrowserResult>(TaskCreationOptions.RunContinuationsAsynchronously);
...
-            cancellationToken.Register(() =>
-            {
-                _taskCompletionSource?.TrySetCanceled();
-            });
+            using var ctr = cancellationToken.Register(() => _taskCompletionSource?.TrySetCanceled());
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 1856b75 and 088af6b.

⛔ Files ignored due to path filters (1)
  • Assets/Thirdweb/Plugins/macOS/libMacBrowser.dylib is excluded by !**/*.dylib
📒 Files selected for processing (9)
  • Assets/Thirdweb/Plugins/macOS.meta (1 hunks)
  • Assets/Thirdweb/Plugins/macOS/MacBrowser.mm (1 hunks)
  • Assets/Thirdweb/Plugins/macOS/MacBrowser.mm.meta (1 hunks)
  • Assets/Thirdweb/Plugins/macOS/README.md (1 hunks)
  • Assets/Thirdweb/Plugins/macOS/README.md.meta (1 hunks)
  • Assets/Thirdweb/Plugins/macOS/libMacBrowser.dylib.meta (1 hunks)
  • Assets/Thirdweb/Runtime/Unity/Browser/CrossPlatformUnityBrowser.cs (1 hunks)
  • Assets/Thirdweb/Runtime/Unity/Browser/iOSBrowser.cs (5 hunks)
  • Assets/Thirdweb/Runtime/Unity/ThirdwebManagerBase.cs (6 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
Assets/Thirdweb/Runtime/Unity/Browser/CrossPlatformUnityBrowser.cs (1)
Assets/Thirdweb/Runtime/Unity/Browser/iOSBrowser.cs (1)
  • MacBrowser (152-209)
Assets/Thirdweb/Runtime/Unity/Browser/iOSBrowser.cs (2)
Assets/Thirdweb/Runtime/Unity/Browser/CrossPlatformUnityBrowser.cs (1)
  • Task (47-50)
Assets/Thirdweb/Runtime/Unity/ThirdwebManagerBase.cs (6)
  • Task (304-312)
  • Task (338-343)
  • Task (357-541)
  • Task (543-584)
  • Task (586-599)
  • ThirdwebClient (241-241)
🔇 Additional comments (4)
Assets/Thirdweb/Plugins/macOS.meta (1)

1-8: LGTM — standard folder meta.

Assets/Thirdweb/Plugins/macOS/README.md.meta (1)

1-7: LGTM — text asset meta is fine.

Assets/Thirdweb/Runtime/Unity/Browser/CrossPlatformUnityBrowser.cs (1)

40-44: Nice: macOS routed to MacBrowser.

This cleanly extends platform coverage.

Assets/Thirdweb/Runtime/Unity/Browser/iOSBrowser.cs (1)

28-34: Init guard is good.

Throwing when session init returns zero avoids null deref later.

Comment on lines +14 to +27
- first:
: Any
second:
enabled: 0
settings:
Exclude Android: 1
Exclude Editor: 1
Exclude Linux64: 1
Exclude OSXUniversal: 0
Exclude WebGL: 1
Exclude Win: 1
Exclude Win64: 1
Exclude iOS: 1
- first:
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

🧩 Analysis chain

Exclude the .mm source from macOS Standalone to avoid duplicate/accidental compilation.

Since you ship a prebuilt dylib, ensure the Objective‑C++ source isn’t included for Standalone OSX. The “Any/Exclude OSXUniversal: 0” plus “Standalone/OSXUniversal enabled: 0” mix is easy to misconfigure.

Set the .mm to be excluded on OSXUniversal at the “Any” level (and keep Standalone/OSXUniversal disabled):

-        Exclude OSXUniversal: 0
+        Exclude OSXUniversal: 1

Please confirm in Unity that only libMacBrowser.dylib is included in macOS builds.

Also applies to: 54-61


🏁 Script executed:

#!/bin/bash
set -e
echo "---- Lines with OSXUniversal ----"
grep -n 'OSXUniversal' Assets/Thirdweb/Plugins/macOS/MacBrowser.mm.meta || true
echo
echo "---- Lines with Standalone ----"
grep -n 'Standalone' Assets/Thirdweb/Plugins/macOS/MacBrowser.mm.meta || true
echo
echo "---- Full contents of MacBrowser.mm.meta ----"
nl -ba Assets/Thirdweb/Plugins/macOS/MacBrowser.mm.meta

Length of output: 339


🏁 Script executed:

#!/bin/bash
set -e
echo "---- Context around 'Exclude OSXUniversal' (lines 15–30) ----"
sed -n '15,30p' Assets/Thirdweb/Plugins/macOS/MacBrowser.mm.meta
echo
echo "---- Context around 'Standalone: OSXUniversal' (lines 45–60) ----"
sed -n '45,60p' Assets/Thirdweb/Plugins/macOS/MacBrowser.mm.meta

Length of output: 776


Exclude MacBrowser.mm from OSXUniversal at the default level
Set Exclude OSXUniversal to 1 under the default Any settings (keep Standalone: OSXUniversal enabled: 0) to prevent the .mm source from compiling alongside the dylib.

-        Exclude OSXUniversal: 0
+        Exclude OSXUniversal: 1

Confirm only libMacBrowser.dylib is included in macOS builds.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- first:
: Any
second:
enabled: 0
settings:
Exclude Android: 1
Exclude Editor: 1
Exclude Linux64: 1
Exclude OSXUniversal: 0
Exclude WebGL: 1
Exclude Win: 1
Exclude Win64: 1
Exclude iOS: 1
- first:
- first:
: Any
second:
enabled: 0
settings:
Exclude Android: 1
Exclude Editor: 1
Exclude Linux64: 1
Exclude OSXUniversal: 1
Exclude WebGL: 1
Exclude Win: 1
Exclude Win64: 1
Exclude iOS: 1
- first:
🤖 Prompt for AI Agents
In Assets/Thirdweb/Plugins/macOS/MacBrowser.mm.meta around lines 14 to 27, the
default Any platform settings currently have "Exclude OSXUniversal: 0" so the
.mm source can compile alongside the dylib; update the Any section to set
"Exclude OSXUniversal" to 1 (leave any Standalone: OSXUniversal entry with
enabled: 0 as-is) so the MacBrowser.mm source is excluded at the default level;
after changing the meta, verify macOS builds only include libMacBrowser.dylib
and not the .mm source.

@0xFirekeeper 0xFirekeeper merged commit 695d774 into v5 Sep 27, 2025
3 checks passed
@0xFirekeeper 0xFirekeeper deleted the firekeeper/mac-auth branch September 27, 2025 11:56
@0xFirekeeper
Copy link
Member Author

@coderabbitai create a short user-facing changelog for this

@coderabbitai
Copy link

coderabbitai bot commented Sep 27, 2025

Tip

For best results, initiate chat on the files or code changes.

@0xFirekeeper Here's a short user-facing changelog for this PR:

🍎 macOS OAuth Browser Support

✨ New Features

  • Native macOS OAuth Integration: Added support for OAuth authentication flows on macOS standalone builds using native ASWebAuthenticationSession
  • Universal Binary Support: Includes optimized native plugin with both ARM64 and x86_64 architecture support

🔧 Improvements

  • Enhanced Platform Detection: macOS is now properly detected and handled in authentication workflows
  • Seamless Browser Experience: OAuth flows on macOS now use the system's native web authentication session for better security and user experience

📦 What's Included

  • Native macOS plugin (libMacBrowser.dylib)
  • MacBrowser class implementation
  • Build instructions for plugin compilation
  • Updated browser selection logic for macOS builds

This update enables developers to deploy Unity applications with fully functional OAuth authentication on macOS platforms.

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