Integration guides

Flutter with Firebase

Complete path for a Flutter app with Firebase Authentication and Cloud Functions as the backend.

The login is Firebase Authentication. The Firebase UID is the externalUserId at Limenia (required if you also use the Firebase connector).

This path does the five things every integration does (see Choose your path): forward reports, return the user’s own status, receive webhooks, apply the actions and forward complaints.

Backend: Cloud Functions (2nd gen)

Start from firebase-cloud-functions/ of the examples repo:

Shell
git clone https://github.com/DL3KB/limenia-examples.git
cp -R limenia-examples/firebase-cloud-functions/functions/src <your-project>/functions/src/limenia
cd <your-project>/functions
# Node.js 22, firebase-admin and firebase-functions (see the example's package.json)
firebase functions:secrets:set LIMENIA_API_KEY          # the user types the value, not the agent
firebase functions:secrets:set LIMENIA_WEBHOOK_SECRET
firebase functions:secrets:set DEVICE_CHECK_SECRET      # any random string, only for the device check

LIMENIA_BASE_URL goes into functions/.env (non-secret). The project needs the Blaze plan (secrets and outbound requests). The example exports:

Function Type Calls Limenia
submitReport onCall POST /v1/reports, reporter = request.auth.uid, idempotencyKey in the payload, retries
getMyModerationStatus onCall GET /v1/subjects/{uid}/status for the caller only
requestDeviceHash, checkDevice onCall POST /v1/devices/check (see Device checks)
limeniaWebhook onRequest, public called by Limenia; signature over req.rawBody, dedupe in the Cloud Firestore collection limeniaWebhookEvents, all event types

Errors reach the app as HttpsError with details: { status, problem, retryAfter, idempotencyKey }, where problem is Limenia’s problem body. A 401 from Limenia (wrong API key) becomes internal, so the app does not sign the user out.

The webhook function

The heart of the webhook function (from functions/src/index.js):

JavaScript
export const limeniaWebhook = onRequest(
  { secrets: [LIMENIA_WEBHOOK_SECRET], invoker: "public", timeoutSeconds: 10, cors: false },
  async (req, res) => {
    if (req.method !== "POST") return void res.status(405).end();
    try {
      // req.rawBody: the exact bytes Limenia signed. Never use JSON.stringify(req.body).
      verifySignature({ header: req.get("Limenia-Signature"), rawBody: req.rawBody, secrets: [LIMENIA_WEBHOOK_SECRET.value()] });
    } catch (err) {
      if (err instanceof WebhookSignatureError) return void res.status(401).json({ code: err.code });
      throw err;
    }
    let event;
    try {
      event = JSON.parse(req.rawBody.toString("utf8"));
    } catch {
      return void res.status(400).json({ code: "invalid_body" });
    }
    try {
      await withDeadline(handleEvent(event, { store: firestoreEventStore(), actions }), 8_000);
      res.status(204).end();
    } catch (err) {
      logger.error("webhook failed", { eventId: event.id }); // IDs only
      res.status(503).end(); // Limenia retries
    }
  },
);

Add complaints

The example has no complaint function. Add one next to submitReport in index.js (same helpers requireUid, idempotencyKey, callLimenia, limenia):

JavaScript
// data: { decisionId, appellant: { type }, text, externalAppealId?, idempotencyKey }
export const submitAppeal = onCall({ secrets: [LIMENIA_API_KEY], timeoutSeconds: 120 }, async (request) => {
  const uid = requireUid(request);
  const d = request.data ?? {};
  const appeal = {
    decisionId: d.decisionId,
    appellant: { type: d.appellant?.type, externalUserId: uid }, // the person from the login, never from the app
    text: d.text,
    externalAppealId: d.externalAppealId,
  };
  const key = idempotencyKey("appeal", d.idempotencyKey);
  const created = await callLimenia(
    () => limenia().request("POST", "/v1/appeals", { body: appeal, idempotencyKey: key }),
    { idempotencyKey: key },
  );
  // Remember who complained, so only this person gets the status and the answer later.
  await getFirestore().collection("limeniaAppeals").doc(created.appealId).set({ uid });
  return created;
});

Deploy

Deploy with firebase deploy --only functions. Enter the URL of limeniaWebhook as the webhook URL in the dashboard and press Send test webhook (see Testing). Add a Cloud Firestore TTL policy on expireAt of limeniaWebhookEvents. With LIMENIA_DISABLE_FIREBASE_USERS=true the example disables the Firebase user on ban_user/suspend_user; leave it off if you use Limenia’s Firebase connector instead.

App: Flutter

Add the packages:

YAML
dependencies:
  limenia: ^0.12.0          # API (models, validation, queue, status) and ready-made widgets
  limenia_device: ^0.1.1    # optional: device token for the device connector
  cloud_functions: any      # keep the version your app already uses

Tip: Or run flutter pub add limenia (and flutter pub add limenia_device only with the device connector). Both packages are on pub.dev; limenia needs Flutter 3.35 or newer, limenia_device Flutter 3.24. Import the API from package:limenia/limenia.dart and the widgets (report sheet, complaint form, statement of reasons, notice for restricted accounts) from package:limenia/ui.dart. Pure Dart programs without Flutter (e.g. a Dart server) stay on limenia 0.11.x, which has no widgets. See SDKs and tools.

Transport over callable functions

Implement LimeniaTransport against the callable functions. The package queues and retries reports and complaints; the transport only maps errors:

Dart
import 'package:cloud_functions/cloud_functions.dart';
import 'package:limenia/limenia.dart';

