Skip to content

About

[14/16 · Flutter Studio] 🔑 Drop-in Flutter package for managing a Firestore-backed pool of admin API keys with failover, cooldowns, health checks & admin UI.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

admin_api_key_manager

Flutter CI

A drop-in Flutter package for managing a Firestore-backed pool of admin API keys (Gemini / OpenRouter / any OpenAI-compatible /chat/completions endpoint) with automatic failover, cooldowns, periodic health checks, batched error logging, and a ready-made admin UI.

Originally extracted from the SpeakEasy app so it can be reused in any Flutter project without copy-pasting.


Features

  • 🔑 Firestore-backed key pool — add/edit/disable keys from an admin screen; every device syncs live via snapshot listeners.
  • 🔄 Automatic failover — round-robin selection within the highest-priority enabled provider group; slower groups wait in reserve.
  • 🧊 Smart cooldowns — 429 / 5xx / auth failures each get their own cooldown (configurable per provider group), and cooldowns persist across app restarts via Hive.
  • ⚕️ Health checks — proactively pings the primary key so dead keys are caught before users hit them. cooldownUntil(keyId) and getKeyHealth() expose the exact end of a cooldown, so a UI can say "in 4 min".
  • ⚠️ All-keys-failed alert — fires a pluggable callback when every key is exhausted (you wire your own push notification).
  • 📊 Usage & error stats — written back to Firestore so the admin panel shows live numbers.
  • 🖥️ Admin screen — key cards with a health label (healthy / cooling down / has errors / disabled), usage and error counts, per-filter view, masked keys with reveal-per-row, and add/edit/test/delete. Styled entirely from the host app's ColorScheme; the three state colours come from a KeyAdminPalette ThemeExtension you can replace. A static preview lives in design/admin_screen_preview.html.
  • 🔗 Provider-aware form — picking a provider fills in its base URL and model. A URL you typed yourself is never overwritten; you get an explicit "use default" button instead.
  • 🔍 Free Model Explorer — live list of free models from openrouter.ai/api/v1/models (no key needed) with provider filter, search, context-length badge, and one-tap Copy model id + Get API key + Use model (opens the admin key form).

Installation

Compatibility

Supported
cloud_firestore 5.x and 6.x
firebase_core 3.x and 4.x
Dart / Flutter Dart ^3.3, Flutter >= 3.19

The Firestore constraint is intentionally wide: the package only touches long-stable API surface, and pinning a single major stopped it installing alongside apps already on Firestore 6.

Option A — Git dependency (easiest)

dependencies:
  admin_api_key_manager:
    git:
      url: https://github.com/Keshab1997/admin_api_key_manager
      ref: master

Option B — Local path

dependencies:
  admin_api_key_manager:
    path: ../admin_api_key_manager

Then:

flutter pub get

Pinning

ref: master follows every push to this repository. Two apps depend on this package, so an unrelated change here reaches all of them at once. Once a release is tagged, pin the tag instead:

    git:
      url: https://github.com/Keshab1997/admin_api_key_manager
      ref: v1.2.0

Setup

In main.dart, after Firebase.initializeApp() and HiveFlutter.init():

import 'package:admin_api_key_manager/admin_api_key_manager.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  await HiveFlutter.init();          // or Hive.initFlutter()

  // Opens the package's own Hive box itself and is safe to await. Calling
  // KeyCache.init() first is optional. (Before 1.2.1 leaving it out threw a
  // StateError from inside the first cache read, and left the manager
  // un-initialized for the rest of the process.)
  await ApiKeyManager.instance.initialize();

  // optional: your own push notification when all keys fail
  ApiKeyManager.instance.onAllKeysFailed = (keyCount, message) {
    // send your OneSignal / FCM push here
  };

  runApp(const MyApp());
}

Using a key

final key = ApiKeyManager.instance.getNextKey();
if (key == null) {
  // no healthy key available
  return;
}

try {
  final response = await http.post(
    Uri.parse('${key.baseUrl}/chat/completions'),
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ${key.key}',
    },
    body: jsonEncode({
      'model': key.model,
      'messages': [{'role': 'user', 'content': 'Hello'}],
    }),
  );

  if (response.statusCode == 200) {
    ApiKeyManager.instance.reportSuccess(key);
  } else {
    ApiKeyManager.instance.reportFailure(
      key, response.statusCode, 'my_feature', userId);
  }
} catch (e) {
  ApiKeyManager.instance.reportFailure(key, 0, 'my_feature', userId);
}

Use ApiKeyManager.instance.ensureReady() at startup if you make a call immediately after launch, to avoid racing the Firestore listener.


Opening the admin screen

Gate this behind your own admin check, then:

Navigator.of(context).push(
  MaterialPageRoute(builder: (_) => const AdminApiKeysScreen()),
);

Theming it

The screen reads every colour from ColorScheme, so it inherits the app's theme. The three state colours are the one exception, and they are a ThemeExtension — register your own and the defaults disappear:

MaterialApp(
  theme: ThemeData(
    colorSchemeSeed: const Color(0xFF1B6EF3),
    extensions: const <ThemeExtension<dynamic>>[
      KeyAdminPalette(
        healthy: Color(0xFF43E0A0),
        attention: Color(0xFFFFB545),
        danger: Color(0xFFFF5D6C),
      ),
    ],
  ),
  // ...
);

Register nothing and KeyAdminPalette.fallback is used, so the screen never depends on the host having heard of this package.


Firestore structure

admin_api_keys (doc id = auto or custom)

{
  "name": "Primary OpenRouter",
  "key": "sk-or-...",
  "baseUrl": "https://openrouter.ai/api/v1",
  "model": "gpt-4o-mini",
  "provider": "openrouter",     // google | openrouter | custom
  "isActive": true,
  "priority": 1,
  "usageCount": 0,
  "errorCount": 0
}

admin_key_groups (doc id = provider)

{
  "name": "OpenRouter",
  "enabled": true,
  "priority": 1,
  "rateLimitCooldownSeconds": 60,   // optional
  "serverErrorCooldownSeconds": 120, // optional
  "defaultCooldownSeconds": 30       // optional
}

Also used (optional)

  • api_error_logs — batched failure logs (auto-cleaned after 30 days).
  • admin_alerts — outage banner when all keys fail.

Firestore rules (sketch)

Allow reads for all users, but only admin writes/deletes on admin_api_keys and admin_key_groups. Non-admin devices fail their writes silently, which is fine — the first admin device to hit a failure threshold does the deactivation.

Read this before shipping the rules

The rule sketch above — every signed-in client may read admin_api_keys — means the API keys ship to every device. Anyone who installs the app can read them out of Firestore and spend your provider quota; the admin UI is protected, the secrets are not.

That is a deliberate MVP trade-off, not an oversight. The full analysis — what it costs, what moves where, and a five-step migration that never leaves a device broken — is in docs/API_SECURITY.md. In short, it has a direction of travel: the endpoint that needs protecting is the AI call itself. A proxy (e.g. a Cloud Function) that holds the keys server-side and exposes POST /reply is the fix, and when that exists this package's selection, cooldown and health-check logic belongs behind it, not on the client. Until then, keep the key pool on keys you can afford to lose and rotate them if a build leaks.


Error log (admin UI)

AdminErrorLogsScreen reads api_error_logs — the collection the manager has always filled in batches. Read-only by design: the manager's own 30-day sweep (and a Firestore TTL policy, if you enable one) is what deletes rows, so a screen cannot be the thing that loses the evidence for a report.

It groups by failure kind (rate limit / auth / server / network / other) with counts, and shows time-ago, key name and feature per row. No message text is in these documents, by design.

Navigator.of(context).push(MaterialPageRoute(
  builder: (_) => const AdminErrorLogsScreen(),
));

Bulk actions and failover order

The key screen's overflow menu can enable/disable every key in one Firestore batch, and delete the keys that are both disabled and erroring (a disabled key with a clean record is probably parked on purpose, so the one irreversible action never takes it).

"Reorder failover" is a mode: drag the rows, then save. Positions become priority 1, 2, 3… across the pool, written in one batch, and only rows whose number actually changed are updated. Cancelling writes nothing.

Provider groups (admin UI)

AdminKeyGroupsScreen writes admin_key_groups — enable/disable a provider, rank it, and override the three cooldown durations. The key screen links to it from the app bar. Optional: the collection has always been read by ApiKeyManager, so leaving the screen out only means those values stay hand-edited in the console.

Navigator.of(context).push(MaterialPageRoute(
  builder: (_) => const AdminKeyGroupsScreen(),
));

An empty cooldown field means "use the built-in default" (429 → 60s, 5xx → 120s, other → 30s), which is deliberately different from 0.

Free Model Explorer

