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 [...]
0.4.0 #
- PKCE (RFC 7636,
S256) is built in:OAuthFlow.authorizationandOAuthFlow.discoverytakepkce: true(off by default). The flow makes a verifier of 32 secure random bytes (base64url, 43 characters), addscode_challengeandcode_challenge_method=S256to the authorization URL the caller builds (anArgumentErrorif the caller set them), and returns the verifier on the newOAuthRedirect.codeVerifier; never in a URL, page, error ortoString. With discovery, a document whosecode_challenge_methods_supportedlacksS256fails the run before the browser opens; a document without the field is accepted. A provider app's redirect has no verifier.Pkce.generate()andPkce.challengeOf(verifier)are public for apps that build their own request. secure_flow still has no dependencies: it carries its own SHA-256 (FIPS 180-4 vectors, VM and web). - Breaking:
SecureFlowPurpose.deviceCode, the purpose of a device sign-in. AswitchoverSecureFlowPurposewithout adefault(or a wildcard) no longer compiles until it handles the new case. FacebookDeviceFlow: Facebook Login for Devices, for desktop apps and command line tools.POST graph.facebook.com/<facebookGraphApiVersion>/device/loginwithaccess_token=<app id>|<client token>andscope; the user code and the verification URL go to aDeviceCodePresenter, and polling ofdevice/login_statusstarts at once (it does not wait for the presenter to return; an error of the presenter ends the run). Polls come at Facebook's interval, never more often than every five seconds, plus five seconds for good after eachslow_down. The result is aFacebookDeviceToken. A code that expires (Facebook's subcode or itsexpires_in) is aSecureFlowTimeout, the app's cancel or the run's timeout aSecureFlowCancelledorSecureFlowTimeout; on each, the wait and the expiry timer are cancelled, the request in flight is aborted, and nothing is sent afterwards (the flow overridesSecureFlow.presentDirectlyUntil). A granted sign-in leaves no timer behind. Facebook's documented errors are matched on the subcode, or the code without one (1349174 / 31 pending, 1349172 / 17 too fast, 1349152 / 463 expired). An interval above 60 seconds or a lifetime above one hour is refused as an unusable answer. Other failures are aFacebookDeviceFailure(network,status,response,deviceLoginDisabledfor "Invalid API method" (error 3),refused) whose message holds the HTTP status and Facebook's numeric codes, never the body or a token. No API takes a secret parameter: the value must be<app id>|<client token>, and one without exactly one|is refused. An app access token (<app id>|<app secret>) has the same shape, so passing one is a misuse the library cannot detect. The Graph API version is pinned (facebookGraphApiVersion,v25.0). The HTTP layer isdart:io'sHttpClientand can be replaced (post, aDeviceHttpPost); on the web there is none, sorunfails with anUnsupportedErrorunlesspostis given.AppleWebFlowandAppleRelay: Sign in with Apple on Windows, Linux and the command line, through a relay the app supplies (anhttpsreturn URL of its Services ID; Apple never redirects to127.0.0.1). There is noAppleWebFlowwithout a relay. The result is Apple's tokens (AppleWebResult: the ID token, the authorization code, the redirect URI it was issued for, andAppleWebUserwith the first-time name and email); the app decides what to do with them. The flow makes its own listener path and secret (32 random bytes each, base64url without padding) and sendsstate=<port>.<path>.<secret>,response_type=code id_token, the hashed nonce (64 lowercase hex digits), and alwaysresponse_mode=form_post, so that no token is ever in a URL. Its listener takes only a form of the relay's origin (or one withoutOrigin) carrying the secret; the first one decides the run (no retry). It checksiss,aud(the Services ID),exp(60 seconds of skew) and the nonce (constant time), not the signature. Apple's cancel is aSecureFlowCancelled; other failures anAppleWebFailure(response,refused,claims,nonceMismatch) whose message holds no token, code or nonce. A flow runs once. Presenters: the system browser and the console. The README has the relay's rules, what the relay sees, and a paragraph on shared machines in "What it does not protect against".SecureAnswer.crossOriginForm(path:, allowedOrigin:): a form answer that a page of one otherhttpsorigin may post. The origin must behttpswith a host and no user info, path, query or fragment (ArgumentErrorotherwise), and is compared asUri.origin;Origin: nullis never taken.SecureAnswer.allowedOriginis null for the other answers, whose behaviour does not change.- A request the loopback server refuses (400) names the check that refused it, at the end of a message page and in
the
x-secure-flow-refusalheader:host,origin,content-typeorstate. No value of the request or of the run is in it. DeviceCode,DeviceCodePresenterandDeviceCodeCallbackPresenter(kindother): a code for the person to type on another device;DeviceCode.verificationUriWithCodeis the page with the code filled in, for a QR code.ConsolePresenteris aDeviceCodePresentertoo: it writes one line with the page and the code.- Dev dependency:
fake_async. OAuthAppRequest(abandoned:)andOAuthAppRequest.abandoned: a future that completes whenSecureFlow.rungives up on a provider-app sign-in because its timeout or cancel came first (never after a result or an error), so that the presenter can close its sheet and free itself for the next sign-in. It completes beforerunthrows itsSecureFlowTimeoutorSecureFlowCancelled, so the presenter is free by the time the caller retries.SecureFlow.presentDirectlyUntil(presenter, abandoned:), whichrunnow calls instead ofpresentDirectly. Its default callspresentDirectly, so a flow that extendsSecureFlowand was written for 0.3.0 works unchanged. Breaking for a class thatimplements SecureFlow(rather than extending it): it must addpresentDirectlyUntil.OAuthFlowandmappass the signal on.ProviderAppException: anabstract base classfor the errors of provider apps, with a coarsekind, aProviderAppExceptionKind(nonceMismatch,invalidRequest,other;otherby default), for callers to map. A new kind comes only in a breaking version.SecureFlowCancelledalso covers a person's cancel in a provider app.- Documentation: the README and the
RecaptchaFlowdartdoc record the real runs of 2026-11-28 (Google throughOAuthFlow.discovery, the discovery cache, GitHub, a reCAPTCHA v2 token on localhost); the README warns thatCallbackPresenterdefaults tokind: systemBrowser, so an embedded web view must pass its true kind; and it notes that the Windows413drain fix (#131) has not been run on Windows since the fix. - Docs: the public doc comments no longer carry RFC and OpenID section numbers; the streams that callers pass in
(
ConsolePresenter.input, thebodyofOidcHttpResponseandDeviceHttpResponse) say they are listened to once and do not replay. Doc-only references use@docImportinstead of imports.
0.3.0 #
-
Breaking:
OAuthFlow's unnamed constructor is nowOAuthFlow.authorization, with the same arguments. Migration: replaceOAuthFlow(withOAuthFlow.authorization(. TheauthorizationUrlfield is gone (the builder is private). -
OAuthFlow.discovery(providerId:, issuer:, authorizationUrl:, state:, discovery:, ...): an OpenID Connect sign-in whose endpoints come from the issuer's discovery document.runfetches it before the loopback server starts, within the run's timeout and cancel (a provider app needs none, and none is fetched), and callsauthorizationUrl(configuration, redirectUri); the caller still builds the query.OAuthRedirect.configurationcarries the document, so thatmapcan exchange the code at itstokenEndpoint. -
OidcDiscovery: fetches and caches discovery documents. The issuer must behttps(no user info, query or fragment), the document'sissuermust equal it exactly (OpenID Connect Discovery 1.0, section 4.3), and itsauthorization_endpointandtoken_endpointmust behttps. One GET, no redirects followed, a 64 KiB body cap, a 30 second timeout (timeout), andcancel. Freshness:Cache-Control: max-age, or elseExpiresminusDate, minusAge;no-storeis not stored,no-cacheis revalidated every time. A stale document is revalidated with one conditional GET (If-None-Match,If-Modified-Since): a 304 renews it, a 200 replaces it after the same checks, and a failure throwsOidcDiscoveryException(a stale copy is never returned). A cached document is checked again whenever it is used.OidcConfigurationhasissuer,authorizationEndpoint,tokenEndpointand the wholejson. -
Caches (
OidcConfigurationCache, keyed by issuer):MemoryOidcConfigurationCache(the default) andFileOidcConfigurationCache(path), one JSON file at a path the app chooses (a corrupt file is a miss; writes go to a temporary file renamed over it). The HTTP layer isdart:io'sHttpClientand can be replaced (httpGet, anOidcHttpGet). On the web there is no default HTTP layer (passhttpGet), and the file cache throws anUnsupportedError; the library still compiles there. -
SecureFlow.prepare: the step before the loopback server starts (the fetch ofOAuthFlow.discovery), bounded by the run's timeout and cancel. It returns the flow itself by default. -
Changed behaviour: the timeout and the
cancelofSecureFlow.runnow bound the work ofmap(and ofparse) on the loopback server too, as they already did with a direct presenter. When either comes while an answer is being parsed,runthrowsSecureFlowTimeoutorSecureFlowCancelledat once, the browser that sent the answer gets the failed page, and the late result is dropped (the work itself is not stopped: give a code exchange its own, shorter timeout). Before, the timeout waited for the parser, so a hanging exchange hungrun, while the cancel did not wait; the dartdoc said neither applied. -
ConsolePresenter's timeout hint no longer tells the person to forward the port of the run that just ended and open its URL again (that server is closed, and the next run gets a new port): it says to run the flow again and forward the port of the new URL while it waits. -
Docs: the security scope names other local programs and, on Linux, other local users (the URL is in the opener's and a freshly started browser's arguments, which
/procshows to every local account by default), withhidepidas a mitigation. reCAPTCHA keys, v2 and Enterprise, do not allowlocalhostby default: add it to the key's domain list. -
The browser tests (
test/browser) run in CI, in Chrome with dart2js and dart2wasm.
0.2.0 #
-
Breaking for exhaustive
switchstatements:SecurePresenterKindhas the new valueinPage, andRecaptchaActionhas new values for the Enterprise actions. -
RecaptchaFlow.enterprise(siteKey:, action:): a reCAPTCHA Enterprise token for an action. Its loopback page loadsenterprise.js?render=<site key>and posts the token ofgrecaptcha.enterprise.executeas soon as it is ready. The action is checked (letters, digits,/and_). -
RecaptchaFlowtakes thesize(RecaptchaSize: normal, compact, invisible) andtheme(RecaptchaTheme) of the v2 widget; the loopback page starts an invisible widget at once. Its script keeps its names out of the page's global scope. -
InPageRecaptchaPresenter(web builds,dart:js_interoponly): renders the v2 widget into an element of the app's page (invisible without a container), or runs the Enterprise execute, and returns the token without the loopback server;render,clear, andonVerified/onExpired/onErrorcallbacks. The Enterprise script loads once per site key (also next to App Check's), and again after a failed execute; a script that fails or times out loses its tag; without a container the widget's element is removed after each check; a newer check fails the waiting one (superseded);scriptAddressreplaces Google's address.SecureEnvironment.current()offers one on the web, andRecaptchaFlowranks it first, so a reCAPTCHA runs in the page there. Tested in Chrome against a fakegrecaptcha. -
New presenter kind
SecurePresenterKind.inPageand interfaceRecaptchaPresenter(a presenter that returns a reCAPTCHA token itself;RecaptchaFlowtakes one of any kind it ranks).CallbackPresenterrefuses theinPagekind. -
RecaptchaFailure(scriptLoad,loadTimeout,widget,noToken,superseded) for a presenter that could not make a token;RecaptchaFlowthrows it for an empty token of aRecaptchaPresenter.
0.1.0 #
First release.
SecureFlow<T>: a self-contained browser round trip (what to open or serve, which request answers it, its host, how the answer becomes aT) that ranks the presenter kinds it accepts and runs itself:flow.run(presenter:, environment:, timeout:, cancel:)takes the best presenter of the environment, or checks the given one and throwsSecureFlowRefusedwhen it does not accept it.mapruns work, such as a code exchange, before the browser is told the outcome. Third parties can write flows and presenters.- Flows:
OAuthFlow(resultOAuthResult: the redirect of a code request onhttp://127.0.0.1:<port>, or the tokens of a provider app; ranks provider app, system browser, in-app browser, console),RecaptchaFlow(a reCAPTCHA v2 token from a page onhttp://localhost:<port>; ranks embedded web view, system browser, console) andCodeEntryFlow(a code typed at the terminal or into a form; ranks console, then the system browser). - Presenters with a
SecurePresenterKind(providerApp,systemBrowser,inAppBrowser,embeddedWebView,console,other) and capability interfaces (LoopbackPresenter,PromptPresenter,ProviderAppPresenter):SystemBrowserPresenter,ConsolePresenter(only the URL, on stderr by default; prompts read the injected input, stdin by default) andCallbackPresenter(the app shows the URL and declares the kind).SecureEnvironmentlists what is on offer: registered presenters, the system browser with a display, the console with a terminal. - The loopback server: binds 127.0.0.1 (and ::1 for
localhostflows), random path, the page only for a GET with the state, single-use state compared in constant time, one accepted answer,Hostchecked against the flow's host,Originchecked for form answers, 64 KiB body limit, a CSP nonce in every response, timeout, cancel, closed on every exit; pages follow the system's light or dark setting. - Typed errors:
SecureFlowTimeout(with anssh -Lhint fromConsolePresenter),SecureFlowCancelled,SecureFlowRefused,SecureFlowNoPresenter.