secure_flow 0.4.0
secure_flow: ^0.4.0 copied to clipboard
Pure-Dart browser round trips for desktop apps and command line tools: OAuth redirects, reCAPTCHA (v2 and Enterprise) and code entry answered over a hardened one-shot loopback server, reCAPTCHA in the [...]
secure_flow #
Browser round trips for Dart desktop apps and command line tools: a flow opens a URL for the person (or asks at the terminal, or hands over to the provider's app), takes the answer, and returns a typed result.
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('${code.length} characters');
}
Pure Dart, no dependencies. The library compiles on the web: there the loopback server and its
presenters throw an UnsupportedError, and a RecaptchaFlow runs in the app's own page
(InPageRecaptchaPresenter). It is used by firebase_auth_providers_dart for its OAuth sign-in, its Facebook device
sign-in, its Sign in with Apple on desktops and its reCAPTCHA checks.
Flows choose their presenters #
A flow (SecureFlow<T>) is self-contained: what to open or serve, which request answers it
(method, path, query or form), the host the browser uses, how the answer becomes a T, and the
presenter kinds it accepts, best first. flow.run() starts it:
- without a presenter, the flow takes the best one the
SecureEnvironmentoffers; - with
presenter:, the flow uses it if it accepts it, and throwsSecureFlowRefusedotherwise. It never switches to another presenter on its own.
run is a method of the flow, not a function of the presenter, because the flow is what knows how
to drive each kind: a browser over the loopback server, a terminal prompt, or a provider's SDK.
| Flow | Result | Presenter kinds, best first | Loopback host and answer |
|---|---|---|---|
OAuthFlow.authorization, and OAuthFlow.discovery (endpoints from the issuer's discovery document) |
OAuthResult: OAuthRedirect (code or error, the redirect URI, and the discovery document) or OAuthTokens (from a provider app) |
providerApp (if it can sign in to this provider), systemBrowser, inAppBrowser, console; never embeddedWebView or other | exactly 127.0.0.1; GET on the redirect path, query |
RecaptchaFlow (v2 widget) and RecaptchaFlow.enterprise (an Enterprise token for an action) |
the token | inPage (a RecaptchaPresenter: no server), embeddedWebView, systemBrowser, console |
localhost (127.0.0.1 and ::1 bound); POST of the page's form, random path |
CodeEntryFlow |
the code, trimmed | console (a prompt from the injected input: no browser, no server), systemBrowser | exactly 127.0.0.1; POST of the page's form, random path |
FacebookDeviceFlow (Facebook Login for Devices) |
FacebookDeviceToken: a user access token |
console, other (a DeviceCodePresenter: no browser, no server) |
none: the flow polls Facebook |
AppleWebFlow (Sign in with Apple through a relay the app supplies) |
AppleWebResult: Apple's ID token, the authorization code, the first-time name and email |
systemBrowser, console | exactly 127.0.0.1; POST of the relay's form (its Origin only), random path |
A presenter is a way to show a flow and collect its answer. It has a SecurePresenterKind
(providerApp, systemBrowser, inAppBrowser, embeddedWebView, console, inPage, other), and what
it can do is told by the interfaces it implements: LoopbackPresenter (shows a URL), PromptPresenter (reads a
line), ProviderAppPresenter (returns OAuth results itself), RecaptchaPresenter (returns a reCAPTCHA token
itself), DeviceCodePresenter (shows a code to type on another device). Flows rank kinds and check interfaces;
they never look at a presenter's class, and presenters never look at a flow's.
| Presenter | Kind | In the environment when |
|---|---|---|
SystemBrowserPresenter() |
systemBrowser: open, xdg-open or rundll32 (openInSystemBrowser) |
macOS or Windows, or Linux with DISPLAY or WAYLAND_DISPLAY, not over SSH |
ConsolePresenter(sink:, input:) |
console: writes only the URL to sink (stderr), which carries the state and the PKCE challenge (see What it does not protect against); prompts read a line from input (stdin); a device code is one line with the page and the code |
stdin and stderr are terminals |
CallbackPresenter(show, kind:) |
the kind you declare (systemBrowser by default; not providerApp or inPage) | you register it |
DeviceCodeCallbackPresenter(show) |
other: show gets the DeviceCode (the user code, the page, the lifetime) |
you register it |
Pass the true kind:. CallbackPresenter claims systemBrowser unless told otherwise. If show opens an
embedded web view or an in-app browser and you leave kind: out, the presenter claims a system browser, which is
the RFC 8252 bypass described in What it does not protect against. Pass
SecurePresenterKind.embeddedWebView or SecurePresenterKind.inAppBrowser as it is.
| InPageRecaptchaPresenter(containerId:, onVerified:, onExpired:, onError:) | inPage: the reCAPTCHA in the page of a web app | on the web (SecureEnvironment.current()) |
| a ProviderAppPresenter of yours | providerApp | you register it |
final SecureEnvironment environment = SecureEnvironment.current(
registered: <SecurePresenter>[myFacebookSdkPresenter],
);
final OAuthResult result = await OAuthFlow.authorization(
providerId: 'facebook.com',
authorizationUrl: (String redirectUri) => buildAuthorizationUrl(redirectUri),
state: state,
rawNonce: rawNonce,
hashedNonce: hashedNonce,
pkce: true,
).run(environment: environment);
switch (result) {
case OAuthRedirect(:final Map<String, String> parameters, :final String? codeVerifier):
// Exchange parameters['code'], sending codeVerifier as code_verifier.
break;
case OAuthTokens(:final String? idToken):
// The SDK's tokens: no exchange.
break;
}
OAuthFlow carries the request out and the result back. The code exchange, the nonce check and the
state value are the caller's; the flow checks the state and passes the scopes and both nonces to a
provider app. PKCE is built in: see PKCE. Its redirect URI is http://127.0.0.1:<port> for the path / (no
trailing /, the form GitHub OAuth Apps with the callback http://127.0.0.1 and Google Desktop
clients accept). flow.map(...) runs work such as the code exchange while the browser waits, so
that the page it gets says whether the sign-in worked.
PKCE #
With pkce: true, OAuthFlow.authorization and OAuthFlow.discovery add PKCE (RFC 7636) with the
S256 method to every run:
- The flow makes a verifier of 32 bytes from a cryptographically secure source (base64url without
padding, 43 characters) and adds
code_challengeandcode_challenge_method=S256to the URL yourauthorizationUrlbuilds. Don't set those two yourself; the run fails with anArgumentErrorbefore anything is shown if you do. - The verifier comes back on
OAuthRedirect.codeVerifier, for your code exchange (code_verifier). It never goes into the URL, a page, an error ortoString; aConsolePresenterprints only the challenge. - With
OAuthFlow.discovery, a document whosecode_challenge_methods_supportedlacksS256fails the run (OidcDiscoveryException, reasondocument) before the browser opens. A document without the field is accepted, because many providers leave it out. - A provider app (
ProviderAppPresenter) runs its own protocol and never sees the challenge, so itsOAuthRedirecthas no verifier (codeVerifieris null). - The code exchange stays yours: providers differ in it, and some want a client secret as well.
pkce is off by default. An app that builds its own request can use Pkce.generate() (a verifier
and its challenge) or Pkce.challengeOf(verifier).
final OAuthResult result = await OAuthFlow.authorization(
providerId: 'oidc.example',
authorizationUrl: (String redirectUri) => authorizationEndpoint.replace(
queryParameters: <String, String>{
'client_id': clientId,
'redirect_uri': redirectUri,
'response_type': 'code',
'scope': 'openid email',
'state': state,
},
),
state: state,
pkce: true,
).run();
final OAuthRedirect redirect = result as OAuthRedirect;
// POST the token endpoint: grant_type=authorization_code, code=redirect.parameters['code'],
// redirect_uri=redirect.redirectUri, code_verifier=redirect.codeVerifier.
OpenID Connect discovery #
OAuthFlow.discovery takes the issuer of an OpenID Connect provider instead of its endpoints. run
fetches <issuer>/.well-known/openid-configuration before the loopback server starts, within the
run's timeout and cancel, and hands the checked document to authorizationUrl; the caller still
builds the query. The redirect carries the document, so map can exchange the code at its token
endpoint. A provider app needs no document, and none is fetched.
final OAuthFlow flow = OAuthFlow.discovery(
providerId: 'oidc.example',
issuer: Uri.parse('https://accounts.google.com'),
discovery: OidcDiscovery(cache: FileOidcConfigurationCache(cachePath)),
authorizationUrl: (OidcConfiguration configuration, String redirectUri) =>
configuration.authorizationEndpoint.replace(
queryParameters: <String, String>{
'client_id': clientId,
'redirect_uri': redirectUri,
'response_type': 'code',
'scope': 'openid email',
'state': state,
},
),
state: state,
pkce: true,
);
final String idToken = await flow.map((OAuthResult result) async {
final OAuthRedirect redirect = result as OAuthRedirect;
return exchangeCode(redirect.configuration!.tokenEndpoint, redirect);
}).run();
OidcDiscovery (also usable on its own: fetch(issuer)) checks and caches the document:
- The issuer must be an
httpsURL without user info, query or fragment. The document'sissuermust equal it exactly (OpenID Connect Discovery 1.0, section 4.3; a trailing/counts), and itsauthorization_endpointandtoken_endpointmust behttpsURLs. Other URLs of the document (OidcConfiguration.json) are not checked. - One GET with
dart:io'sHttpClient(certificates checked, redirects not followed), at most 64 KiB of body, within 30 seconds (timeout, or the run's deadline when it is sooner). - Freshness:
Cache-Control: max-age, or elseExpiresminusDate, minusAge. Without either, withno-cache, or with a value that does not parse, the copy is stale at once;no-storeis not stored. Google's document (public, max-age=3600withExpiresandLast-Modified, noETag) is used for an hour, then revalidated. - A stale copy is revalidated with one conditional GET (
If-None-Matchfrom itsETag,If-Modified-Sincefrom itsLast-Modified). A 304 renews it; a 200 replaces it, after the same checks. When the revalidation fails (no connection, another status, a document that fails the checks),fetchthrows anOidcDiscoveryException: a stale copy is never used. - Caches, keyed by issuer:
MemoryOidcConfigurationCache(the default;OidcDiscovery.standard, whichOAuthFlow.discoveryuses without adiscovery, keeps one for the program) andFileOidcConfigurationCache(path), one JSON file at a path the app chooses: the library never picks a place on disk. A corrupt file is a miss; a write goes to a temporary file that is renamed over it. A cached document is checked again every time it is used. - Whoever can write the cache chooses the endpoints, within those checks (an
httpsURL of any host). Keep the file in a directory only this user can write. - On the web there is no default HTTP layer (pass
httpGet, anOidcHttpGet), andFileOidcConfigurationCachethrows anUnsupportedError. Tests pass their ownhttpGet.
Timeouts #
The timeout and cancel of run bound the whole run with every presenter, map included: when
either comes while the code exchange runs, run throws at once, the browser gets the failed page,
and the late result is dropped. The exchange itself is not stopped, so give it its own timeout,
shorter than the run's.
run(presenter:, environment:, timeout:, cancel:) throws SecureFlowTimeout (five minutes by
default; a console presenter adds a hint to forward the port of the next run over SSH),
SecureFlowCancelled, SecureFlowRefused or
SecureFlowNoPresenter (nothing in the environment fits: on Android, iOS and, except for reCAPTCHA,
the web, register or pass one). Errors of the parser and of the presenter are rethrown as they are.
reCAPTCHA in the page of a web app #
On the web, RecaptchaFlow(...).run() takes the InPageRecaptchaPresenter of the environment:
- v2: the widget goes into a new element inside the element
containerId, in the flow'ssize(normal,compact,invisible) andtheme(the system's light or dark setting without one). Without acontainerIdit is invisible, in a new element at the end of the document. A visible widget waits for the check; an invisible one starts at once. The widget is reset after each token (the element the presenter made without acontainerIdis removed, so repeated checks leave nothing);renderrenders it ahead of time andclearremoves it. One check runs at a time: a newer one fails the one still waiting withsuperseded. - Enterprise (
RecaptchaFlow.enterprise(siteKey:, action:)):grecaptcha.enterprise.execute(siteKey, {action}), with Google's badge and no widget. - Google's script is loaded once per page (
api.js, unless the page hasgrecaptcha.render) or once per site key (enterprise.js?render=<site key>, also when another key's script is there, and again after a failed execute).scriptAddressmaps Google's address to another one (a mirror, tests). A script that fails or times out has its tag removed, so a retry loads it again. Its failures are aRecaptchaFailure:scriptLoad(blocked, offline, or refused by the page's content security policy, which must allowhttps://www.google.com/recaptcha/andhttps://www.gstatic.com/recaptcha/),loadTimeout(30 seconds by default),widget(the widget's error callback, or Enterprise refusing to make a token),noTokenandsuperseded.
final String token = await RecaptchaFlow(
siteKey: siteKey,
size: RecaptchaSize.compact,
).run(presenter: InPageRecaptchaPresenter(containerId: 'recaptcha'));
Tested in Chrome (dart2js and dart2wasm) against a fake grecaptcha; Google's scripts were not loaded.
On desktop and command line, RecaptchaFlow.enterprise serves a page on localhost that asks for the
token as soon as enterprise.js is ready. reCAPTCHA keys, v2 and Enterprise, do not allow localhost
by default: add it to the key's domain list (Google advises doing so only on a development key).
Facebook Login for Devices #
FacebookDeviceFlow signs a person in to Facebook without a browser on this machine: 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 it
has a user access token. It suits command line tools, SSH sessions, containers and desktop apps on macOS, Windows
and Linux.
final FacebookDeviceToken token = await FacebookDeviceFlow(
clientAccessToken: '<app id>|<client token>',
scopes: <String>['public_profile'],
).run(presenter: ConsolePresenter());
POST https://graph.facebook.com/<facebookGraphApiVersion>/device/loginwithaccess_token=<app id>|<client token>andscopegives the device code, the user code, the verification URL, its lifetime and the interval.- The presenter gets a
DeviceCode: the user code, the verification URL (httpsonly) and the lifetime. Nothing else of the flow reaches it. POST .../device/login_statuswith the device code, at Facebook's interval and never more often than every five seconds (facebookMinimumPollInterval). Eachslow_downadds five seconds for that poll and every later one (RFC 8628, section 3.5). Facebook's documented errors are matched on the subcode, or on the code when there is no subcode: 1349174 / 31 (authorization pending), 1349172 / 17 (polling too fast) and 1349152 / 463 (code expired). Facebook documents no HTTP status for them, and no error for a person who declines: that run ends when the code expires, or with whatever error Facebook sends.
run throws a SecureFlowTimeout when the code expires (Facebook says so, or its expires_in passes) or the run's
timeout comes first, and a SecureFlowCancelled when cancel completes. In each case the wait is cancelled, the
request in flight is aborted, and no request is sent afterwards (SecureFlow.presentDirectlyCancellable). Other
failures are a FacebookDeviceFailure: network (no connection, or no answer in 30 seconds), status (an HTTP
error without Facebook's error object), response (not a JSON object, larger than 64 KiB, or a field missing or
unsafe, such as a user code with control characters), deviceLoginDisabled ("Invalid API method", error 3: Login
from Devices is off; the message names the setting) and refused (any other error of Facebook: its code and
error_subcode are kept, its text is not). No message, toString or presenter call holds
the client token, the device code or the access token.
The client token is not a secret. Facebook's access token
guide says: "Because client tokens are
embedded in apps, they are not secret." Facebook's SDKs embed it in every app (FacebookClientToken in an iOS
Info.plist, com.facebook.sdk.ClientToken on Android); it lets an app start a sign-in that the person must
approve, nothing more. It is under App settings, Advanced, Security, Client token. The app secret is a secret:
no API here has a secret parameter, and the value must be the client token, <app id>|<client token>. A value
without exactly one | is refused, but an app access token (<app id>|<app secret>) has the same shape and
passes: passing one is a misuse the library cannot detect. Never put the app secret in an app.
Meta app settings. Facebook Login, Settings: Login from Devices set to Yes. In live mode, permissions
other than public_profile need App Review, and email may need it too.
Graph API version. facebookGraphApiVersion is pinned to v25.0 (supported until 2028-07-29; the newest on
2026-11-04 was v27.0), so that a new Graph version never changes what a released app sends. Meta keeps a version
for about two years. To move it forward: read the Graph API changelog for changes to device/login and
device/login_status, change the constant in lib/src/flows/facebook_device_flow.dart, run the unit tests and the
kit's facebook-device check, and note it in the CHANGELOG; it moves only with a release.
A QR code. DeviceCode.verificationUriWithCode is the device page with the code filled in
(https://www.facebook.com/device?user_code=<code>), a form Facebook documents for QR codes.
The HTTP layer is dart:io's HttpClient (certificates checked, no redirects followed) and can be replaced with
post: (a DeviceHttpPost). On the web there is none: without post:, run fails with an UnsupportedError.
Polling starts as soon as the code is handed to the presenter; it does not wait for the presenter to return (a
dialog or a QR code may stay up until the sign-in ends), and an error of the presenter ends the run. run waits
facebookDeviceDefaultTimeout (ten minutes) when no timeout is given, so the code's own expiry (420 seconds at
Facebook) ends it first. A run that ends, with a token or not, leaves no timer behind. An interval above 60
seconds or a code lifetime above one hour is refused as an unusable answer. To sign in to Firebase with the token, use
signInWithFacebookDevice of firebase_auth_providers_dart.
Sign in with Apple through a relay #
AppleWebFlow signs a person in with Apple on Windows, Linux and the command line, and returns Apple's tokens: the
ID token, the authorization code, and on a first sign-in the name and email. What the app does with them is its own
choice: sign in to Firebase (signInWithApple of firebase_auth_providers_dart, or
AppleAuthProvider.credentialWithIDToken with the raw nonce), or send them to a backend of its own. On macOS and iOS
use Apple's native sheet instead (AppleSignInPresenter of secure_flow_flutter).
It needs a relay that the app supplies; without one, Sign in with Apple is not available on these systems. Apple
sends its answer only to an https return URL on a domain registered with the app's Services ID, never to
127.0.0.1 ("can't be an IP address or localhost"), and Firebase's own /__/auth/handler hands its result only to
the Firebase JavaScript SDK in a page. So something on an https domain must receive Apple's answer and hand it to the
app. AppleRelay names it; there is no AppleWebFlow without one. examples/apple_relay of the repository is a
reference relay: a plain Dart server with no Firebase dependency, for any https host (a container), with an optional
wrapper that deploys it as a Cloud Functions for Firebase function.
final AppleWebResult result = await AppleWebFlow(
relay: AppleRelay(
servicesId: 'com.example.app.web',
returnUrl: Uri.parse('https://apple-relay.example.com/apple'),
),
hashedNonce: hashedNonce, // hex SHA-256 of a raw nonce the app keeps
).run();
- The flow binds
127.0.0.1on a free port and makes two values of 32 random bytes each, base64url without padding (43 characters of[A-Za-z0-9_-]): the path of its listener and a secret. It openshttps://appleid.apple.com/auth/authorizewith the Services ID, the return URL,response_type=code id_token, the scopes, the hashed nonce,state=<port>.<path>.<secret>and alwaysresponse_mode=form_post(with or without scopes), so that no token is ever in a URL: not in the address bar, the history, aRefereror a log. - Apple posts the answer to the relay. The relay's page posts
state=<secret>,id_token,code,useranderroras a top-level form tohttp://127.0.0.1:<port>/<path>. - The listener takes that form only on its path, with
Host: 127.0.0.1:<port>, with noOriginor exactly the relay's origin (SecureAnswer.crossOriginForm;Origin: nullnever), and with the secret, compared in constant time. The first such form decides the run: there is no retry, every later request gets a 404, and the listener closes when the run ends. A refused request gets a 400 page that names the check that refused it (host,origin,content-type,state, also in thex-secure-flow-refusalheader), never a value. error=user_cancelled_authorizeis aSecureFlowCancelled; another error, no ID token, or a token whoseissis nothttps://appleid.apple.com, whoseaudis not the Services ID, whoseexppassed (60 seconds of skew), or whosenonceis not the hashed nonce, is anAppleWebFailure. The signature is checked by whoever accepts the token (Firebase does).
A flow runs once (a second run throws a StateError). The user JSON comes through the browser unsigned: a field
longer than 256 characters or with control characters is dropped. The code is single use and valid five minutes:
pass it right away to whatever revokes it (FirebaseUserAuth.revokeToken(code, redirectUri: result.redirectUri)
after a fresh sign-in, before deleting an account), and never store it. On macOS and iOS the native sheet's code is
read with AppleSignInPresenter.detailsOf(tokens) and revoked without a redirectUri; store that one neither.
The relay's rules #
A relay of your own must keep all of them; the reference relay does, with a test for each.
- Run on an origin of its own (a host that serves nothing else): the listener takes forms from that origin.
- Only
POST <return path>withapplication/x-www-form-urlencoded, at most 64 KiB. Any other method (aGETtoo) gets a 405 and another path a 404, with the same headers and a page that does not echo the request. statemust match^([0-9]{4,5})\.([A-Za-z0-9_-]{43})\.([A-Za-z0-9_-]{43})$, with the port from 1024 to 65535.- The target is always
http://127.0.0.1:<port>/<path>from the checked state; no URL or host is read from the request. - Forward exactly
state(the secret only),id_token,code,useranderror, each escaped for a double-quoted HTML attribute (&,",',<,>), in a form submitted at once by a script allowed by a CSP hash, with a "Return to the app" button. Headers: that CSP (default-src 'none',form-action http://127.0.0.1:<port>,base-uri 'none',frame-ancestors 'none'),Cache-Control: no-store,Referrer-Policy: origin(measured in Chrome: underno-referrerand thestrict-*policies the https page's form tohttp://127.0.0.1goes withOrigin: null, which the listener refuses; neverunsafe-url, which sends the full URL),X-Content-Type-Options: nosniff. Never a redirect: a 307 would sendOrigin: null, and a GET would put the token in a URL. - Store nothing; never log the body or a field.
- Check the ID token before forwarding it, by default: its RS256 signature against Apple's keys
(
https://appleid.apple.com/auth/keys),iss,audandexp. Forward an answer with onlyerrorwithout a token.
What the relay sees #
Apple's ID token (the person's Apple user id, their email or private relay email, and the hashed nonce), the
authorization code, on a first sign-in the user JSON with their name and email, or an error, and the state; and
the usual request metadata (IP address, user agent, time). It never sees the raw nonce, so the token alone cannot sign in to Firebase, which refuses an
Apple token with a nonce unless the matching raw nonce comes with it; and it cannot use the code, whose exchange
needs the Apple private key that only the Firebase console holds. A compromised relay exposes personal data, not
access. If another backend of yours accepts Apple ID tokens for the same Services ID without checking a nonce, a
leaked token works there: check nonces everywhere.
What the loopback server checks #
- It binds 127.0.0.1, plus ::1 on the same port for
localhostflows (so that no other process can answer on ::1 in its place), and no other interface. - The page is served only to a GET of the flow's path that carries the state of this run.
- The answer must come to the flow's path (random unless the flow fixes it), with the flow's method
and encoding, with
Host: <host>:<port>exactly (a page of another site whose name resolves to the loopback address sends its own name), with the page'sOriginfor form answers when the browser sends one, and with the state of this run, compared in constant time. Anything else gets an error page, and the server keeps waiting. - One answer is accepted, ever: while an answer is being handled and after it, every request gets a
- A flow can reject an answer (an empty token) and keep the state for a retry.
- Request bodies are limited to 64 KiB. Pages are not cached, cannot be framed, and carry a content
security policy with a new nonce in every response (for the styles of the message and code pages;
for the scripts of the reCAPTCHA page, whose widget needs inline style attributes). The reCAPTCHA
page sends
Referrer-Policy: strict-origin(Google sees the origin, not the path or the state); the other pages load nothing and sendno-referrer. Pages follow the system's light or dark setting. - The server is closed on every exit: result, error, timeout, cancel, or a presenter that throws.
- Nothing is logged, and no error message contains the state, the path, a token or a site key.
What it does not protect against #
- Other local programs, and on Linux other local users. The URL is in the arguments of the
opener (
xdg-open,open,rundll32) and, when the browser was not running yet, in the arguments of the browser for as long as it runs. On Linux/proc/<pid>/cmdlineshows them to every local account by default, so other users can read the state and, for OAuth, the code challenge. Any local account can connect to the loopback port, and a program of the same user can drive the browser. PKCE keeps an intercepted OAuth code useless to them, but someone who has the state can send a code for an account of their own (see the console case below); nothing here hides a URL from them. On a Linux machine shared with other people, mount/procwithhidepid=invisible(orhidepid=2) so that other users cannot read the arguments, or start the browser yourself before the flow so that only the short-lived opener carries the URL. - Sign in with Apple through a relay (
AppleWebFlow). Everything that binds the answer to this run (the port, the random path and the secret) travels in thestateof the authorization URL, with the hashed nonce next to it, so whoever reads that URL can complete the run, as the first point above says for every flow. For Apple they need nothing but a browser and an Apple account of their own: on Linux another local user reads the URL from/proc/<pid>/cmdlineof the opener or the browser, signs in with their account, and Apple and your relay deliver their ID token, carrying your nonce, to your listener before yours arrives. Your app then signs in to their account (login CSRF); there is no code exchange or PKCE to stop it. The same mitigations apply:hidepid=invisibleon/proc, or a browser that is already running, so that only the short-lived opener carries the URL. Show the person which account they signed in to. - Whoever sees the terminal or its logs of a
ConsolePresenter. The URL it prints carries the state of the run and, for an OAuth request with PKCE, the code challenge (and the nonce hash when one is sent). When stderr is captured (a CI log,journald, a log shipper,script, a terminal multiplexer's scrollback), the log holds them, and they stay good for the life of the flow (five minutes by default). Someone who reads the log in that time and can reach the loopback port (a program on this machine) can get an authorization code for an account of their own, issued for that challenge, and send it with the state: the app then signs in to their account. PKCE keeps a code of the user's useless to them, because the verifier is never printed. Where stderr is recorded, passConsolePresenter(sink:)a sink that is not, or use another presenter. - What PKCE does not cover.
pkce: truebinds the code to this run's verifier, so a code that someone else intercepts is useless to them. It does not stop someone who has the state from sending a code for an account of their own (the first point above), and it does nothing for a provider app's result or for a URL you build withoutpkce: true. The code exchange, and keepingOAuthRedirect.codeVerifierout of your own logs, are yours. - A remote browser. The answer must reach this machine's loopback interface. Over SSH, forward
the port while the flow waits (
ssh -L <port>:127.0.0.1:<port> <host>, orlocalhostfor a reCAPTCHA flow); without that, the run ends with aSecureFlowTimeoutwhose message says so. - A presenter that lies about its kind. A web view registered as a system browser would be used for OAuth; kinds are declarations, not checks. A web view the app controls can read and change the page.
- A provider app. Its result is trusted as the app returns it; the caller checks the nonce of an
ID token, and Firebase checks the token. An access token alone carries no nonce, so nothing ties
it to the request:
firebase_auth_providers_dartrefuses one unless its provider opts in. - Firebase's verdict on a localhost token. Google issues a reCAPTCHA v2 token on a localhost page (checked on 2026-11-28 with the project's own key). Whether Firebase accepts it was not checked: it depends on the site key and the project, and the one request that takes a v2 token sends an SMS.
How it is tested #
The unit tests run the flows against fake identity providers and a fake grecaptcha. On 2026-11-28 the
production verification kit ran against a real Firebase
project with secure_flow 0.3.0: Google through OAuthFlow.discovery, the discovery cache on disk, the GitHub
loopback sign-in and a reCAPTCHA v2 token on localhost passed; reCAPTCHA Enterprise was not run. See the
report.
AppleWebFlow is tested against a fake Apple and a fake relay (the state format over 5,000 flows, the one delivery,
the relay's Origin, every check of the ID token, both response modes). It has not been run against the real Apple;
the kit's apple-web check does that with your Services ID and relay.
FacebookDeviceFlow is tested against a fake Graph API in fake time (the interval, slow_down, expiry, the run's
timeout and cancel, every failure). It has not been run against the real Facebook; the kit's facebook-device check
does that with your app.
The fix that drains the request body before answering 413 on Windows (#131) has not been run on Windows
since the fix.
License #
Apache 2.0; see LICENSE and NOTICE.