AdminFreeModelsScreen fetches openrouter.ai/api/v1/models (public, no key) and shows every free model with provider, context length and a FREE badge. Search by id/name/provider, filter by provider, Free only chip, and one-tap actions: Copy model id, Get API key (opens the provider's key page) and Use model (pushes AdminApiKeysScreen so you paste only the key).

Navigator.of(context).push(
  MaterialPageRoute(builder: (_) => const AdminFreeModelsScreen()),
);

The AppBar of AdminApiKeysScreen already has a 🔍 Free models button — no extra wiring needed. For a cached catalogue, wrap FreeModelDiscovery().fetchFree() in your own Cloud Function / Firestore doc and pass the list in.

Free sources — where the free keys actually come from

The screen has two tabs. Catalog is the live OpenRouter list above; Free sources is lib/models/free_source.dart, a hand-curated directory of the places that hand out free model access — first-party free tiers (Google AI Studio, Groq, Cerebras, Mistral, Cloudflare Workers AI, Cohere, NVIDIA NIM, GitHub Models, Hugging Face) and gateways (OpenRouter, NaraRouter).

The directory is deliberately data, not scraping: every entry carries the OpenAI-compatible base URL, a link to the page that owns its limits, and the day a human last checked it. Allowances move weekly — NaraRouter cut its free plan from ten models to one inside a fortnight — so the number in the chip is a snapshot and the link is the truth. Anything that is not first-party is flagged RELAY ⚠, because a gateway forwarding your prompt upstream may log or train on it; no student data belongs there.

Adding a source is one const entry:

FreeSource(
  id: 'my-gateway',
  name: 'My Gateway',
  kind: FreeSourceKind.gateway,
  freeAllowance: '2M tokens/day',
  baseUrl: 'https://api.my-gateway.dev/v1',
  keyUrl: 'https://api.my-gateway.dev/keys',
  infoUrl: 'https://api.my-gateway.dev/docs/limits',
  dailyTokens: 2000000,
  relay: true,
  verifiedOn: '2026-11-26',
),

Watching the catalog without opening the app

tool/free_model_radar.py answers "did anything new appear while I was not looking?" — no key, no dependency, cron-shaped:

python3 tool/free_model_radar.py            # + new / - gone since the snapshot
python3 tool/free_model_radar.py --update   # accept today's catalog as the baseline
python3 tool/free_model_radar.py --all      # every free model with its context
python3 tool/free_model_radar.py --telegram # push the news (needs TELEGRAM_BOT_TOKEN + TELEGRAM_CHAT_ID)

It compares tool/free_models_snapshot.json with the live catalog and prints nothing when nothing changed.

The daily job

.github/workflows/free-model-radar.yml runs it every day at 02:30 UTC (08:00 IST) and on demand (Actions → Free model radar → Run workflow). No API key, no Flutter SDK, no commit back to master:

  • the snapshot lives in the Actions cache, not in git — a daily commit would queue a full Flutter CI run every morning and open a downstream PR in every app that pins this package;
  • the run's summary shows the count and every added/gone model id, so the Actions page is readable without digging into logs;
  • a transient catalog failure is retried three times before the run goes red.

To get the news pushed to Telegram, add two repository secrets (Settings → Secrets and variables → Actions):

Secret Where it comes from
TELEGRAM_BOT_TOKEN @BotFather → /newbot
TELEGRAM_CHAT_ID message your bot, then read https://api.telegram.org/bot<TOKEN>/getUpdates

Without them the step prints telegram skipped or failed and the run still succeeds — the news stays in the job summary.

To prove the wiring without waiting for a free model to appear: Actions → Free model radar → Run workflow → force_notify: true. That sends one test message with the current free-model count, and the step log prints radar: sent.

Example

A runnable host app lives in example/ — Firebase.initializeApp() → Hive.initFlutter() → ApiKeyManager.instance.initialize() with three buttons for the admin screens. See example/README.md.

Changelog

See CHANGELOG.md.

Configuration

All collection names are configurable on the singleton:

ApiKeyManager.instance.keysCollection = 'admin_api_keys';
ApiKeyManager.instance.groupsCollection = 'admin_key_groups';
ApiKeyManager.instance.errorLogsCollection = 'api_error_logs';

License

MIT — see LICENSE.

About

[14/16 · Flutter Studio] 🔑 Drop-in Flutter package for managing a Firestore-backed pool of admin API keys with failover, cooldowns, health checks & admin UI.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages