blocks_runtime

Runtime library for the AWS CDK Blocks Dart SDK. Provides a JSON-RPC 2.0 HTTP client, WebSocket realtime channels, file upload/download handles, cookie-based session management, and OIDC authentication (PKCE + token exchange).

Usage

import 'package:blocks_runtime/blocks_runtime.dart';

Client code generated by blocks_codegen calls this package for you. You use it directly to configure the BlocksClient and to sign in with an OidcClient.

BlocksClient

final client = BlocksClient(baseUrl: 'https://your-api.example.com/cdk-blocks/api');
Parameter Type Default Description
baseUrl String required The JSON-RPC endpoint. A call to namespace.method is POSTed to {baseUrl}/{namespace}.
client http.Client? http.Client() The HTTP client that sends the calls.
sessionStore SessionStore? Platform default Where session cookies are kept. See Sessions for Flutter secure storage, browser cookies and the pure Dart default.
tokenStore TokenStore? InMemoryTokenStore() Where an OidcClient keeps its tokens. The default loses them when the process exits.
authProvider AuthProvider? none Supplies a bearer token. When it has one, calls send it as an Authorization: Bearer header, alongside the session cookie when there is one. On an HTTP 401 the client calls its onAuthFailure() and runs the call once more.

The generated Blocks class takes only baseUrl and sessionStore and builds its own BlocksClient. To set client, tokenStore or authProvider, build the BlocksClient yourself and pass it to each generated API class:

final client = BlocksClient(
  baseUrl: 'https://your-api.example.com/cdk-blocks/api',
  tokenStore: tokenStore,
  authProvider: bearerProvider, // An AuthProvider that supplies a bearer token.
);
final authApi = AuthApi(client);

The built-in OidcClient sign-in flow requests a session cookie, not bearer tokens. For that flow, use the same SessionStore for sign-in and RPC calls; the generated Blocks does this automatically.

PersistentSessionStore(store: tokenStore) is a SessionStore that persists cookies through a TokenStore. It loads saved cookies before the first request automatically.

With valid parameters (List or Map), RPC response and transport failures use these exceptions:

  • An ApiException, with the server's message, status, name and retriable, when the response carries a JSON-RPC error, at any HTTP status. Match its name with isBlocksError(e, 'ConditionalCheckFailedException').
  • A TransportException when no usable JSON-RPC result came back: no response, a non-2xx response with no JSON-RPC error, or a body that is not a JSON-RPC envelope. Its statusCode is null when no response arrived, and its cause is then the HTTP client's error.
  • A ClientClosedException after client.close(), which closes the HTTP client. An OidcClient that a generated API class built from one of this client's results throws it too.

Using Auth

An Auth block's createApi() export (here authApi) is a state machine:

  • getAuthState() returns the current state, the signed-in user and the actions the user can take next, and setAuthState(input: ...) submits one of them.
  • Use it for everything except the federated sign-in buttons: whether the user is signed in, email and password sign-in, sign-up, confirmation codes, MFA steps and unavailable actions.
  • The result of setAuthState is the next state: the confirmation, MFA and password-reset steps only appear there, never in getAuthState(), which returns only signedIn or signedOut.
  • Call getAuthState() on launch and after a federated sign-in or sign-out.

Federated sign-in and sign-out go through the OidcClient the block's createOidcApi() export (here oidcApi) returns from getClient():

  • Render one sign-in button per provider in that client's providers, and have it call oidc.signIn(provider).
  • Don't render the state machine's signIn:<id> actions as buttons: their url starts a browser-cookie flow whose cookie never reaches the app, and the client already lists the providers it can sign in with.
  • A provider whose discovery failed on the server is left out of providers, so it gets no button.
  • Call getClient() once per block and keep that client for the app's lifetime.
// cdk-blocks/index.ts
export const authApi = auth.createApi();
export const oidcApi = auth.createOidcApi();

The sample below is a ChangeNotifier a Flutter widget can listen to. It opens the identity provider's logout URL with url_launcher, so add that package to your app's dependencies too.

An Auth block on the default store signs in through its providers only once it is deployed. To sign in through a provider while running locally, give the provider to a store: 'builtin' block with stubIdp(), and export that block's createOidcApi(); the Auth block's README has the details.

import 'package:blocks_runtime/blocks_runtime.dart';
import 'package:blocks_runtime_flutter/blocks_runtime_flutter.dart';
import 'package:flutter/foundation.dart';
import 'package:url_launcher/url_launcher.dart';

import 'blocks.blocks.dart'; // the generated client

/// The app's sign-in state, driven by an `Auth` block's two exports.
class AuthModel extends ChangeNotifier {
  AuthModel(this.blocks);

  final Blocks blocks;

  // Listed in the block's redirects.allowedRelayOrigins.
  static const relayTo = 'com.example.app://auth';

  AuthState? state;
  TypedOidcClient<OidcApiGetClientProvider>? oidc;
  String? error;

  /// On launch: the state of the session the store kept, and the block's
  /// OIDC client. Both calls throw when the backend can't be reached, so show
  /// the error and offer a retry.
  Future<void> load() async {
    try {
      state = await blocks.authApi.getAuthState();
      oidc = await blocks.oidcApi.getClient();
    } on BlocksException catch (e) {
      error = 'Could not reach the server: ${e.message}';
    }
    notifyListeners();
  }

  /// The federated sign-in buttons: one per provider the client can sign in
  /// with, as the generated enum.
  List<OidcApiGetClientProvider> get signInButtons => [
    for (final name in oidc?.providers ?? const <String>[])
      ?OidcApiGetClientProvider.fromProviderName(name),
  ];

  /// What a federated sign-in button runs. On iOS and Android the browser
  /// returns through [relayTo]; on macOS, Linux and Windows the client signs
  /// in through a loopback listener and needs no launcher.
  Future<void> signInWith(OidcApiGetClientProvider provider) async {
    error = null;
    final mobile =
        defaultTargetPlatform == TargetPlatform.iOS ||
        defaultTargetPlatform == TargetPlatform.android;
    try {
      await oidc!.signIn(
        provider,
        launcher: mobile ? FlutterBrowserLauncher() : null,
        relayTo: relayTo,
      );
    } on OidcCancelledException {
      // The user closed the browser, or the sign-in timed out.
      return;
    }
    state = await blocks.authApi.getAuthState();
    notifyListeners();
  }

  /// Runs [action] with the [values] the user typed into its fields. Render
  /// every action but the `signIn:<id>` ones, which [signInButtons] replaces,
  /// and render an action that carries `unavailable` disabled, with that
  /// text, so it never gets here.
  Future<void> run(AuthAction action, Map<String, String> values) async {
    error = null;
    if (action.name == 'signOut' && action.url != null) {
      // A federated sign-out. Never submit it through setAuthState, which
      // drops the IdP's logout URL. Open that URL to end the IdP's session
      // too.
      final logoutUrl = await oidc!.signOut();
      if (logoutUrl != null) await launchUrl(logoutUrl);
      state = await blocks.authApi.getAuthState();
    } else {
      // A plain action. Its result is the next state, such as
      // confirmingSignUp after a sign-up.
      final next = await blocks.authApi.setAuthState(
        input: switch (action.name) {
          'signIn' => SignInInput(
            username: values['username']!,
            password: values['password']!,
          ),
          'signUp' => SignUpInput(
            username: values['username']!,
            password: values['password']!,
            // Every other field the action lists goes in
            // additionalProperties.
            additionalProperties: {
              for (final MapEntry(:key, :value) in values.entries)
                if (key != 'username' && key != 'password') key: value,
            },
          ),
          'confirmSignUp' => ConfirmSignUpInput(
            username: values['username']!,
            code: values['code']!,
          ),
          // Offered after confirmSignUp when the block signs the user in
          // automatically: submit it to finish signing in.
          'autoSignIn' => AutoSignInInput(username: values['username']!),
          'signOut' => const SignOutInput(),
          // ...one case for each other action the block offers.
          _ => throw UnsupportedError(action.name),
        },
      );
      // Either way, show the error, if any: a wrong password, for example.
      error = next.error;
      // A retriable failure, such as a wrong confirmation code, keeps the
      // current state and form. Anything else, including a failed sign-in,
      // is the next state.
      if (next.retriable != true) state = next;
    }
    // Render state?.state, state?.user, state?.actions and error.
    notifyListeners();
  }
}
  • The client getClient() returns shares the generated client's session store and token store, so the session cookie the sign-in sets is the one every RPC call sends. It carries the block's own routes, including a custom redirects.callbackPath or redirects.signOutPath, and keeps its tokens under keys of its own block, so several Auth blocks can share one token store and one session store.
  • When the spec names the block's providers, getClient() returns a TypedOidcClient whose signIn takes the generated provider enum (OidcApiGetClientProvider for oidcApi.getClient), so a provider the block doesn't have doesn't compile. providers holds the names the server described; fromProviderName turns each into the enum value, as above. A spec that names no providers returns a plain OidcClient, whose signIn takes the name.
  • A retriable failure comes back as {state: signedOut, actions: [], retriable: true, error, errorName}. It doesn't mean the user was signed out: keep the current form and show error. A wrong confirmation or MFA code, a password that fails the policy, an invalid field and a server fault are retriable. A wrong password is not: it comes back as a signed-out state with the sign-in actions and an error to show.
  • A confirmation step lives only in the app: getAuthState() can't bring it back after the app is killed. To let the user finish confirming a sign-up, save the username when you get confirmingSignUp, and after a restart show the code form and submit ConfirmSignUpInput with it, or ResendSignUpCodeInput for a new code. An interrupted MFA or new-password challenge can't be resumed: sign in again.
  • On launch, call getAuthState(). It works for every Auth block. oidc.restore() returns the same user, but only a block with sign-in providers serves its session route; any other answers 404.
  • Disable an action that carries unavailable, and show its text.
  • Never submit a signOut action that has a url through setAuthState: that drops the identity provider's logout URL. Call oidc.signOut() instead.
  • signOut() returns the identity provider's logout URL, or null. The SDK doesn't open it. Whatever the outcome, it signs out locally: it clears this block's tokens and session cookie and emits OidcSignedOut. Then:
    • a 503 SignOutIncompleteException throws an ApiException with that name, so isBlocksError(e, 'SignOutIncompleteException') is true;
    • any other failed status throws an ApiException with the status and the server's error name;
    • a request with no response throws a TransportException;
    • a cancelled request passes its own error through.
  • Hide actions whose capability is webauthn-get or webauthn-create (passkeys). This SDK doesn't run WebAuthn ceremonies.
  • New actions can appear in a later version of the block. Render or skip actions you don't know by name, and don't fail on them.
  • For relayTo on mobile, prefer a verified App Link (Android) or Universal Link (iOS) over a bare custom scheme. Another app can register the same custom scheme and receive the relay redirect; with a custom scheme, PKCE is what stops it from using the code, because only this app holds the verifier.
  • Sign in with signIn. signInDirect, the direct flow, sends the IdP a custom-scheme redirect_uri, which most identity providers reject.

Register the backend's callback with the identity provider, not an address in the app: every platform's signIn sends the IdP the backend's HTTPS callback as its redirect_uri, and the backend relays the result to the app. That callback is the client's baseUrl with its final /cdk-blocks/api replaced by the block's redirects.callbackPath, /cdk-blocks/auth/callback unless you set one. A deployed API keeps its stage: for https://abc123.execute-api.us-west-2.amazonaws.com/prod/cdk-blocks/api, register https://abc123.execute-api.us-west-2.amazonaws.com/prod/cdk-blocks/auth/callback. If the IdP asks for a sign-out URL, register the same prefix followed by the block's redirects.postSignOutPath (/ by default), here https://abc123.execute-api.us-west-2.amazonaws.com/prod/.

Federated sign-in on each platform

Platform How signIn gets the redirect What to pass
iOS, Android The app's custom scheme launcher: FlutterBrowserLauncher() and a relayTo in the block's redirects.allowedRelayOrigins
macOS, Linux, Windows A loopback listener on 127.0.0.1 Nothing: oidc.signIn(OidcApiGetClientProvider.google)
Web Not supported: a browser app signs in on its own origin

While waiting for the browser redirect, cancellation throws OidcCancelledException:

  • Pass cancel: to signIn or signInDirect to stop waiting early, for example when the user closes the sign-in dialog: signIn(OidcApiGetClientProvider.google, cancel: dialogClosed.future). When it completes before the redirect arrives, the client stops waiting, the loopback listener closes, and a launcher gets the same cancel future so it can stop too.
  • FlutterBrowserLauncher throws it when the app resumes after being hidden or paused and no redirect arrives within resumeGracePeriod (2 seconds by default), or when its optional timeout passes: FlutterBrowserLauncher(timeout: const Duration(minutes: 5)).
  • The loopback sign-in throws it once oidc.signInTimeout passes.
  • A custom BrowserLauncher should throw it when its browser is dismissed.

On desktop, a call without a launcher binds 127.0.0.1 on a port the operating system picks, relays to http://127.0.0.1:<port>/oidc/callback (the backend allows a loopback relay target without an allowedRelayOrigins entry), opens the browser and waits for the redirect. A launcher, when passed, always wins.

  • oidc.openBrowser sets how the browser opens. It defaults to the platform's URL handler (open, xdg-open or rundll32). A Flutter desktop app should set it, for example to url_launcher, throwing when no browser opened, and handle the error signIn then throws:

    oidc.openBrowser = (url) async {
      if (!await launchUrl(url, mode: LaunchMode.externalApplication)) {
        throw StateError('No browser to sign in with');
      }
    };
    
  • oidc.signInTimeout (default 5 minutes) bounds the wait. When it passes, signIn throws OidcCancelledException. Both fields apply only to a call without a launcher.

  • For a command-line app: when the default handler can't open a browser, for example on a Linux host with no xdg-open, the client prints a one-time http://127.0.0.1:<port>/oidc/start/<random> URL to stderr and keeps waiting. Opening it redirects to the sign-in page. Treat it like the sign-in link itself: it works once, for this sign-in only. On Windows, rundll32 usually exits 0 even when nothing opened, so this fallback rarely runs there. A Flutter app has no stderr to read, which is why it should set openBrowser.

  • A sandboxed macOS app needs the com.apple.security.network.server entitlement to accept the redirect on its listener, and should set openBrowser to url_launcher, because the sandbox can stop it from running open.

OidcClient

Member Type Description
providers List<String> The names of the providers the client can sign in with.
signIn(provider, launcher:, relayTo:, cancel:) Future<OidcUser> Signs in through the backend's HTTPS callback, which redirects the browser to relayTo or, without a launcher, to a loopback listener. All three named parameters are optional; Federated sign-in on each platform says what to pass and how cancel ends the wait.
signInDirect(provider, launcher:, redirectUri:, cancel:) Future<OidcUser> Signs in with redirectUri as the IdP's redirect_uri. launcher and redirectUri are required.
exchange(...) Future<OidcUser> Exchanges an authorization code for the user. signIn and signInDirect call it; call it only when the app runs the authorize step itself.
restore() Future<OidcUser?> Reads the signed-in user from the backend's session route. Returns null when there is no session.
signOut() Future<Uri?> Signs out on the backend and locally. Returns the identity provider's logout URL, or null.
openBrowser Future<void> Function(Uri url)? How a signIn without a launcher opens the browser. null, the default, uses the platform's URL handler.
signInTimeout Duration How long a signIn without a launcher waits for the redirect. Default 5 minutes.
authState OidcAuthState The current state: OidcLoading until the first change, then OidcSignedOut or OidcSignedIn (with its user).
authStateChanges Stream<OidcAuthState> The current state, then each change.

