Skip to content

About

Crossly Connect SDK for android (partners: https://crossly.net/partners)

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Crossly Connect for Android

Connect a seller's marketplace account (Poshmark, Mercari, Depop, Vinted, …) to Crossly from your native Android app. The seller signs in inside a WebView whose marketplace traffic goes through that seller's own IP-pinned Crossly proxy, so the session is born on the same IP Crossly later uses it from. OAuth marketplaces open in a Custom Tab instead.

Headless: the SDK draws only the WebView. Every header, button, message and loading state is yours, through callbacks, view factories or Compose slots. There is no Crossly branding or copy in the SDK.

The React Native equivalent is @crossly/connect-react-native; both implement the same contract.

Partner access: this SDK needs a Crossly partner key (used server-side only). Request access at https://crossly.net/partners.

The rule: no proxy, no login

A marketplace session that is created on the phone's own IP and then used from a server IP is flagged and dies within hours. So this SDK never opens a marketplace login without the proxy:

  • the WebView is created only after the proxy override is applied and WebView has confirmed it;
  • if the device cannot proxy, the relay is missing, the override cannot be applied, the relay keeps refusing its token, or the token cannot be renewed, the login does not open (or is destroyed) and you get ConnectResult.Blocked(reason);
  • there is no fallback to a direct connection, and no option to enable one.

Offer another way to connect (e.g. your desktop extension) when CrosslyConnect.canProxy(context) says no.

Requirements

Android minSdk 24 (Android 7.0).
WebView An Android System WebView with PROXY_OVERRIDE and PROXY_OVERRIDE_REVERSE_BYPASS (androidx.webkit). Any current WebView from the Play Store has both; otherwise canProxy answers NO_PROXY_OVERRIDE. No WebView at all: UNSUPPORTED.
Build AGP 8.x, Kotlin 2.0+, Java 17. Compose wrapper: Compose BOM 2024.12+.
Permissions INTERNET (merged from the library manifest).

Install

Releases are tagged on GitHub (https://github.com/crossly-dev/crossly-connect-android/releases); Maven Central publication is planned. Until then build from source with ./gradlew publishToMavenLocal and add mavenLocal().

// settings.gradle.kts
dependencyResolutionManagement {
  repositories {
    google()
    mavenCentral()
  }
}

// app/build.gradle.kts
dependencies {
  implementation("net.crossly.connect:connect:0.1.0")
  // Jetpack Compose apps, additionally:
  implementation("net.crossly.connect:connect-compose:0.1.0")
}

Dependencies it brings: androidx.webkit, androidx.browser (Custom Tabs), androidx.activity, androidx.fragment, kotlinx-coroutines-android, kotlinx-serialization-json, okhttp 4. R8 rules ship in the AAR (consumer-rules.pro).

Building this repo: ./gradlew :connect:assembleRelease :connect:testDebugUnitTest with Gradle 8.9+ (run gradle wrapper once to create the wrapper; it is not checked in). Publishing: ./gradlew publishToMavenLocal or configure a repository in the publishing block.

The flow

your server                         Crossly                          your app
-----------                         -------                          --------
POST /v1/partner/sellers/:id/connect-sessions   (partner key)
  { platform: 'poshmark' }   ─────►  provisions the seller's proxy
                             ◄─────  ConnectSession JSON
send the ConnectSession to the app  ──────────────────────────────►  ConnectSession.fromJson(json)
                                                                      CrosslyConnectView / Activity / composable
                                                                      applies the relay, opens the login
                                     POST .../connect-sessions/:id/relay    ◄── renews the relay (upload token)
                                     POST .../connect-sessions/:id/cookies  ◄── signed-in session (upload token)
webhook connection.active  ◄──────  verifies the session server-side
  • Your partner key never goes to the app. The app only receives the ConnectSession; its uploadToken is single-use for /cookies (15 minutes) and reusable for /relay. Both calls send it as Authorization: Bearer <uploadToken>; the /cookies body carries the WebView's userAgent.
  • Create a new ConnectSession for every attempt. A session whose upload token was used or expired cannot be reused.
  • The final word is server-side: GET /v1/partner/connect-sessions/:id or the connection.active / connection.failed webhooks. ConnectResult.Connected means the session was handed over.
  • ConnectSession.fromJson accepts the session bare or still inside the /v1 envelope ({ "data": { … } }). For OAuth platforms login and relay are null and oauth.authorizeUrl is set.

Usage

Before offering the button at all:

val support = CrosslyConnect.canProxy(context)
if (!support.ok) showConnectFromComputer(support.reason) // NO_PROXY_OVERRIDE | UNSUPPORTED

Activity (simplest)

private val connect = registerForActivityResult(CrosslyConnectContract()) { result ->
  when (result) {
    is ConnectResult.Connected -> showToast("Connected")           // your copy, not the SDK's
    is ConnectResult.Blocked -> showConnectFromComputer(result.reason)
    is ConnectResult.OAuth -> pollSessionStatus(result.sessionId)
    null -> Unit                                                    // the seller backed out
  }
}

connect.launch(ConnectSession.fromJson(sessionJsonFromYourServer))

CrosslyConnectActivity as shipped draws only the WebView. Brand it by subclassing (and declaring the subclass in your manifest), then pass the class: CrosslyConnectContract(config, MyConnectActivity::class.java).

class MyConnectActivity : CrosslyConnectActivity() {
  private var done: Button? = null

  override fun onCreateLoadingView(parent: ViewGroup) = layoutInflater.inflate(R.layout.my_spinner, parent, false)

  override fun onCreateBlockedView(parent: ViewGroup, reason: BlockedReason) =
    layoutInflater.inflate(R.layout.my_connect_elsewhere, parent, false)

  override fun onCreateControlsView(parent: ViewGroup): View =
    layoutInflater.inflate(R.layout.my_footer, parent, false).also { v ->
      done = v.findViewById<Button>(R.id.signed_in).apply { setOnClickListener { confirmLoggedIn() } }
    }

  override fun onControlsStateChanged(state: CrosslyConnectControlsState) {
    done?.isEnabled = !state.uploading
  }

  override fun onConnectError(error: CrosslyConnectException, auto: Boolean) {
    if (!auto) showToast(if (error.retryable) R.string.not_signed_in_yet else R.string.start_over)
  }

  // Keep the blocked view on screen until the seller leaves (default: finish at once).
  override fun onConnectResult(result: ConnectResult) {
    if (result !is ConnectResult.Blocked) finishWith(result)
  }
}

OAuth in the Activity: the authorize URL opens in a Custom Tab. To get OAuthOutcome.COMPLETED (with the URL), route your redirect deep link to your subclass (launchMode="singleTop" + an intent-filter for the redirect); coming back without it reports DISMISSED.

View

val view = CrosslyConnectView(context)
container.addView(view)
view.start(session, object : CrosslyConnectListener {
  override fun onResult(result: ConnectResult) { /* once per session */ }
  override fun onError(error: CrosslyConnectException, auto: Boolean) { /* recoverable */ }
  override fun onPhaseChanged(phase: CrosslyConnectPhase, blockedReason: BlockedReason?) {
    // PREPARING -> your spinner, LOGIN -> your controls, BLOCKED -> your fallback, DONE -> your success state
  }
  override fun onControlsStateChanged(state: CrosslyConnectControlsState) { /* currentUrl, loggedInDetected, uploading, pageLoading */ }
}, CrosslyConnectConfig(clearCookiesFirst = true))

signedInButton.setOnClickListener { view.confirmLoggedIn() }

One view = one session. Forward onPause()/onResume(), use canGoBack()/goBack() for the back button, and call dispose() when you are done (detaching the view from its window also disposes it). OAuth sessions report OAuth(OPENED) from the view.

Fragment

supportFragmentManager.commit { replace(R.id.connect_container, CrosslyConnectFragment.newInstance(session)) }
supportFragmentManager.setFragmentResultListener(CrosslyConnectFragment.REQUEST_KEY, this) { _, bundle ->
  val result = CrosslyConnectFragment.resultOf(bundle)
}

Callbacks go to fragment.listener, else to a parent fragment or activity implementing CrosslyConnectListener.

Jetpack Compose

CrosslyConnect(
  session = session,
  onResult = { result -> viewModel.onConnectResult(result) },
  onError = { error, auto -> if (!auto) viewModel.onConnectError(error) },
  loading = { MySpinner() },
  blocked = { reason -> MyConnectFromComputer(reason) },
  controls = { state, confirmLoggedIn ->
    MyFooter(onDone = confirmLoggedIn, busy = state.uploading)
  },
  complete = { MyDoneState() },
)

A new session.id starts over; leaving the composition disposes the attempt.

Options (CrosslyConnectConfig)

Option Default
clearCookiesFirst false Sign the WebView out of everything first — use for a new account so the previous account's session is not reused. Clears your app's whole WebView cookie store.
autoDetect true Upload as soon as a page matches login.loggedInMatchers.
settleMs 1500 Delay between detection and reading cookies.
userAgent WebView's own WebView user agent override (also what is reported to Crossly).
apiBaseUrl https://crossly.net/api Must be https.

login.loggedInMatchers are regular-expression sources tested case-insensitively against each page URL; an entry starting with ! must not match (e.g. ["!login|checkpoint", "facebook\\.com"]); an empty list turns auto-detection off (the seller confirms with your control). A matcher that Java's regex engine cannot compile is skipped. CrosslyConnect.isLoggedInUrl(matchers, url) is exported for your own checks.

Results and errors

  • ConnectResult.Connected(sessionId, platform, accountId, status, cookieCount)
  • ConnectResult.Blocked(sessionId, platform, reason): NO_PROXY_OVERRIDE, UNSUPPORTED, RELAY_UNAVAILABLE, PROXY_APPLY_FAILED, RELAY_RENEWAL_FAILED, WEBVIEW_CRASHED (Android only: the renderer died; the app does not).
  • ConnectResult.OAuth(sessionId, platform, outcome, url?): COMPLETED / DISMISSED / OPENED.
  • result.toJson() is the TypeScript ConnectResult ({ "type": "connected", … }) for your server or logs.

CrosslyConnectException carries code (NO_COOKIES, UPLOAD_FAILED, RELAY_RENEWAL_FAILED, OAUTH_FAILED, NETWORK), status (HTTP), serverCode (from { error: { code } }) and retryable (network, 5xx, 429, no cookies yet). A non-retryable upload failure (used or expired upload token) needs a new ConnectSession.

Behavior worth knowing

  • The proxy override is process-wide: every WebView in your app, while the login is open. Only the relay's marketplace hosts (and their subdomains) use it (reverse bypass); everything else stays direct. It is cleared when the attempt ends (connected, blocked, disposed), after the WebView is destroyed. Do not show another WebView to the same marketplace meanwhile. The SDK's own API calls use OkHttp, never the override.
  • In-app loopback forwarder. Android WebView cannot authenticate to an HTTPS proxy (it never calls onReceivedHttpAuthRequest for one and fails with net::ERR_PROXY_AUTH_UNSUPPORTED), and the Crossly relay is one. So the override points at http://127.0.0.1:<random port>, a forwarder the SDK runs inside your app for the length of the login (LoopbackRelayForwarder, own thread pool). It accepts only CONNECT <marketplace host>:443 for the login's own hosts (exact or subdomain; 403 otherwise, 405 for plain http, 503 beyond 32 open tunnels), opens TLS to the relay (system trust store, hostname verified, pinned to the relay's CA roots), sends the relay token preemptively as Proxy-Authorization: Basic, and pipes once the relay answers 200 (anything else, or a TLS failure: 502). It never connects anywhere but the relay and closes with all its tunnels when the attempt ends.
  • Loopback credential. Every CONNECT to the forwarder must carry its own random per-login credential (SecureRandom; 407 otherwise), so other apps on the phone that find the port cannot use it. The WebView answers the forwarder's 407 (onReceivedHttpAuthRequest) only when the challenge comes from 127.0.0.1 with the forwarder's realm (which names its port); every other challenge is cancelled. The relay token never reaches the WebView. If the relay refuses the token 3 times in a row (revoked or expired) the login is blocked (PROXY_APPLY_FAILED).
  • Relay pinning. On top of the system trust store and hostname verification, the relay's certificate must chain (by signature, not just by presence) to one of the pinned CA keys in RelayPins (ISRG Root X1, X2 and Root YE: the relay's certificate is Let's Encrypt via Fly). Rotation steps are in that file.
  • Cookies leave the device's WebView store. After the upload succeeds, and whenever the attempt ends (blocked, disposed, cancelled), the session's cookies (cookieDomains + the login host) are deleted from CookieManager and the store is flushed, so the marketplace session never stays in your app's WebView profile.
  • Renewal: the relay token is renewed through /relay 3 minutes before it expires (and before the login opens, if it is about to). The same relay and hosts only swap the forwarder's token (new tunnels use it); a different relay gets a new forwarder and override. A failed renewal destroys the WebView: Blocked(RELAY_RENEWAL_FAILED).
  • Navigation: only http(s) loads. intent:, market:, app links and every other scheme are refused, never launched, so the login cannot escape to an unproxied app or browser. New-window links open in the same WebView; file and content access are off.
  • Secrets: ConnectSession, ConnectSessionRelay and UploadCookie redact the upload token, relay password and cookie values in toString(). The upload and relay tokens live in process memory only: CrosslyConnectActivity and CrosslyConnectFragment get an opaque key in their Intent / arguments (never the session), nothing goes to SharedPreferences, saved state or disk, and after process death the screen ends without a result (start a new ConnectSession). ConnectSession.toJson() contains the tokens: never log or persist it. The SDK logs nothing.

Cookies and HttpOnly

Cookies are read from android.webkit.CookieManager (the store every WebView in your app shares) for each login.cookieDomains entry plus the login page's host (when it is inside the cookie domains), then filtered to the cookie domains.

  • HttpOnly cookies are included. CookieManager is the network stack's jar, not document.cookie, so session cookies flagged HttpOnly are read like any other.
  • Attributes depend on the WebView. With GET_COOKIE_INFO (androidx.webkit CookieManagerCompat.getCookieInfo, recent WebView builds) each cookie comes with Domain, Path, Expires/Max-Age, Secure, HttpOnly and SameSite. On older WebViews only getCookie(url) exists: names and values only, so each cookie is uploaded host-only on the host it was read from, path /, no expiry (a session cookie), secure: true, httpOnly omitted, sameSite: Lax. Crossly replays such cookies fine for the marketplace's own hosts; a domain cookie read from the bare domain may appear twice (bare domain and login host) — harmless.
  • Only cookies that would be sent to the URL read are visible: a cookie scoped to a sub-path (Path=/api), or set on a host that is neither a cookie domain nor the login host, is not seen. Session config (cookieDomains) must name every host whose cookies matter.
  • Partitioned (CHIPS) third-party cookies may not be returned.
  • clearCookiesFirst removes all cookies of all WebViews in your app; there is no per-domain delete in CookieManager.

Device checks

These cannot be unit-tested and must be verified on real devices before relying on them:

  • The override to http://127.0.0.1:<port> takes effect (no cleartext-policy objection on the loopback hop), the WebView answers the forwarder's 407 (host 127.0.0.1, the forwarder's realm) and reuses the credential on later tunnels, the forwarder's pinned TLS to the live relay verifies, and a full marketplace login completes through it.
  • After the upload the marketplace cookies are gone from CookieManager (including on a WebView without GET_COOKIE_INFO).
  • setProxyOverride with reverse bypass routes depop.com and www.depop.com to the forwarder, and nothing else (no 403s in the forwarder for third-party hosts, no foreign hosts in the relay's logs).
  • The override's completion callback fires before the first request; clearProxyOverride after destroy() leaves no request going direct while the WebView dies.
  • CookieManagerCompat.getCookieInfo returns the session cookies with attributes (HttpOnly included) for every cookie domain; the getCookie fallback on a WebView without GET_COOKIE_INFO.
  • doUpdateVisitedHistory / onPageStarted see the post-login URL of each supported marketplace (single-page apps included), so loggedInMatchers fire.
  • Renewal during a long login (> 12 minutes) swaps the forwarder's token without breaking the page.
  • OAuth: the Custom Tab opens; with a redirect routed to the Activity subclass, COMPLETED arrives; without it, DISMISSED on return.
  • Renderer crash (chrome://crash in a debug build) yields Blocked(WEBVIEW_CRASHED), not an app crash (API 26+).

License

MIT

About

Crossly Connect SDK for android (partners: https://crossly.net/partners)

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages