Skip to content

Commit 6442e5f

Browse files
wesbillmanBrain
andcommitted
Fix mobile onboarding policy loading, browser cancellation and pairing feedback
Co-authored-by: Brain <1a02c72794dcd0f07058a353bc3a81f4028b8c77c92c87fce6d5c8b85970a20b@buzz.block.builderlab.xyz> Signed-off-by: Wes <[email protected]>
1 parent a12ad1c commit 6442e5f

13 files changed

Lines changed: 301 additions & 19 deletions

File tree

‎mobile/android/app/build.gradle.kts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,7 @@ android {
199199
dependencies {
200200
implementation("com.google.android.play:age-signals:0.0.4")
201201
implementation("androidx.appcompat:appcompat:1.6.1")
202+
implementation("androidx.browser:browser:1.9.0")
202203

203204
testImplementation(kotlin("test"))
204205

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
package xyz.block.buzz.mobile
2+
3+
import android.app.Activity
4+
import android.content.Intent
5+
import android.net.Uri
6+
import androidx.test.ext.junit.runners.AndroidJUnit4
7+
import androidx.test.platform.app.InstrumentationRegistry
8+
import io.flutter.plugin.common.BinaryMessenger
9+
import io.flutter.plugin.common.FlutterException
10+
import io.flutter.plugin.common.MethodCall
11+
import io.flutter.plugin.common.StandardMethodCodec
12+
import java.nio.ByteBuffer
13+
import org.junit.Test
14+
import org.junit.runner.RunWith
15+
import kotlin.test.assertEquals
16+
import kotlin.test.assertNull
17+
18+
/** Real Android Uri/Intent and registered channel; only browser launch is replaced. */
19+
@RunWith(AndroidJUnit4::class)
20+
class BrowserAuthPluginTest {
21+
@Test fun closeRetryCallbackAndLateResume() {
22+
InstrumentationRegistry.getInstrumentation().runOnMainSync { runJourney() }
23+
}
24+
25+
private fun runJourney() {
26+
val messenger = Messenger()
27+
var launches = 0
28+
val plugin = BrowserAuthPlugin(Activity(), messenger) { launches++ }
29+
val first = messenger.start("first")
30+
plugin.onResume() // Initial resume is not a close.
31+
assertEquals(0, first.replies)
32+
plugin.onPause()
33+
plugin.onResume()
34+
assertEquals("cancelled", first.error)
35+
assertEquals(1, first.replies)
36+
37+
val second = messenger.start("second")
38+
plugin.onPause()
39+
plugin.onNewIntent(Intent(Intent.ACTION_VIEW, Uri.parse(
40+
"xyz.block.buzz.mobile:/auth/callback?state=first&code=old",
41+
)))
42+
assertEquals(0, second.replies)
43+
val callback = "xyz.block.buzz.mobile:/auth/callback?state=second&code=code"
44+
plugin.onNewIntent(Intent(Intent.ACTION_VIEW, Uri.parse(callback)))
45+
plugin.onResume()
46+
assertEquals(callback, second.value)
47+
assertNull(second.error)
48+
assertEquals(1, second.replies)
49+
assertEquals(2, launches)
50+
51+
val third = messenger.start("third")
52+
messenger.call("cancel", null)
53+
plugin.onPause()
54+
plugin.onResume()
55+
assertEquals("cancelled", third.error)
56+
assertEquals(1, third.replies)
57+
plugin.dispose()
58+
assertNull(messenger.handler)
59+
}
60+
61+
private class Reply {
62+
var replies = 0
63+
var value: Any? = null
64+
var error: String? = null
65+
}
66+
67+
private class Messenger : BinaryMessenger {
68+
var handler: BinaryMessenger.BinaryMessageHandler? = null
69+
fun start(state: String) = call("start", mapOf(
70+
"url" to "https://app.builderlab.xyz/api/goose/v1/auth/login?state=$state",
71+
))
72+
fun call(method: String, arguments: Any?): Reply {
73+
val reply = Reply()
74+
val message = StandardMethodCodec.INSTANCE.encodeMethodCall(MethodCall(method, arguments))
75+
message.flip()
76+
handler!!.onMessage(message) { response ->
77+
reply.replies++
78+
response!!.flip()
79+
try {
80+
reply.value = StandardMethodCodec.INSTANCE.decodeEnvelope(response)
81+
} catch (error: FlutterException) {
82+
reply.error = error.code
83+
}
84+
}
85+
return reply
86+
}
87+
override fun send(channel: String, message: ByteBuffer?) = Unit
88+
override fun send(channel: String, message: ByteBuffer?, callback: BinaryMessenger.BinaryReply?) = Unit
89+
override fun setMessageHandler(channel: String, handler: BinaryMessenger.BinaryMessageHandler?) {
90+
assertEquals("buzz/browser_auth", channel)
91+
this.handler = handler
92+
}
93+
}
94+
}
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
package xyz.block.buzz.mobile
2+
3+
import android.app.Activity
4+
import android.content.Intent
5+
import android.net.Uri
6+
import androidx.browser.customtabs.CustomTabsIntent
7+
import io.flutter.plugin.common.BinaryMessenger
8+
import io.flutter.plugin.common.MethodChannel
9+
10+
/** One browser session. Android delivers onNewIntent before onResume on return. */
11+
internal class BrowserAuthPlugin(
12+
activity: Activity,
13+
messenger: BinaryMessenger,
14+
private val launch: (Uri) -> Unit = { uri ->
15+
CustomTabsIntent.Builder().build().launchUrl(activity, uri)
16+
},
17+
) {
18+
private val channel = MethodChannel(messenger, "buzz/browser_auth")
19+
private var pending: MethodChannel.Result? = null
20+
private var state: String? = null
21+
private var departed = false
22+
23+
init {
24+
channel.setMethodCallHandler { call, result ->
25+
when (call.method) {
26+
"start" -> {
27+
val url = call.argument<String>("url")?.let(Uri::parse)
28+
if (url == null || url.scheme != "https" || url.host.isNullOrEmpty()) {
29+
result.error("unavailable", "Unable to open sign-in.", null)
30+
} else {
31+
cancel()
32+
pending = result
33+
state = url.getQueryParameter("state")
34+
departed = false
35+
try {
36+
launch(url)
37+
} catch (_: Exception) {
38+
finishError("unavailable")
39+
}
40+
}
41+
}
42+
"cancel" -> {
43+
cancel()
44+
result.success(null)
45+
}
46+
else -> result.notImplemented()
47+
}
48+
}
49+
}
50+
51+
fun onPause() {
52+
if (pending != null) departed = true
53+
}
54+
55+
fun onResume() {
56+
if (departed) cancel()
57+
}
58+
59+
fun onNewIntent(intent: Intent) {
60+
val uri = intent.data ?: return
61+
if (pending == null || uri.scheme != "xyz.block.buzz.mobile" ||
62+
uri.encodedSchemeSpecificPart.substringBefore('?') != "/auth/callback" ||
63+
uri.getQueryParameter("state") != state
64+
) return
65+
val result = pending
66+
clear()
67+
// Dart remains authoritative for canonical URI, state, expiry and PKCE.
68+
result?.success(uri.toString())
69+
}
70+
71+
private fun clear() {
72+
pending = null
73+
state = null
74+
departed = false
75+
}
76+
77+
private fun finishError(code: String) {
78+
val result = pending
79+
clear()
80+
result?.error(code, "Sign-in did not complete.", null)
81+
}
82+
83+
private fun cancel() = finishError("cancelled")
84+
85+
fun dispose() {
86+
cancel()
87+
channel.setMethodCallHandler(null)
88+
}
89+
}

‎mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/MainActivity.kt‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@ class MainActivity : FlutterFragmentActivity() {
134134
private var hapticsPlugin: HapticsPlugin? = null
135135
private var hostedHpkePlugin: HostedHpkePlugin? = null
136136
private var identityFilePlugin: IdentityFilePlugin? = null
137+
private var browserAuthPlugin: BrowserAuthPlugin? = null
137138

138139
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
139140
super.configureFlutterEngine(flutterEngine)
@@ -143,6 +144,7 @@ class MainActivity : FlutterFragmentActivity() {
143144
)
144145
hostedHpkePlugin = HostedHpkePlugin(flutterEngine.dartExecutor.binaryMessenger)
145146
identityFilePlugin = IdentityFilePlugin(this, flutterEngine.dartExecutor.binaryMessenger)
147+
browserAuthPlugin = BrowserAuthPlugin(this, flutterEngine.dartExecutor.binaryMessenger)
146148
hapticsPlugin = HapticsPlugin(this, flutterEngine.dartExecutor.binaryMessenger)
147149

148150
huddleMediaPlugin = HuddleMediaPlugin(
@@ -203,6 +205,22 @@ class MainActivity : FlutterFragmentActivity() {
203205
}
204206
}
205207

208+
override fun onNewIntent(intent: Intent) {
209+
// Resolve the browser session before resume can report cancellation.
210+
browserAuthPlugin?.onNewIntent(intent)
211+
super.onNewIntent(intent)
212+
}
213+
214+
override fun onPause() {
215+
browserAuthPlugin?.onPause()
216+
super.onPause()
217+
}
218+
219+
override fun onResume() {
220+
super.onResume()
221+
browserAuthPlugin?.onResume()
222+
}
223+
206224
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
207225
super.onActivityResult(requestCode, resultCode, data)
208226
identityFilePlugin?.onActivityResult(requestCode, resultCode, data)
@@ -218,6 +236,8 @@ class MainActivity : FlutterFragmentActivity() {
218236
}
219237

220238
override fun onDestroy() {
239+
browserAuthPlugin?.dispose()
240+
browserAuthPlugin = null
221241
identityFilePlugin?.dispose()
222242
identityFilePlugin = null
223243
hostedHpkePlugin?.dispose()

‎mobile/lib/features/pairing/add_community_page/add_community_connection.dart‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,14 @@ class _AddCommunityConnection extends HookWidget {
151151
),
152152
),
153153
actions: [
154+
if (!enteringLink && errorMessage != null)
155+
Semantics(
156+
liveRegion: true,
157+
child: Text(
158+
errorMessage!,
159+
style: TextStyle(color: context.colors.error),
160+
),
161+
),
154162
ExcludeSemantics(
155163
excluding: enteringLink,
156164
child: ExcludeFocus(

‎mobile/lib/features/pairing/pairing_provider.dart‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import 'package:nostr/nostr.dart' as nostr;
99

1010
import '../../shared/auth/auth.dart';
1111
import '../../shared/hosted/hosted_flow_provider.dart';
12+
import '../../shared/hosted/account_identity_store.dart';
1213
import '../../shared/hosted/hosted_environment.dart';
1314
import '../../shared/community/paired_community_landing.dart';
1415
import '../../shared/crypto/ecdh.dart';
@@ -789,7 +790,9 @@ class PairingNotifier extends Notifier<PairingState> {
789790
_cleanup();
790791
state = PairingState(
791792
status: PairingStatus.error,
792-
errorMessage: 'Failed to import credentials: $e',
793+
errorMessage: e == AccountIdentityFailure.mismatch
794+
? 'This device uses a different identity. Your saved identity has been kept.'
795+
: 'Could not import the identity. Try pairing again.',
793796
);
794797
}
795798
}

‎mobile/lib/onboarding_app_entry.dart‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ class OnboardingAppEntry extends HookConsumerWidget {
195195
? null
196196
: () => unawaited(flow.signInAccount()),
197197
accountStatus: status,
198-
builderlabBusy: busy,
198+
builderlabBusy: busy && !signingIn,
199199
signInPending: signingIn || busy,
200200
builderlabLabel: signingIn
201201
? 'Cancel sign-in'

‎mobile/lib/shared/hosted/bounded_http_response.dart‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@ import 'package:http/http.dart' as http;
66
/// leaving the shared client usable for sign-out and subsequent attempts.
77
Future<http.Response> boundedHttpResponse(
88
http.Client client,
9-
http.Request source,
10-
) async {
9+
http.Request source, {
10+
int maxBytes = 65536,
11+
}) async {
1112
final abort = Completer<void>();
1213
final request =
1314
http.AbortableRequest(
@@ -28,7 +29,7 @@ Future<http.Response> boundedHttpResponse(
2829
}
2930
final bytes = <int>[];
3031
while (await iterator.moveNext()) {
31-
if (bytes.length + iterator.current.length > 65536) {
32+
if (bytes.length + iterator.current.length > maxBytes) {
3233
throw const FormatException('Response too large');
3334
}
3435
bytes.addAll(iterator.current);

‎mobile/lib/shared/hosted/browser_auth.dart‎

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,6 @@ import 'package:flutter/foundation.dart';
99
import 'package:flutter/services.dart';
1010
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
1111

12-
import 'package:url_launcher/url_launcher.dart';
13-
1412
import '../storage/secure_storage.dart';
1513

1614
import 'hosted_environment.dart';
@@ -244,7 +242,8 @@ class BrowserAuth {
244242
Future<void> cancel() async {
245243
++_generation;
246244
_activeState = null;
247-
if (defaultTargetPlatform == TargetPlatform.iOS) {
245+
if (defaultTargetPlatform == TargetPlatform.iOS ||
246+
defaultTargetPlatform == TargetPlatform.android) {
248247
try {
249248
await _channel.invokeMethod<void>('cancel');
250249
} catch (_) {
@@ -270,18 +269,15 @@ class BrowserAuth {
270269
}
271270

272271
static Future<String?> _openPlatformBrowser(Uri uri) async {
273-
if (defaultTargetPlatform == TargetPlatform.iOS) {
272+
if (defaultTargetPlatform == TargetPlatform.iOS ||
273+
defaultTargetPlatform == TargetPlatform.android) {
274274
return _channel.invokeMethod<String>('start', {
275275
'url': uri.toString(),
276276
if (kDebugMode &&
277277
const bool.fromEnvironment('BUZZ_DEBUG_PRIVATE_LOGIN'))
278278
'ephemeral': 'true',
279279
});
280280
}
281-
if (defaultTargetPlatform == TargetPlatform.android &&
282-
await launchUrl(uri, mode: LaunchMode.inAppBrowserView)) {
283-
return null;
284-
}
285281
throw BrowserAuthFailure.unavailable;
286282
}
287283
}

‎mobile/lib/shared/hosted/hosted_join_policy.dart‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,13 @@ enum HostedInviteFailure {
2929
/// Reads only a bounded JSON document, never follows redirects or logs bodies.
3030
Future<Map<String, dynamic>> readJoinResponse(
3131
http.Client client,
32-
http.Request request,
33-
) async {
32+
http.Request request, {
33+
int maxBytes = 65536,
34+
}) async {
3435
final http.Response response;
3536
final Map<String, dynamic> data;
3637
try {
37-
response = await boundedHttpResponse(client, request);
38+
response = await boundedHttpResponse(client, request, maxBytes: maxBytes);
3839
if (response.statusCode == 429 ||
3940
(response.statusCode >= 500 && response.statusCode < 600)) {
4041
throw AccountFailure.unavailable;
@@ -81,7 +82,14 @@ Future<String?> freshJoinPolicyReceipt({
8182
request.headers['Content-Type'] = 'application/json';
8283
request.body = jsonEncode(body);
8384
}
84-
final data = await readJoinResponse(client, request);
85+
// The relay permits two 256 KiB Markdown documents. Allow their JSON
86+
// escaping (up to six bytes per input byte), plus the policy envelope.
87+
// Receipt and claim responses retain the ordinary 64 KiB bound.
88+
final data = await readJoinResponse(
89+
client,
90+
request,
91+
maxBytes: path == '/api/join-policy' ? 4 * 1024 * 1024 : 65536,
92+
);
8593
checkCurrent();
8694
return data;
8795
}

0 commit comments

Comments
 (0)