final class LimeniaCallableTransport implements LimeniaTransport {
  LimeniaCallableTransport(this._functions); // FirebaseFunctions.instanceFor(region: '<region of your functions>')

  final FirebaseFunctions _functions;

  
  Future<ReportReceipt> createReport(ReportRequest request, {required String idempotencyKey}) async =>
      ReportReceipt.fromJson(await _call('submitReport', {...request.toJson(), 'idempotencyKey': idempotencyKey}));

  
  Future<SubjectStatus> getSubjectStatus(String externalUserId) async =>
      SubjectStatus.fromJson(await _call('getMyModerationStatus', const {})); // always the caller

  
  Future<AppealReceipt> createAppeal(AppealRequest request, {required String idempotencyKey}) async =>
      AppealReceipt.fromJson(await _call('submitAppeal', {...request.toJson(), 'idempotencyKey': idempotencyKey}));

  // Add functions like submitAppeal when you use these features (see the API reference).
  
  Future<AppealStatusInfo> getAppealStatus(String appealId) => throw UnimplementedError('getAppealStatus');
  
  Future<ReviewReceipt> createReview(ReviewRequest request, {required String idempotencyKey}) =>
      throw UnimplementedError('createReview');
  
  Future<ReviewStatusInfo> getReviewStatus(String reviewId) => throw UnimplementedError('getReviewStatus');
  
  Future<SignalsReceipt> createSignals(SignalsRequest request, {required String idempotencyKey}) =>
      throw UnimplementedError('createSignals');
  
  Future<DeviceCheckResult> checkDevice(DeviceCheckRequest request) =>
      throw UnimplementedError('use requestDeviceHash/checkDevice directly, see below');

  Future<JsonMap> _call(String name, Map<String, Object?> data) async {
    try {
      final result = await _functions
          .httpsCallable(name, options: HttpsCallableOptions(timeout: const Duration(seconds: 130)))
          .call<Object?>(data);
      return Map<String, Object?>.from(result.data! as Map);
    } on FirebaseFunctionsException catch (e) {
      // The functions put Limenia's status, problem body and Retry-After into `details`.
      final details = e.details is Map ? Map<String, Object?>.from(e.details as Map) : const <String, Object?>{};
      final status = details['status'] is int ? details['status'] as int : _status(e.code);
      throw LimeniaException.fromResponse(status: status, body: details['problem'], retryAfter: details['retryAfter']?.toString());
    }
  }

  static int _status(String code) => switch (code) {
        'invalid-argument' || 'failed-precondition' || 'out-of-range' => 400,
        'unauthenticated' => 401, // the request waits in the queue until the user is signed in again
        'permission-denied' => 403,
        'not-found' => 404,
        'already-exists' || 'aborted' => 409,
        'resource-exhausted' => 429,
        'unavailable' => 503,
        'deadline-exceeded' => 504,
        _ => 500,
      };
}

The functions behind the unimplemented methods follow the pattern of submitAppeal: see Complaints, Pre-moderation reviews and Signals.

Use it in the app

Dart
import 'package:limenia/limenia.dart';
import 'package:limenia/ui.dart';

// functionsRegion: the region you deployed your Cloud Functions to.
final limenia = Limenia(transport: LimeniaCallableTransport(FirebaseFunctions.instanceFor(region: functionsRegion)));
await limenia.sendPendingReports(); // at app start: send what is still queued

// Report a comment, with the ready-made report sheet of package:limenia/ui.dart:
await showLimeniaReportSheet(
  context,
  goodFaith: GoodFaithConfirmation.optional,
  onSubmit: (draft) => limenia.report(
    ReportRequest.content(
      reasonCategory: draft.reasonCategory,
      reasonText: draft.reasonText,
      goodFaith: draft.goodFaithConfirmed,
      content: ReportedContent(externalContentId: comment.id, contentType: 'comment', text: comment.text),
      author: ReportedUser(comment.authorUid), // always send the author of reported content
      externalReportId: 'report-${comment.id}-$myUid',
    ),
  ),
);

// The user's own status, e.g. to show a suspension notice:
final watcher = limenia.watchSubject(myUid);
await watcher.refresh(); // after login; call watcher.tryRefresh() when the app resumes

limenia.report(...) never throws on transport errors; it returns ReportSent (with reporterWarning if the reporter was warned), ReportQueued, ReportFailed (e.g. isReporterSuspended with suspendedUntil) or ReportExpired. Show restriction notices with LimeniaRestrictionNotice/LimeniaRestrictionScreen and statements of reasons with LimeniaStatementOfReasonsView (plain text). Complaints: showLimeniaAppealSheet(context, topic: AppealTopic.fromDecision(decision), onSubmit: (text) => limenia.appeal(AppealRequest.subject(decisionId: decision.id, externalUserId: myUid, text: text))).

Device check

Device check with the example’s functions (only if you use the device connector):

Dart
import 'package:flutter/foundation.dart';
import 'package:limenia_device/limenia_device.dart';

final start = await functions.httpsCallable('requestDeviceHash').call<Object?>();
final s = Map<String, Object?>.from(start.data! as Map); // { requestHash, ticket }
final token = await LimeniaDevice.requestToken(
  requestHash: s['requestHash']! as String,
  cloudProjectNumber: 123456789012, // Android: the Cloud project linked to Play Integrity
);
await functions.httpsCallable('checkDevice').call<Object?>({
  'platform': token.platform, // 'android' or 'ios'
  'token': token.token,       // single-use; never store or log it
  'ticket': s['ticket'],
  if (token.platform == 'ios' && kDebugMode) 'environment': 'development',
  'event': 'login',           // registration, login, report or other
});