launcher is a BrowserLauncher; a Flutter app on iOS or Android passes FlutterBrowserLauncher() from blocks_runtime_flutter.

Failures:

  • signIn, signInDirect and exchange throw the subclasses of the sealed OidcException in the table below. Only OidcExchangeException carries a cause.
  • An auth route that refuses a request throws an ApiException with the status and the server's error name:
    • restore() on a status other than 200 or 401;
    • signOut() on a failed status, such as a 503 SignOutIncompleteException;
    • a token refresh (refresh(), or an API call made with this client as authProvider) on a status other than 200, 400 or 401.
  • A request that gets no response throws a TransportException whose cause is the HTTP client's error. A 200 answer to restore() or to a token refresh that the client cannot read throws a TransportException with statusCode 200.
  • Once the BlocksClient whose call returned the client is closed, signIn, signInDirect, exchange, restore(), signOut() and refresh() throw a ClientClosedException.
  • A 2xx answer to the authorize-params request of signIn that is not the expected JSON throws a FormatException or a TypeError. A 2xx exchange answer whose user or tokens have the wrong type throws a TypeError.
  • signIn throws a StateError, before any request is sent, when it gets a launcher without a relayTo, or no launcher on a platform with no loopback sign-in (mobile or the web).
  • signIn without a launcher throws an ArgumentError when the backend's authorize URL is neither an https URL nor http on a loopback host.
  • signInDirect throws a StateError on a state mismatch in its redirect.
