upcode
Open source · Dart
Razvan Lungupdated 29 Novembersecure_flow 0.4.0pure Dart, no dependenciesDart 3.8+Apache 2.0

secure_flow: browser round trips for Dart CLIs and desktop apps

OAuth sign-in, reCAPTCHA and code entry on macOS, Windows and Linux, reCAPTCHA on the web, and OAuth on Android and iOS with a presenter you add.

An OAuth sign-in with secure_flow in seven steps between your app, the browser, the provider and the loopback server. Your appCLI or desktop Browsersystem default ProviderGoogle, GitHub… Loopback server127.0.0.1:53817 path ✓ Host ✓ state ✓ first ✓
Seven steps. The loopback server never sees the PKCE verifier.

Some steps in a command line tool or a desktop app need a web page. Signing in with Google or GitHub needs a browser and a redirect back to your program. A reCAPTCHA check needs a page with Google's widget on it. A code from an email needs somewhere to type it. secure_flow is a pure-Dart package that runs these round trips. It shows the person a page or asks at the terminal, takes the answer, and returns it to your code as a typed value. The part that is easy to get wrong is the local server that receives the answer: it has to accept the one right request, refuse everything else, and close when it is done.

I wrote it for the pure-Dart Firebase SDK, whose Auth client needs all three, and published it on its own because nothing in it depends on Firebase.

The shortest example

dart pub add secure_flow
import 'package:secure_flow/secure_flow.dart';

Future<void> main() async {
  final String code =
      await const CodeEntryFlow(prompt: 'The code from the email').run();
  print('Got a code of ${code.length} characters.');
}

When stdin and stderr are terminals, this prompts in the terminal. When they are not, as in a desktop app started from the dock, it opens a small form in the system browser and reads the code from the form's answer. On a machine with neither, such as a headless server, it throws SecureFlowNoPresenter. The next section explains how it chooses.

Flows and presenters

A flow is one round trip. It knows what to show, which request counts as the answer, and how to turn that answer into a Dart value. The main three are OAuthFlow, RecaptchaFlow and CodeEntryFlow; 0.4.0 adds two for Facebook and Apple (below). You can write your own by extending SecureFlow<T>.

