Clavem

Validate a license key in a Flutter app

Send a POST to /v1/licenses/validate with package:http, give it an 8-second timeout, and read the JSON body whatever the status code is. Draw your UI first, check in the background, and keep the stored token for the days the network fails.

What comes back

Captured on 19 November 2026 from the public demo key. A known key answers 200 even when it is not valid, so read valid, not only the status.

POST /v1/licenses/validate   {"license_key":"S1GNE-TDEM0-7K4QX-9WZ2P-H5RB8"}
200  {"valid":true,"error":null,"license_key":{"id":1,"status":"active","activation_limit":3,
      "activation_usage":1,"expires_at":null,...},"instance":null,"meta":{"product_id":1,...},
      "token":"sgt1.eyJ2IjoxLCJsaWQiOjEsInB..."}

POST ...  {"license_key":"S1GNE-...","instance_id":"00000000-0000-4000-8000-000000000000"}
404  {"valid":false,"error":"instance_id not found.","license_key":{...},"instance":null,...}

Without instance_id the response carries instance: null. With the instance_id you stored at activation, the license has to be active on that device.

The call in Dart

// pubspec.yaml: http, flutter_secure_storage
import 'dart:convert';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:http/http.dart' as http;

const _base = 'https://clavem.io';

class ApiReply {
  const ApiReply(this.status, this.body, [this.retryAfter]);
  final int status; // 0 means no HTTP answer at all
  final Map<String, dynamic> body;
  final Duration? retryAfter;
}

Future<ApiReply> clavemPost(String action, Map<String, String> fields) async {
  try {
    final res = await http
        .post(
          Uri.parse('$_base/v1/licenses/$action'),
          headers: {
            'Content-Type': 'application/json',
            if (!kIsWeb) 'User-Agent': 'Inkwell/3.2', // browsers refuse to set it
          },
          body: jsonEncode(fields),
        )
        .timeout(const Duration(seconds: 8));
    final seconds = int.tryParse(res.headers['retry-after'] ?? ''); // header names arrive lower-cased
    final decoded = jsonDecode(res.body);
    return ApiReply(
      res.statusCode,
      decoded is Map<String, dynamic> ? decoded : {},
      seconds == null ? null : Duration(seconds: seconds),
    );
  } catch (_) {
    return const ApiReply(0, {}); // timeout, offline, DNS, TLS, or a body that is not JSON
  }
}

The catch is deliberate. Several different exceptions mean “no answer” (TimeoutException, ClientException, SocketException, HandshakeException, FormatException), and the app treats them all the same way.

The launch check

enum LicenseState { unlicensed, licensed, invalid, needsNetwork }

class LicenseService {
  LicenseService(this._store, this._tokenIsFresh);
  final FlutterSecureStorage _store;
  // From the offline verification page: verifies the signature and the claims.
  final Future<bool> Function(String token) _tokenIsFresh;

  Future<LicenseState> check() async {
    final saved = await _load();
    if (saved == null) return LicenseState.unlicensed;

    final r = await clavemPost('validate', {
      'license_key': saved['key']!,
      'instance_id': saved['instance']!,
    });
    if (r.status == 200) {
      // Keep the new token even when the license is not valid: offline, it then says so.
      final token = r.body['token'];
      if (token is String) await _save({...saved, 'token': token});
      return r.body['valid'] == true ? LicenseState.licensed : LicenseState.invalid;
    }
    if (r.status == 404) {
      await _clear(); // unknown key, or this device was removed: ask for the key again
      return LicenseState.invalid;
    }
    // 0, 400, 429, 5xx: no usable answer. Trust the stored token while it is fresh.
    return await _tokenIsFresh(saved['token']!) ? LicenseState.licensed : LicenseState.needsNetwork;
  }

  Future<Map<String, String>?> _load() async {
    try {
      final text = await _store.read(key: 'clavem.license');
      return text == null ? null : Map<String, String>.from(jsonDecode(text) as Map);
    } catch (_) {
      return null; // a storage failure reads as "no license", not as a crash
    }
  }

  Future<void> _save(Map<String, String> v) => _store.write(key: 'clavem.license', value: jsonEncode(v));
  Future<void> _clear() => _store.delete(key: 'clavem.license');
}

What each outcome means

Result Meaning App behavior
200, valid: true Active or not yet activated Store the new token. Run.
200, valid: false Expired or disabled Store the token, show error, keep the key. A renewal can revive it.
404 Unknown key, or this device’s activation was removed Clear storage, ask for the key.
400 Your request is malformed Log it. Use the stored token.
429 Over the limit, Retry-After: 60 Use the stored token. Do not retry this launch.
503 Our side, Retry-After: 5 Use the stored token.
status 0 Offline or timed out Use the stored token.

Do not hold up the first frame

Do not await the check in main() before runApp. On a slow network that is up to eight seconds of a blank window. Start it from initState with unawaited(...), draw the normal interface, and move to a locked state only when a LicenseState.invalid or needsNetwork result arrives. Check mounted before setState.

Run it once per process. A WidgetsBindingObserver that validates on AppLifecycleState.resumed will burn through the per-key limit on a laptop that sleeps and wakes.

Where to keep the key

flutter_secure_storage uses the Keychain on iOS and macOS and platform stores on Android, Windows and Linux. Three things break it in practice:

  • macOS and iOS need the Keychain Sharing capability: a keychain-access-groups entry in both DebugProfile.entitlements and Release.entitlements.
  • Linux needs libsecret installed. Catch the exception, as _load does, and ask for the key again rather than crash.
  • Web has no secret store. Anything the page keeps, the user can read.

Release builds that cannot reach the network

Debug works, release does not. Flutter’s docs say Android needs android.permission.INTERNET in the main manifest, and a sandboxed macOS app needs com.apple.security.network.client in both entitlements files. Without it, macOS requests fail with Operation not permitted.

Doing this with Clavem

The License API needs no secret, so nothing sensitive ships in the app. Token verification is in offline verification in Flutter, first-time setup and seats in device activation. Fields and limits are in the API reference.

Questions

Should a Flutter app validate on every app resume?

No. Validate once per launch. The License API allows 60 requests per minute per license key, and a resume handler can fire many times a minute on a phone or a laptop that sleeps and wakes.

Does package:http throw on a 404 or 429?

No. It returns the response for any HTTP status and throws only when there is no answer at all, such as a timeout, a DNS failure or a TLS error. Read statusCode and the body yourself.

Sources

  1. Flutter docs, networking permissions for Android and macOS (checked November 2026)
  2. flutter_secure_storage on pub.dev (checked November 2026)