Exception Thrown when
OidcUnknownProviderException The client's providers does not list the provider or, for signInDirect, providerConfigs has no entry for it. Thrown before anything is sent.
OidcCallbackException In signIn: the backend refuses the authorize-params request, or the redirect carries an IdP error, a state envelope that cannot be read or a CSRF value that does not match. With a launcher, also when the redirect lacks state or code or its state does not match; a loopback listener answers such a request with 404 and keeps waiting. In signInDirect: the redirect carries an IdP error or lacks code.
OidcExchangeException The exchange route answers with a failed status (the cause is an ApiException with the status and the server's error name), with a 2xx body that is not a JSON object (the cause is a TransportException), or without a user.
OidcCancelledException A sign-in ends without a redirect: cancel completes first, signInTimeout passes in a signIn without a launcher, or the launcher throws it. FlutterBrowserLauncher throws it when the app returns to the foreground without a redirect and when its timeout passes. See Federated sign-in on each platform.

Typed OIDC providers

This section covers custom blocks that return an OIDC client; for Auth, see Using Auth. OidcClient's signInDirect, signIn and exchange take a provider by the name the backend knows it by. TypedOidcClient<P extends OidcProvider> is an extension type over an OidcClient that narrows those three methods to providers of type P. A generated client returns one, with P an enum it generates from the spec's provider names, so passing a provider that client doesn't have is a compile error:

// AuthApiGetClientProvider is the enum blocks_codegen generates for a
// method `auth.getClient` whose spec names its providers.
final TypedOidcClient<AuthApiGetClientProvider> oidc =
    await blocks.auth.getClient();
await oidc.signIn(
  AuthApiGetClientProvider.google,
  launcher: launcher,
  relayTo: 'com.example.app://auth',
);
  • Each enum value carries the name the backend knows the provider by as its providerName (loginGov is 'login.gov').
  • fromProviderName(name) on the enum finds the value for a name known only at runtime, or returns null.
  • A TypedOidcClient is the same object as the OidcClient it wraps: it can be passed wherever an OidcClient is expected, and its other members are the client's own. Typed as an OidcClient, it takes provider names again.
  • is TypedOidcClient can't tell it from a plain OidcClient at runtime, because it is a compile-time view.
  • A spec that names no providers, a client inside a model, and a client built with OidcClient(...) are a plain OidcClient, which takes the provider's name: signIn('google', …).

The enum's name is in the blocks_codegen README under Generated names.

Sessions

A BlocksClient keeps the session cookies the backend sets in its sessionStore, and sends them back on later calls. A client built without one (as the generated Blocks builds it when you pass no sessionStore:) uses the default store:

  • With blocks_runtime_flutter in a Flutter app, a PersistentSessionStore over the platform's secure storage, registered automatically and shared by every client. The session survives an app restart.
  • Otherwise, a new InMemorySessionStore for each client. On the web that is all there is to it: the browser keeps the session cookies (for a backend on the app's own origin) and never shows them to Dart.

A pure Dart program keeps its session across runs by registering a store before it builds any client. Registering a different store once a client has the default throws a StateError, because two stores over the same storage would overwrite each other's cookies; registering the same function again does nothing, and registerDefaultSessionStore(null) (for tests) is always allowed:

import 'package:blocks_runtime/blocks_runtime.dart';

void main() {
  registerDefaultSessionStore(
    () => PersistentSessionStore(
      store: FileTokenStore(applicationId: 'com.example.notes_cli'),
    ),
  );
  final client = BlocksClient(baseUrl: 'https://your-api.example.com/cdk-blocks/api');
  print(client.sessionStore is PersistentSessionStore); // true
}

applicationId keeps this program's session apart from every other program run by the same OS user, so pick a value unique to your program and keep it. FileTokenStore writes to ~/.blocks/<applicationId>/dart/ without encryption, in an owner-only directory and owner-only files on Linux and macOS.

Pass sessionStore: InMemorySessionStore() to keep one client's session in memory only, or call registerDefaultSessionStore(null) to go back to the in-memory default for every client.

A PersistentSessionStore reads its storage before it returns the first Cookie header from cookieHeaderFor, so you don't call load() yourself. It writes to its TokenStore in the background, only when a cookie actually changes. A program that calls exit right after signing in awaits flush() first, or the new cookie may not be written:

final session = PersistentSessionStore(
  store: FileTokenStore(applicationId: 'com.example.notes_cli'),
);
registerDefaultSessionStore(() => session);
// ... sign in ...
await session.flush();

A read or write that fails never throws into your app: the session keeps working from memory. The error goes to the store's onPersistError callback; without one it is logged with dart:developer's log (name blocks_runtime.session) and written once to standard error. Only the first failure is reported until storage works again, and a store that could not be read is read again when a cookie changes, or on a call at least 30 seconds after the last failed read, not on every call.

InMemorySessionStore, PersistentSessionStore and FileTokenStore are final classes. For a store of your own, implement SessionStore or TokenStore; in tests, use a PersistentSessionStore over an InMemoryTokenStore rather than a mock.

User-agent attribution

Outbound requests carry an aws-blocks-dart token so AWS telemetry can attribute traffic.

RPC calls send it as x-blocks-user-agent on every platform. The header is not CORS-safelisted, so a browser preflights the call; the CDK Blocks server has allowed it since @aws-blocks/core 0.6.0 (and every @aws-cdk-blocks/core).

On web, presigned uploads, presigned downloads and the WebSocket upgrade do not carry the token. Elsewhere they send it as User-Agent, a header a browser ignores on a request and does not allow on the upgrade.

License

Apache 2.0

Libraries

blocks_runtime
CDK Blocks Runtime — JSON-RPC 2.0 client, WebSocket realtime, and transferables.