A presenter is a way to show a flow to the person. Each has a kind. On a desktop the two you meet are systemBrowser, which opens the URL with open, xdg-open or rundll32, and console. For code entry the console reads a line. For OAuth and reCAPTCHA it prints the URL, and the person opens it in a browser on the same machine. The others cover mobile and the web: providerApp (a provider's native SDK that signs in itself and returns tokens), inAppBrowser (a browser tab the app cannot read, such as an Android Custom Tab), embeddedWebView (a web view the app can read and script) and inPage (the page a web app is running in).

Each flow lists the kinds it accepts, best first. flow.run() without a presenter takes the best one the machine offers. run(presenter: ...) uses the presenter you pass if the flow accepts it and throws SecureFlowRefused if not. A flow never falls back to a different presenter on its own. On a desktop with a terminal, code entry therefore picks the console and OAuth picks the browser.

Each flow ranks the presenter kinds it accepts. OAuth never takes an embedded web view. OAuthFlow→ OAuthResult RecaptchaFlow→ token CodeEntryFlow→ code never
Each flow ranks the kinds it accepts. OAuth refuses the embedded web view kind.
FlowReturnsKinds it accepts, best first
OAuthFlowOAuthResultproviderApp, systemBrowser, inAppBrowser, console
RecaptchaFlow, .enterprisethe tokeninPage, embeddedWebView, systemBrowser, console
CodeEntryFlowthe code, trimmedconsole, systemBrowser
FacebookDeviceFlowa Facebook user access tokenconsole, or a presenter that shows a code (no browser, no server)
AppleWebFlowApple's ID token, and its code when Apple sends onesystemBrowser, console

OAuthFlow refuses every presenter that declares the embedded web view kind, because the hosting app could read what the person types into the provider's page. RFC 8252, the OAuth guidance for native apps, says the same.

SecureEnvironment.current() says what the machine offers. Outside an SSH session it includes the system browser on macOS and Windows, and on Linux when DISPLAY or WAYLAND_DISPLAY is set. It includes the console when stdin and stderr are terminals. On the web it offers only the in-page reCAPTCHA presenter, because OAuth and code entry need dart:io. On Android and iOS it offers nothing, so run throws SecureFlowNoPresenter until you add a presenter.

LaptopmacOS, Windows, or Linux with a displaysystemBrowser, console in a terminal
Over SSHno display; stdin and stderr are terminalsconsole
Web appcompiled with dart2js or dart2wasminPage, reCAPTCHA only

In a Flutter app, CallbackPresenter wraps whatever opens a URL, such as url_launcher's launchUrl. Without kind: it declares systemBrowser, so never wrap a web view without saying so. Only OAuth accepts the inAppBrowser kind; for code entry or reCAPTCHA, declare systemBrowser. Throw when the URL cannot be opened, or the flow waits until its timeout:

final SecureEnvironment environment = SecureEnvironment.current(
  registered: <SecurePresenter>[
    CallbackPresenter((Uri url) async {
      if (!await launchUrl(url)) throw StateError('Could not open $url');
    }, kind: SecurePresenterKind.inAppBrowser),
  ],
);
await flow.run(environment: environment);

How it differs from googleapis_auth

Google's googleapis_auth has OAuth flows with one callback to show the URL. The server flow in googleapis_auth binds localhost and takes the first HTTP request that reaches its port (server.first, line 63). If another local program sends a request first, the sign-in ends with an error. The secure_flow server waits for the one request that passes all of its checks.

Signing in with OAuth

secure_flow is for code that already has an OAuth client, or for a wrapper such as the Firebase SDK below. OAuthFlow carries the request to the provider and the result back. Your client keeps its own parts: you make the state (an unpredictable random value) and you exchange the code for tokens. The flow checks that the redirect carries your state. Since 0.4.0 it can also do PKCE for you: pass pkce: true.

There are two ways to build one. OAuthFlow.discovery takes an OpenID Connect issuer, such as https://accounts.google.com, and reads the provider's endpoints from its discovery document before the loopback server starts. OAuthFlow.authorization takes a function that builds the authorization URL, for providers without discovery, such as GitHub. In both, you build the query string yourself.

The result is a sealed OAuthResult, which is an OAuthRedirect with the redirect's query parameters, or OAuthTokens when a provider app signed in itself. flow.map(...) returns a new flow that runs your function on the result. With it, the redirect reaches the flow's loopback server (a short-lived HTTP server on 127.0.0.1, described below), your function exchanges the code, and only then does the browser tab get its page, which can say whether the exchange worked.

// clientId, state, exchangeCode and Tokens are
// your OAuth client's.
final OAuthFlow flow = OAuthFlow.discovery(
  providerId: 'google.com',
  issuer: Uri.parse('https://accounts.google.com'),
  authorizationUrl: (OidcConfiguration config, String redirectUri) =>
      config.authorizationEndpoint.replace(queryParameters: <String, String>{
        'client_id': clientId,
        'redirect_uri': redirectUri, // http://127.0.0.1:<port>
        'response_type': 'code',
        'scope': 'openid email',
        'state': state,
      }),
  state: state,
  pkce: true, // adds code_challenge and code_challenge_method=S256
);

final Tokens tokens = await flow.map((OAuthResult result) async {
  switch (result) {
    case OAuthRedirect(
        :final Map<String, String> parameters,
        :final OidcConfiguration? configuration,
        :final String? codeVerifier,
      ):
      final String? code = parameters['code'];
      if (code == null) throw StateError('Sign-in failed: ${parameters['error']}');
      return exchangeCode(configuration!.tokenEndpoint, code, codeVerifier!);
    case OAuthTokens():
      throw StateError('No provider app is registered here.');
  }
}).run();

The redirect URI is http://127.0.0.1:<port> on the path /, with a free port picked at run time. For Google, create an OAuth client of type Desktop app, which accepts any loopback port. For a GitHub OAuth App, register the callback http://127.0.0.1. An error thrown inside map, such as the failed sign-in above, ends the run. The browser gets a failure page and run rethrows the error. The run's timeout (five minutes by default) and its cancel: future also bound map: when either comes first, run throws and the late result is dropped, but the exchange itself keeps going, so give it its own shorter HTTP timeout.

With pkce: true, the flow makes the verifier when you build it (32 secure random bytes, base64url, 43 characters), so build a new flow for each sign-in. It adds the S256 challenge to the URL you build and hands the verifier back on OAuthRedirect.codeVerifier for your code exchange. The verifier never goes into a URL, a page, an error or toString; the console shows only the URL, with the challenge. If your URL already sets code_challenge or code_challenge_method, run throws an ArgumentError before anything is shown. With discovery, a provider whose document lists code_challenge_methods_supported without S256 fails before the browser opens; a document without the field is accepted, because many providers leave it out. A provider app never sees the challenge, so its result has no verifier. Pkce.generate() is there for code that builds its own request. The code exchange stays yours: providers differ in it, and some want a client secret too. secure_flow still has no dependencies; it carries its own SHA-256, checked against the FIPS 180-4 vectors.

OidcDiscovery fetches the discovery document and checks it: the issuer and both endpoints must be https, and the document's issuer must equal the one you asked for. It caches the document as long as the response's Cache-Control or Expires allows (Google's says one hour), then revalidates it with one conditional request. If that fails, the run fails; a stale copy is never used. The cache is in memory by default. To keep it between runs of a command line tool, pass OidcDiscovery(cache: FileOidcConfigurationCache(path)) with a path only your user can write.

With firebase_auth_providers_dart, the flow, PKCE and the exchange sit behind one call:

final UserCredential result = await auth.signInWithOAuthLoopback(
  OAuthLoopbackProvider.google(clientId: clientId, clientSecret: clientSecret),
);

Facebook and Apple on a desktop

Neither takes a plain redirect to 127.0.0.1, so 0.4.0 has a flow for each.

FacebookDeviceFlow uses Facebook Login for Devices. The app shows a short code, the person opens Facebook's device page on any device, signs in and types it, and the flow polls Facebook until the sign-in is granted, the code expires, or the run is cancelled. No browser opens on this machine and no server listens, so it also works over SSH. It never polls faster than Facebook allows. Its only credential is the app's client token (<app id>|<client token>), which ships inside apps and is not a secret. No parameter takes the app secret, but an app access token (<app id>|<app secret>) has the same shape and the flow cannot tell them apart, so never put the secret in an app. Its default timeout is ten minutes, longer than Facebook's code lifetime.

AppleWebFlow brings Sign in with Apple to Windows, Linux and the command line. Apple sends its answer only to an https address registered for the app, never to 127.0.0.1, so the app supplies a relay: a small server on its own domain that receives Apple's form and passes it to the loopback server. The repository has a reference relay in plain Dart. The answer always comes as a form post, so no token is ever in a URL. The loopback server takes it only on a random path made for that run, only with that run's secret, and only from the relay's origin (or with no Origin header). The flow checks the ID token's issuer, audience, expiry and nonce, but not its signature: the reference relay verifies it against Apple's keys, and your backend or Firebase checks it again.

Upgrading from 0.3.0. Two changes can break a build. SecureFlowPurpose has a new case, deviceCode, so a switch over it without a default must handle it. A class that implements SecureFlow instead of extending it must add presentDirectlyUntil. To move an OAuth client to the built-in PKCE, drop your own code_challenge parameters, pass pkce: true, and exchange the code with codeVerifier.

What the loopback server checks

The system browser, an in-app browser, and the console for OAuth and reCAPTCHA all run the flow through a loopback server. It is a short-lived HTTP server on this machine's loopback interface, which a browser on the same machine can reach and other machines cannot. For code entry and reCAPTCHA it serves one page at a random path and takes the answer there; for OAuth it waits for the provider's redirect. Try sending it requests:

Loopback serverlistening on 127.0.0.1:53817code entry form at /k3Fq…

Send it a request

Its checks, in order

1No answer taken yet
2Path and method are the flow's: POST /k3Fq…
3Host is exactly 127.0.0.1:53817
4Origin is the page's own, when sent
5Body is at most 64 KiB
6State matches (constant-time compare)
$ waiting for one answer…
A simulation of the server's checks for a code entry form. Nothing on this page talks to a network.

What it does not protect against

reCAPTCHA, on desktop and on the web

On desktop and in the terminal, RecaptchaFlow(siteKey: ...) serves a page on localhost with Google's v2 widget and takes the token the page posts back. It uses localhost because reCAPTCHA keys are registered for domain names, so add localhost to the key's domains; keys do not allow it by default. RecaptchaFlow.enterprise(siteKey:, action:) does the same for a reCAPTCHA Enterprise action.

On the web there is no loopback server. InPageRecaptchaPresenter runs the Enterprise check in your app's page, or renders the v2 widget in the element containerId names:

final String token = await RecaptchaFlow(
  siteKey: siteKey,
  size: RecaptchaSize.compact,
).run(presenter: InPageRecaptchaPresenter(containerId: 'recaptcha'));

Without a container, the widget is invisible and size is ignored.

Errors

run throws SecureFlowException subtypes (SecureFlowTimeout, SecureFlowCancelled, SecureFlowRefused, SecureFlowNoPresenter), OidcDiscoveryException when the discovery document cannot be fetched or fails its checks, and, for reCAPTCHA, RecaptchaFailure. A fixed port: that is already in use gives a SocketException, and a loopback presenter on the web an UnsupportedError. Constructors throw ArgumentError for bad arguments, and errors from a presenter or from your map function are rethrown as they are.

How it was checked

Try it

dart pub add secure_flow

Package: pub.dev/packages/secure_flow. Source and issues: github.com/long1eu/firebase_dart_sdk.