# Limenia developer documentation

> Everything a developer or coding agent needs to integrate an app with Limenia, in one file: every page of https://limenia.eu/docs/ in navigation order. API version 0.33.0. OpenAPI specification: https://limenia.eu/openapi/v1.yaml.

## Contents

- Getting started
  - [Overview](#overview): What Limenia does for your app, how a report becomes a decision, and the hard rules of every integration.
  - [Quickstart](#quickstart): Set up an app in the dashboard, configure your backend, and send your first report and webhook in a few minutes.
  - [Concepts](#concepts): The terms of Limenia — tenant, app, API key, user file, content, report, case, decision, complaint, review request, signal, rule, policy, reporter and trusted flagger.
  - [Choose your path](#choose-your-path): Pick the integration guide for your app and backend, and see the five things every integration does.
- Integration guides
  - [Flutter with Firebase](#flutter-with-firebase): Complete path for a Flutter app with Firebase Authentication and Cloud Functions as the backend.
  - [Flutter with Supabase](#flutter-with-supabase): Complete path for a Flutter app with Supabase Auth and Supabase Edge Functions as the backend.
  - [Node.js with Express](#nodejs-with-express): Complete path for a Node.js backend with Express, based on the reference example.
  - [Go](#go): Complete path for a Go backend with the standard library only.
  - [Python with FastAPI](#python-with-fastapi): Complete path for a Python backend with FastAPI and httpx.
  - [PHP with Laravel](#php-with-laravel): Complete path for a Laravel 11 backend with drop-in files for the client, the controllers and the webhook.
  - [AWS Lambda](#aws-lambda): Complete path for a Node.js function on AWS Lambda behind a function URL or API Gateway.
  - [Any other backend](#any-other-backend): What to build with any HTTP client and HMAC library when there is no example for your stack.
- API reference
  - [API basics](#api-basics): Base URL, API keys, versioning, idempotency, errors, rate limits, limits, pagination and timestamps of the /v1 API.
  - [Reports](#reports): POST /v1/reports — report content or a user, with categories, media handling and how reports become cases.
  - [Users](#users): PUT /v1/subjects/{externalUserId} and GET /v1/subjects/{externalUserId}/status — display names and the sanction status of a user.
  - [Complaints](#complaints): POST /v1/appeals and GET /v1/appeals/{appealId} — complaints against decisions (Art. 20 DSA), reporters and misuse.
  - [Pre-moderation reviews](#pre-moderation-reviews): POST /v1/reviews and GET /v1/reviews/{reviewId} — have content checked before you publish it.
  - [Signals](#signals): POST /v1/signals — send observations about users that the tenant's rules turn into cases, priorities or flags.
  - [Device checks](#device-checks): POST /v1/devices/check — check the device of a user at registration and login with Play Integrity or DeviceCheck.
  - [Ban evasion across apps](#ban-evasion-across-apps): The optional identifiers field — HMACs of e-mail address and phone number that link the user files of a tenant's apps. Coming soon.
  - [RevenueCat webhook receiver](#revenuecat-webhook-receiver): POST /v1/integrations/revenuecat/{tenantId}/{appId} — the endpoint RevenueCat calls; not called by your backend.
  - [OpenAPI specification](#openapi-specification): The machine-readable description of every /v1 operation and webhook event, and how to use it.
- Webhooks
  - [Receiving webhooks](#receiving-webhooks): How Limenia calls your webhook — headers, signature check with test vector, retries, ordering, applying actions and showing the statement of reasons.
  - [Webhook events](#webhook-events): Every webhook event with an example payload — decision.created, subject.status_changed, reports.resolved, appeal.resolved, review.decided and test.ping.
- Connectors
  - [Firebase connector](#firebase-connector): Let Limenia disable and enable Firebase Authentication accounts directly when moderators suspend, ban or restore a user.
  - [Supabase connector](#supabase-connector): Let Limenia ban and unban Supabase Auth users directly when moderators suspend, ban or restore a user.
  - [RevenueCat connector](#revenuecat-connector): Let Limenia revoke promotional entitlements and end web subscriptions of banned users, and detect ban evasion through purchase transfers.
  - [Device connector](#device-connector): Tie bans to devices without fingerprinting, with Play Integrity Device Recall on Android and Apple DeviceCheck on iOS.
  - [Store reviews](#store-reviews): Collect and answer the reviews of your app in the App Store and Google Play in Limenia — what you set up in App Store Connect, the Play Console and optionally GitHub.
- Compliance
  - [DSA](#dsa): What the Digital Services Act asks of your app, what Limenia does for you and what remains your job — notice and action, statements of reasons, complaints, trusted flaggers and transparency.
  - [Data protection](#data-protection-2): What to send to Limenia and what not, how reporters are pseudonymised, how long data is kept and where it is hosted.
- SDKs and tools
  - [SDKs and tools](#sdks-and-tools): Flutter packages limenia and limenia_device, the example backends, typed clients from the OpenAPI spec, llms.txt and the prompt for coding agents.
- Testing and go-live
  - [Testing](#testing): How to test an integration safely — a test app, self-tests a coding agent can run, the dashboard's webhook test and an end-to-end check.
  - [Go-live checklist](#go-live-checklist): Everything to check before your app goes live with Limenia — setup, reports, webhooks, complaints, optional features and operations.
  - [Troubleshooting](#troubleshooting): Common errors when integrating Limenia and how to fix them — API answers, webhook signatures, deliveries, connectors and media.
  - [FAQ](#faq): Short answers to the questions developers ask most when integrating Limenia.
  - [Changelog](#changelog): Changes of the public API (/v1 and webhook events), newest first.

---

# Overview

What Limenia does for your app, how a report becomes a decision, and the hard rules of every integration. (https://limenia.eu/docs/overview/)

Limenia is a moderation service for apps under the EU Digital Services Act (DSA). Your app backend sends user reports (and, optionally, content for review before publication) to the Limenia REST API, moderators decide in the Limenia dashboard, and Limenia sends every decision with a ready-made statement of reasons back to your backend as a signed webhook. Your content and your users stay in your app; Limenia keeps only what you send with a report.

| | |
|---|---|
| Base URL | `https://app.limenia.eu/v1` |
| API version | 0.33.0 |
| OpenAPI specification | <https://limenia.eu/openapi/v1.yaml> (the `/v1` operations, webhook events under `x-webhooks`) |
| All pages in one file (for coding agents) | <https://limenia.eu/docs/integration.md> |
| All pages and the spec in one file | <https://limenia.eu/llms-full.txt> |
| Example backends (Apache 2.0) | <https://github.com/DL3KB/limenia-examples> |
| Flutter package `limenia` (API and widgets) | <https://pub.dev/packages/limenia> |
| Flutter device plugin `limenia_device` (optional) | <https://pub.dev/packages/limenia_device> |
| Source of both Flutter packages (Apache 2.0) | <https://github.com/DL3KB/limenia-flutter> |

This documentation is written so that a coding agent (Claude Code, Cursor, Copilot) can read it once and integrate an app correctly. Start with the [Quickstart](#quickstart), pick your stack in [Choose your path](#choose-your-path), and finish with [Testing](#testing) and the [go-live checklist](#go-live-checklist).

## Hard rules

> **Important:** Follow these in every integration. They override anything else in this documentation.

1. **The API key lives in the backend only.** Read it from the environment variable `LIMENIA_API_KEY` (or the platform's secret store that fills it). Never put it in the mobile or web app, in a config file shipped with the app, in remote config, in source control or in logs. Never ask the user to paste the key into the chat: ask them to set the environment variable or secret themselves and refer to `$LIMENIA_API_KEY`. The same holds for the identifier key `LIMENIA_IDENTIFIER_KEY` of [ban evasion across apps](#ban-evasion-across-apps).
2. **The app talks to its own backend only, never to Limenia.** In Flutter, implement `LimeniaTransport` of the Flutter package `limenia` so that it calls your backend. Your backend calls Limenia.
3. **The backend sets the people.** `reporter.externalUserId` of a report, `appellant.externalUserId` of a complaint, the author (`subject`) of a review request and the `externalUserId` of a device check come from your backend's own login, never from the request body of the app. Use a stable internal user ID, never an e-mail address.
4. **Verify every webhook.** The webhook secret is in `LIMENIA_WEBHOOK_SECRET`. Check the header `Limenia-Signature: t=<unix seconds>,v1=<hex>` where `v1 = hex(HMAC-SHA256(secret, t + "." + rawBody))`, computed over the **raw** request body exactly as received (never re-serialized JSON), compared in **constant time**, and reject a `t` more than **300 seconds** away from your clock. Answer 401 on a failed check. Details in [Webhooks](#verifying-the-signature).
5. **No content and no personal data in logs.** Log IDs (event, decision, report, user IDs) and error codes, never report texts, statements of reasons, names, e-mail addresses, IP addresses, device tokens or media URLs.
6. **Use idempotency keys as the API defines them.** `POST /v1/reports`, `POST /v1/appeals`, `POST /v1/reviews` and `POST /v1/signals` require the header `Idempotency-Key` (1 to 200 characters). Create one key per logical request (e.g. `report-<your report ID>`), store it with the request, and send the same key with the same body on every retry. Never reuse a key for a different body (409 `idempotency_key_reused`). `POST /v1/devices/check` takes no key and is never retried with the same token.
7. **Respect rate limits and `Retry-After`.** Retry network errors, timeouts, 429 and 5xx with exponential backoff (1, 2, 4, 8 s), and on 429 or 503 wait at least the seconds in `Retry-After`. Never retry other 4xx answers unchanged.

## How it works

User reports something in your app → your app sends it to your backend with your own login → your backend calls `POST /v1/reports` with the API key → a moderator decides in the Limenia dashboard → Limenia sends the signed webhook `decision.created` to your backend (and, with optional connectors, acts in Firebase Authentication, Supabase Auth or RevenueCat) → your backend applies the action (remove content, suspend user, …) and shows the statement of reasons.

1. Your backend sends each report with a snapshot of the content to `POST /v1/reports` ([Reports](#reports)).
2. Limenia bundles reports on the same content into one case while it is open or in review. Reports without content are bundled per reported user. Media are downloaded in the background.
3. A moderator decides. Every decision has exactly one action and a statement of reasons (Art. 17 DSA).
4. Limenia sends `decision.created` to your webhook ([Webhook events](#webhook-events)). Optional [connectors](#firebase-connector) also disable accounts in Firebase Authentication or Supabase Auth and adjust purchases in RevenueCat.
5. When a temporary suspension ends, Limenia sends `subject.status_changed`.
6. If the case had reports of users, Limenia also sends `reports.resolved` so you can inform the reporters (Art. 16(5) DSA).
7. Affected users and reporters can complain against a decision for six months through your backend (`POST /v1/appeals`, Art. 20 DSA, see [Complaints](#complaints)). The result comes as `appeal.resolved`.
8. Content that should only appear after a check goes to `POST /v1/reviews` before you publish it ([Pre-moderation reviews](#pre-moderation-reviews)). The result comes as `review.decided`.
9. With the device connector, your backend checks the device at registration and login (`POST /v1/devices/check`, see [Device checks](#device-checks)).
10. Signals (`POST /v1/signals`, see [Signals](#signals)) are observations about users that the tenant's rules can turn into cases.

The terms used here (tenant, app, case, decision, user file, policy, rule and so on) are explained in [Concepts](#concepts).

## What Limenia stores

| Limenia stores | Stays in your app |
|---|---|
| Snapshot of the reported content: text, context, link, copies of media | The content itself and everything else |
| Reports: reason, free text, source; the reporter only as a hash | Who reported what |
| Reported users: your external user ID, display name, sanction status | Accounts, profiles, e-mail addresses |
| Cases, decisions, statements of reasons, audit log, delivery log | Carrying out the actions (delete, block, notify) |
| Complaints, review requests with a copy of the submitted content | Publishing content, notifying people |

More in [Data protection](#data-protection-2).

## How this documentation is organised

| Section | What you find there |
|---|---|
| Getting started | This overview, the [Quickstart](#quickstart), [Concepts](#concepts) and [Choose your path](#choose-your-path) |
| Integration guides | One complete path per stack, from [Flutter with Firebase](#flutter-with-firebase) to [any other backend](#any-other-backend) |
| API reference | [API basics](#api-basics) (keys, errors, limits, idempotency) and one page per group of `/v1` operations |
| Webhooks | [Receiving webhooks](#receiving-webhooks) and [every event with its payload](#webhook-events) |
| Connectors | [Firebase](#firebase-connector), [Supabase](#supabase-connector), [RevenueCat](#revenuecat-connector), [devices](#device-connector) and [store reviews](#store-reviews) |
| Compliance | [DSA](#dsa) and [data protection](#data-protection-2): what your app must do and what Limenia does |
| SDKs and tools | [Packages, examples, the spec and llms.txt](#sdks-and-tools) |
| Testing and go-live | [Testing](#testing), [go-live checklist](#go-live-checklist), [troubleshooting](#troubleshooting), [FAQ](#faq) and [changelog](#changelog) |

---

# Quickstart

Set up an app in the dashboard, configure your backend, and send your first report and webhook in a few minutes. (https://limenia.eu/docs/quickstart/)

## Set up the app in the dashboard

These steps need a person with the role `admin` or `owner` in the Limenia dashboard at <https://app.limenia.eu>. A coding agent cannot do them; ask the user to do them and to put the resulting values into environment variables or secrets.

1. **Finish the setup wizard** of the tenant. Until it is finished, reports answer 403 `tenant_not_active` (`GET /v1/ping` works already).
2. **Create the app:** **Apps → Create app**, with a name and the backend you use. The slug (lowercase letters, digits, hyphens, at most 40 characters) cannot be changed later and appears in every webhook as `app.slug`. Use a separate test app for testing: there is no sandbox, and every API key writes to the real system (see [Testing](#testing)).
3. **Create an API key:** tab **Connection → API keys → Create API key**. The key (`lm_live_` plus 43 Base62 characters) is shown exactly once; Limenia stores only its SHA-256 hash. Store it as `LIMENIA_API_KEY` in your backend's secret store. An app can have several keys; to rotate, create a new one, deploy it, then revoke the old one (a revoked key stops working within 30 seconds). See [API keys](#api-keys).
4. **Set the webhook:** tab **Connection → Webhook**, enter your HTTPS URL (at most 2048 characters, public, no private or internal addresses, no redirects) and save. The first save turns the webhook on and shows the signing secret (`whsec_…`) once. Store it as `LIMENIA_WEBHOOK_SECRET`. **Rotate secret** shows a new one once and applies it immediately to all following delivery attempts.
5. **Send test webhook** (same place) sends a `test.ping` once (5 s timeout, no retry; again after 10 s at the earliest) and shows HTTP status, duration and error code.
6. **Supported actions** (tab **General**): restrict the actions moderators can choose to those your app can carry out. `dismiss` is always possible.

> **Important:** Decisions taken while the webhook is not active (no URL or secret, or switched off) are never delivered by webhook, also not after switching it on. Reconcile users with `GET /v1/subjects/{externalUserId}/status` if that happened.

The app page has the tabs **Overview**, **General**, **Connection** (API keys, webhook), **Connectors** (Firebase, Supabase, RevenueCat, device connector, store reviews), **Moderation** (approval types, signal types and rules, AI pre-screening) and **DSA** (store requirements, transparency database). The home page shows a checklist of open setup steps.

## Configure your backend

Every example and every snippet in this documentation uses the same variables:

```bash
LIMENIA_BASE_URL=https://app.limenia.eu        # without /v1, this is the default
LIMENIA_API_KEY=<set by the user, never in code>
LIMENIA_WEBHOOK_SECRET=<set by the user, never in code>
LIMENIA_WEBHOOK_SECRET_PREVIOUS=               # optional, only while rotating the secret
LIMENIA_IDENTIFIER_KEY=                        # optional, only for ban evasion across apps
```

`LIMENIA_IDENTIFIER_KEY` belongs to [ban evasion across apps](#ban-evasion-across-apps), which is coming soon.

## Check the key

Check address and key with one call:

```bash
curl -sS "$LIMENIA_BASE_URL/v1/ping" -H "Authorization: Bearer $LIMENIA_API_KEY"
```

```json
{ "tenantId": "01K6…", "appId": "01K6…", "appSlug": "photoapp", "tenantStatus": "active" }
```

`"tenantStatus":"onboarding"` means the setup wizard is not finished yet. A 401 means the key is wrong or revoked.

## Send a first report

Send it to the test app only:

```bash
curl -sS -X POST "$LIMENIA_BASE_URL/v1/reports" \
  -H "Authorization: Bearer $LIMENIA_API_KEY" -H "Content-Type: application/json" \
  -H "Idempotency-Key: report-quickstart-1" \
  -d '{"source":"user","reasonCategory":"spam","reporter":{"externalUserId":"quickstart_reporter"},"subject":{"externalUserId":"quickstart_author"},"content":{"externalContentId":"quickstart_content_1","contentType":"comment","text":"Limenia quickstart"},"externalReportId":"quickstart_1"}'
```

The answer is `201 Created` with `reportId`, `caseId` and `caseCreated`. The case appears under **Cases** in the dashboard. All fields are in [Reports](#reports).

## Receive the decision

1. Deploy a webhook receiver that verifies the signature (see [Webhooks](#receiving-webhooks); every [integration guide](#choose-your-path) has one) and enter its URL in the dashboard.
2. Press **Send test webhook**: your receiver gets a `test.ping`.
3. Decide the quickstart case in the dashboard, e.g. with `dismiss`. Your receiver gets `decision.created` and `reports.resolved` (see [Webhook events](#webhook-events)).

## Next steps

- Pick the complete path for your stack in [Choose your path](#choose-your-path).
- Read the [Hard rules](#hard-rules) and [API basics](#api-basics).
- Verify everything with [Testing](#testing) and go through the [go-live checklist](#go-live-checklist).

---

# Concepts

The terms of Limenia — tenant, app, API key, user file, content, report, case, decision, complaint, review request, signal, rule, policy, reporter and trusted flagger. (https://limenia.eu/docs/concepts/)

## Tenant

The organisation that uses Limenia, usually the company that runs the apps. Under the DSA the tenant is the provider of the apps and responsible for the decisions; Limenia processes data on its behalf (see [Data protection](#data-protection-2)).

- A tenant starts in the status `onboarding` and becomes `active` when an owner finishes the setup wizard (tenant details, retention, policies, first app, API key). Until then the API answers 403 `tenant_not_active` to reports, complaints, review requests, signals, device checks and updates of users (`PUT /v1/subjects`); `GET /v1/ping` returns `tenantStatus`.
- People in the dashboard have one of four roles: **Owner** (everything, including billing, retention periods and opt-ins), **Admin** (team, apps, API keys, webhooks, connectors, policies, rules, trusted flaggers, delivery log), **Moderator** (decides cases, complaints and reviews, sees user files and media) and **Viewer** (reads cases and settings, no media and no user files). Everyone in the dashboard signs in with a second factor (an authenticator app), whatever the role.

## App

One app of the tenant, for example the iOS and Android app of one product with its backend. Each app has its own API keys, webhook, connectors, review types, signal types and rules.

- The **slug** (lowercase letters, digits and hyphens, at most 40 characters) cannot be changed and appears in every webhook as `app.slug`.
- **Supported actions** restrict the actions moderators can choose to those your app can carry out; `dismiss` is always possible. Decisions on review requests ignore this setting.
- External IDs (`externalUserId`, `externalContentId`) are scoped per app: the same ID in two apps means two different users.
- There is no sandbox. Use a separate app as your **test app** (see [Testing](#testing)).

## API key

The secret your backend sends as `Authorization: Bearer <key>`. A key belongs to exactly one app and determines tenant and app of every request. See [API keys](#api-keys).

## User file

Limenia's record of one user of one app, identified by your `externalUserId`. In the API it is a *subject*. It holds the display name you sent, the sanction status (`active`, `warned`, `suspended` until a date, `banned`), counters of reports and violations, flags set by rules, recent signals and, with the device connector, the device state. Moderators can also decide directly on a user file (`warn_user`, `suspend_user`, `ban_user`, `restore`), without a case. See [Users](#users).

## Content and snapshot

The thing that is reported or submitted, identified by your `externalContentId`. With the first report on a content, Limenia stores a **snapshot**: the text, the context, the link and copies of the media you sent. Later reports do not change it. Limenia never reads content from your app; moderators see only the snapshot. See [Reports](#fields).

## Report

A notice that content or a user may break the rules (Art. 16 DSA). Your backend sends it with `POST /v1/reports`.

- `source: user`: a user of your app reported it. `source: system`: your app detected it itself, or Limenia created it (rules, RevenueCat, ban evasion).
- `reasonCategory` is usually the code of a policy.
- The reporter is stored only as a pseudonym (a hash), never with your user ID.

## Case

The unit moderators work on. Limenia bundles reports into cases:

- Reports on the same content of an app go into one case while it is open or in review. Reports without content are bundled per reported user. After a decision the next report opens a new case.
- Status: `open`, `in_review` (a moderator took it) and `decided`.
- Priority: `normal`, `high` (for example reports of trusted flaggers, ban evasion) or `urgent` (child safety). Rules and the optional AI pre-screening can raise the priority, never lower it.

## Decision

The result of a moderator's work. Every decision has exactly one **action** and a **statement of reasons** (Art. 17 DSA). Removing content and suspending its author are two decisions.

| Action | Effect |
|---|---|
| `dismiss` | No violation, nothing happens |
| `remove_content`, `restrict_content` | Remove or restrict the content |
| `warn_user`, `suspend_user`, `ban_user` | Warn, temporarily block or permanently block the user |
| `restore` | Lift an earlier restriction of the content or the account (`restoreScope`) |
| `reject_submission` | Review requests only: do not publish the submitted content |

The statement of reasons comes as ready-made text in the tenant's language and as structured fields (facts, grounds, whether it was based on a notice, automation, redress). Decisions reach your backend as `decision.created`. See [Webhooks](#applying-actions).

## Complaint

A request of the affected user or of a reporter to review a decision again (internal complaint handling, Art. 20 DSA). In the API it is an *appeal*. Complaints are possible for six months after the decision; a human always decides. The outcome is `upheld` (the decision stays) or `changed` (a new decision replaces it). See [Complaints](#complaints).

## Review request

Content your app wants checked **before** publishing it (pre-moderation), for example profile photos. The dashboard calls them approvals. Each request has a **review type** created per app (code, guidelines, target time) and ends as `approved`, `restricted` or `rejected`. See [Pre-moderation reviews](#pre-moderation-reviews).

Not to be confused with **store reviews**: the ratings of your app in the App Store and Google Play, which the [store reviews connector](#store-reviews) collects.

## Signal and rule

A **signal** is an observation about a user that is not a report: a score jump, implausibly many actions, many new accounts. Your backend sends signals of **signal types** you create per app. A signal alone does nothing.

A **rule** of the app turns signals (or many reports of different people) into an action: open a case, raise the priority of open cases, or flag the user file. Limenia never sanctions because of a rule; a moderator decides. See [Signals](#signals).

## Policy

A rule of the tenant's terms of use or a legal provision a decision can be based on, with a code (e.g. `harassment_hate`), a title and a legal basis (terms or law). Policies are the vocabulary of `reasonCategory` and appear in decisions as `policies[]`. The tenant edits them in the dashboard; they are never deleted, only deactivated. See [Categories](#categories).

## Reporter

The person who sent a report. Limenia knows reporters only as a hash of app and user ID. Moderators can warn reporters who send many unfounded reports and later suspend their reports (Art. 23 DSA). Reporters learn about the outcome through your app (`reports.resolved`). See [Reporters and misuse](#reporters-and-misuse).

## Trusted flagger

An organisation recognised under Art. 22 DSA whose reports get priority. The tenant registers trusted flaggers in the dashboard; your backend marks a report with `trustedFlaggerId` when the reporter acts for one. See [Trusted flaggers](#trusted-flaggers).

## AI pre-screening

Optional, switched on by the owner. A language model assesses reported and submitted content against the tenant's policies, suggests an outcome and can raise the priority. A human always decides; when a moderator confirms a suggestion, the statement of reasons says so (`automation: partial`). Fully automated decisions (`automation: full`) are not used. The model receives the content, not user IDs, names or reporter information.

## Connectors

Optional links to services of the tenant that carry out decisions directly, in addition to the webhook: [Firebase](#firebase-connector), [Supabase](#supabase-connector), [RevenueCat](#revenuecat-connector), the [device connector](#device-connector), and the [store reviews connector](#store-reviews), which collects app store ratings.

---

# Choose your path

Pick the integration guide for your app and backend, and see the five things every integration does. (https://limenia.eu/docs/choose-your-path/)

## Which guide

Is the app a Flutter app? Then pick the guide of its backend: Firebase with Cloud Functions or Supabase with Edge Functions. With another backend, use the Flutter part of those guides (`LimeniaTransport`) together with the guide of your backend. Without a Flutter app, pick the guide of your backend.

| Your stack | Guide |
|---|---|
| Flutter app, Firebase Authentication, Cloud Functions | [Flutter with Firebase](#flutter-with-firebase) |
| Flutter app, Supabase Auth, Edge Functions | [Flutter with Supabase](#flutter-with-supabase) |
| Flutter app with another backend | Flutter part of [Flutter with Firebase](#app-flutter) plus your backend's guide |
| Node.js with Express or a similar framework | [Node.js with Express](#nodejs-with-express) |
| Go | [Go](#go) |
| Python with FastAPI | [Python with FastAPI](#python-with-fastapi) |
| PHP with Laravel | [PHP with Laravel](#php-with-laravel) |
| AWS Lambda | [AWS Lambda](#aws-lambda) |
| Anything else with HTTPS | [Any other backend](#any-other-backend) |

## What every integration does

Every path does the same five things. Check them off when you are done:

1. **Forward reports** from the app to `POST /v1/reports`, reporter from the login, `Idempotency-Key` passed through, retries with backoff ([Reports](#reports)).
2. **Return the user's own status** from `GET /v1/subjects/{externalUserId}/status` (for the signed-in user only, see [Users](#users)).
3. **Receive webhooks**: raw body, signature check, dedupe by event ID, every event type handled ([Webhooks](#receiving-webhooks), [Webhook events](#webhook-events)).
4. **Apply the actions** to your data ([Applying actions](#applying-actions)) and show the statement of reasons to the affected user.
5. **Forward complaints** (`POST /v1/appeals`, see [Complaints](#complaints)), because affected users and reporters have a right to complain. Optionally [reviews](#pre-moderation-reviews), [signals](#signals) and [device checks](#device-checks).

## The example backends

All example backends live in <https://github.com/DL3KB/limenia-examples>. They use plain HTTP and the platform's crypto, no SDK, and contain **placeholders** you must replace: the login stub (it trusts a header `X-User-Id` and refuses to run with `NODE_ENV=production` where applicable) and the action functions (remove content, ban user, notify). Each example also includes the device check (`/devices/request-hash`, `/devices/check`) and tests against the [signature test vector](#test-vector).

If you work with a coding agent, the dashboard has a ready-made prompt for it (see [SDKs and tools](#prompt-for-coding-agents)).

---

# Flutter with Firebase

Complete path for a Flutter app with Firebase Authentication and Cloud Functions as the backend. (https://limenia.eu/docs/guide-firebase/)

The login is Firebase Authentication. The Firebase UID is the `externalUserId` at Limenia (required if you also use the [Firebase connector](#firebase-connector)).

This path does the five things every integration does (see [Choose your path](#what-every-integration-does)): 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](https://github.com/DL3KB/limenia-examples):

```bash
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](#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`):

```js
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`):

```js
// 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](#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](#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](#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;

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

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

  @override
  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).
  @override
  Future<AppealStatusInfo> getAppealStatus(String appealId) => throw UnimplementedError('getAppealStatus');
  @override
  Future<ReviewReceipt> createReview(ReviewRequest request, {required String idempotencyKey}) =>
      throw UnimplementedError('createReview');
  @override
  Future<ReviewStatusInfo> getReviewStatus(String reviewId) => throw UnimplementedError('getReviewStatus');
  @override
  Future<SignalsReceipt> createSignals(SignalsRequest request, {required String idempotencyKey}) =>
      throw UnimplementedError('createSignals');
  @override
  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](#complaints), [Pre-moderation reviews](#pre-moderation-reviews) and [Signals](#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](#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
});
```

---

# Flutter with Supabase

Complete path for a Flutter app with Supabase Auth and Supabase Edge Functions as the backend. (https://limenia.eu/docs/guide-supabase/)

The login is Supabase Auth. The Supabase user ID (`auth.users.id`, the `sub` of the access token) is the `externalUserId` at Limenia (required for the [Supabase connector](#supabase-connector)).

## Backend: Edge Functions (Deno)

Start from `supabase-edge-functions/` of the [examples repo](https://github.com/DL3KB/limenia-examples): copy `supabase/functions` and `supabase/migrations` into your Supabase project.

```bash
supabase link --project-ref <your-project-ref>
supabase db push                       # creates the table limenia_webhook_events (RLS on, no policies)
supabase secrets set LIMENIA_API_KEY=… LIMENIA_WEBHOOK_SECRET=… DEVICE_CHECK_SECRET=…   # values typed by the user
supabase functions deploy limenia-reports
supabase functions deploy limenia-moderation-status
supabase functions deploy limenia-devices
supabase functions deploy limenia-webhook --no-verify-jwt   # Limenia sends no Supabase JWT; the signature authenticates
```

| Function | Calls Limenia |
|---|---|
| `POST /functions/v1/limenia-reports` | `POST /v1/reports`, reporter from the user's JWT, `Idempotency-Key` passed through or generated and echoed |
| `GET /functions/v1/limenia-moderation-status` | `GET /v1/subjects/{id}/status` for the signed-in user only |
| `POST /functions/v1/limenia-devices/request-hash`, `…/check` | `POST /v1/devices/check` |
| `POST /functions/v1/limenia-webhook` | called by Limenia; Web Crypto HMAC over `await req.arrayBuffer()`, dedupe in `limenia_webhook_events` |

### The webhook function

The webhook URL is `https://<project-ref>.supabase.co/functions/v1/limenia-webhook`. The signature check (from `_shared/signature.ts`):

```ts
const rawBody = new Uint8Array(await req.arrayBuffer()); // never JSON.stringify(await req.json())
await verifySignature({ header: req.headers.get("limenia-signature"), rawBody, secrets: [LIMENIA_WEBHOOK_SECRET] });
// verifySignature: split at ",", t exactly once, v1 at least once, |now - t| <= 300,
// HMAC-SHA256(secret, `${t}.` + rawBody) via crypto.subtle, constant-time compare with every v1.
```

With `LIMENIA_BAN_SUPABASE_USERS=true` the example bans the Supabase user on `ban_user` (`ban_duration: "876000h"`) and `suspend_user`, and lifts it (`"none"`) on `restore` with `restoreScope: "account"` and on `subject.status_changed` to `active` or `warned`. Leave it off if you use Limenia's [Supabase connector](#supabase-connector).

### Add complaints

Add a complaint function the same way as `limenia-reports`: forward to `POST /v1/appeals` (see [Complaints](#complaints)), set `appellant.externalUserId` from the JWT, and remember `appealId` per user.

## App: Flutter

Same packages as in the [Firebase guide](#app-flutter) (without `cloud_functions`, with `http` and `supabase_flutter`). A transport over HTTP:

```dart
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:limenia/limenia.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

final class LimeniaSupabaseTransport implements LimeniaTransport {
  LimeniaSupabaseTransport({required this.functionsUrl, required this.anonKey, http.Client? client})
      : _http = client ?? http.Client();

  final String functionsUrl; // https://<project-ref>.supabase.co/functions/v1
  final String anonKey;      // the public anon key of the project, not a secret
  final http.Client _http;

  Map<String, String> _headers({String? idempotencyKey}) {
    final token = Supabase.instance.client.auth.currentSession?.accessToken;
    if (token == null) throw LimeniaException.fromResponse(status: 401); // waits in the queue until login
    return {
      'Authorization': 'Bearer $token',
      'apikey': anonKey,
      'Content-Type': 'application/json',
      if (idempotencyKey != null) 'Idempotency-Key': idempotencyKey,
    };
  }

  @override
  Future<ReportReceipt> createReport(ReportRequest request, {required String idempotencyKey}) async {
    final res = await _http
        .post(Uri.parse('$functionsUrl/limenia-reports'),
            headers: _headers(idempotencyKey: idempotencyKey), body: jsonEncode(request.toJson()))
        .timeout(const Duration(seconds: 60));
    return ReportReceipt.fromJson(_body(res));
  }

  @override
  Future<SubjectStatus> getSubjectStatus(String externalUserId) async {
    final res = await _http.get(Uri.parse('$functionsUrl/limenia-moderation-status'), headers: _headers());
    return SubjectStatus.fromJson(_body(res));
  }

  // createAppeal, getAppealStatus, createReview, getReviewStatus, createSignals, checkDevice:
  // the same pattern against your own functions (throw UnimplementedError until you add them).
  @override
  Future<AppealReceipt> createAppeal(AppealRequest request, {required String idempotencyKey}) =>
      throw UnimplementedError('add a limenia-appeals function');
  @override
  Future<AppealStatusInfo> getAppealStatus(String appealId) => throw UnimplementedError();
  @override
  Future<ReviewReceipt> createReview(ReviewRequest request, {required String idempotencyKey}) =>
      throw UnimplementedError();
  @override
  Future<ReviewStatusInfo> getReviewStatus(String reviewId) => throw UnimplementedError();
  @override
  Future<SignalsReceipt> createSignals(SignalsRequest request, {required String idempotencyKey}) =>
      throw UnimplementedError();
  @override
  Future<DeviceCheckResult> checkDevice(DeviceCheckRequest request) => throw UnimplementedError();

  JsonMap _body(http.Response res) {
    if (res.statusCode >= 200 && res.statusCode < 300) return jsonDecode(res.body) as JsonMap;
    throw LimeniaException.fromResponse(status: res.statusCode, body: res.body, retryAfter: res.headers['retry-after']);
  }
}
```

The rest of the app (report sheet, status, complaints, device check against `limenia-devices/request-hash` and `limenia-devices/check` with the returned `ticket`) works as in the [Firebase guide](#use-it-in-the-app).

---

# Node.js with Express

Complete path for a Node.js backend with Express, based on the reference example. (https://limenia.eu/docs/guide-node/)

The reference example `node-express/` of the [examples repo](https://github.com/DL3KB/limenia-examples) (Node.js 20.6+, the only dependency is Express) covers reports, own status, complaints, reviews, device check and the webhook, including ordering of events by `decidedAt`.

```bash
cd limenia-examples/node-express && npm install && npm test
# the user sets LIMENIA_API_KEY and LIMENIA_WEBHOOK_SECRET (e.g. in .env, never committed)
npm start
```

## Routes

| Route of your backend | Calls Limenia |
|---|---|
| `POST /reports` | `POST /v1/reports` |
| `GET /me/moderation-status` | `GET /v1/subjects/{id}/status` |
| `POST /appeals`, `GET /appeals/:appealId` | `POST /v1/appeals`, `GET /v1/appeals/{appealId}` (status only for the person who complained) |
| `POST /reviews`, `GET /reviews/:reviewId` | `POST /v1/reviews`, `GET /v1/reviews/{reviewId}` (status only for the author) |
| `POST /devices/request-hash`, `POST /devices/check` | `POST /v1/devices/check` |
| `POST /limenia/webhook` | called by Limenia |

Files: `src/limenia.js` (client with retries), `src/signature.js`, `src/events.js` (per event, dedupe, ordering), `src/actions.js` (**placeholders**), `src/auth.js` (**login stub, replace it**), `src/device.js`, `src/app.js`.

## Webhook route

The webhook route must read the raw body, so register it **before** `express.json()`:

```js
app.post("/limenia/webhook", express.raw({ type: () => true, limit: "1mb" }), async (req, res) => {
  const rawBody = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);
  try {
    verifySignature({ header: req.get("Limenia-Signature"), rawBody, secrets: webhookSecrets });
  } catch (err) {
    if (err instanceof WebhookSignatureError) return res.status(401).json({ code: err.code });
    throw err;
  }
  const event = JSON.parse(rawBody.toString("utf8"));
  try {
    await withDeadline(handleEvent(event), 8_000); // Limenia waits 10 s
    res.sendStatus(204);
  } catch {
    res.sendStatus(503); // Limenia retries
  }
});
app.use(express.json({ limit: "1mb" }));
```

`verifySignature` (from `src/signature.js`):

```js
import { createHmac, timingSafeEqual } from "node:crypto";

export function verifySignature({ header, rawBody, secrets, now = Date.now() / 1000 }) {
  if (!header) throw new WebhookSignatureError("missing_signature");
  let timestamp;
  const signatures = [];
  for (const part of header.split(",")) {
    const eq = part.indexOf("=");
    if (eq < 1) throw new WebhookSignatureError("malformed_signature");
    const key = part.slice(0, eq).trim();
    const value = part.slice(eq + 1).trim();
    if (key === "t") {
      if (timestamp !== undefined) throw new WebhookSignatureError("malformed_signature");
      timestamp = value;
    } else if (key === "v1") signatures.push(value);
  }
  if (timestamp === undefined || !/^\d{1,12}$/.test(timestamp) || signatures.length === 0)
    throw new WebhookSignatureError("malformed_signature");
  if (Math.abs(now - Number(timestamp)) > 300) throw new WebhookSignatureError("timestamp_out_of_range");
  for (const secret of secrets) {
    const expected = createHmac("sha256", secret).update(`${timestamp}.`).update(rawBody).digest();
    for (const signature of signatures) {
      if (/^[0-9a-fA-F]{64}$/.test(signature) && timingSafeEqual(expected, Buffer.from(signature, "hex"))) return;
    }
  }
  throw new WebhookSignatureError("signature_mismatch");
}
```

## Forwarding a report

Reporter from the login, allowlisted fields only:

```js
app.post("/reports", requireUser, async (req, res) => {
  const b = req.body ?? {};
  const report = {
    source: "user",
    reasonCategory: b.reasonCategory,
    reasonText: b.reasonText,
    goodFaith: b.goodFaith,
    reporter: { externalUserId: req.user.id }, // from the login, never from the app
    subject: b.subject,                         // better: load content and author from your database
    content: b.content,
    externalReportId: b.externalReportId,
  };
  await forward(res, () =>
    limenia.request("POST", "/v1/reports", { body: report, idempotencyKey: idempotencyKey(req, res, "report") }),
  );
});
```

`forward` passes Limenia's status, problem body and `Retry-After` to the app unchanged; no answer at all becomes `502 limenia_unreachable`. `MemoryEventStore` and the device hash store are in memory: replace them with your database or Redis before running more than one instance.

---

# Go

Complete path for a Go backend with the standard library only. (https://limenia.eu/docs/guide-go/)

`go/` of the [examples repo](https://github.com/DL3KB/limenia-examples) uses the standard library only (Go 1.22+): `net/http`, `crypto/hmac`, `encoding/json`. Routes: `POST /reports`, `GET /me/moderation-status`, `POST /devices/request-hash`, `POST /devices/check`, `POST /limenia/webhook`. Files: `main.go` (config), `server.go` (routes, **login stub `currentUser`**), `limenia.go` (client with retries, request hash), `signature.go`, `webhook.go` (events), `actions.go` (**placeholders**).

```bash
cd limenia-examples/go && go test ./...
set -a; . ./.env; set +a   # .env filled in by the user from .env.example
go run .                   # PORT defaults to 8080
```

## Signature check

From `signature.go`:

```go
const SignatureTolerance = 300 * time.Second

func VerifySignature(header string, body []byte, now time.Time, secrets ...string) error {
	if header == "" {
		return ErrMissingSignature
	}
	var ts string
	seenT := false
	var sigs [][]byte
	for _, part := range strings.Split(header, ",") {
		key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
		if !ok {
			return ErrMalformedSignature
		}
		switch key {
		case "t":
			if seenT { // t must appear exactly once
				return ErrMalformedSignature
			}
			seenT, ts = true, value
		case "v1":
			if sig, err := hex.DecodeString(value); err == nil {
				sigs = append(sigs, sig)
			}
		}
	}
	unix, err := strconv.ParseInt(ts, 10, 64)
	if !seenT || err != nil || unix < 0 || len(sigs) == 0 {
		return ErrMalformedSignature
	}
	if d := now.Sub(time.Unix(unix, 0)); d > SignatureTolerance || d < -SignatureTolerance {
		return ErrTimestampOutOfRange
	}
	for _, secret := range secrets {
		mac := hmac.New(sha256.New, []byte(secret))
		mac.Write([]byte(ts + "."))
		mac.Write(body)
		want := mac.Sum(nil)
		for _, sig := range sigs {
			if hmac.Equal(sig, want) { // constant time
				return nil
			}
		}
	}
	return ErrSignatureMismatch
}
```

Read the body with `io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))` and verify **before** `json.Unmarshal`. Secrets come from `LIMENIA_WEBHOOK_SECRET` and, while rotating, `LIMENIA_WEBHOOK_SECRET_PREVIOUS`.

## Complaints and reviews

The Go example has no routes for complaints and reviews. Add them like `POST /reports`: take the user from your login, forward to `POST /v1/appeals` or `POST /v1/reviews` with an `Idempotency-Key`, and store the returned ID with the user. See [Complaints](#complaints) and [Pre-moderation reviews](#pre-moderation-reviews).

---

# Python with FastAPI

Complete path for a Python backend with FastAPI and httpx. (https://limenia.eu/docs/guide-python/)

`python-fastapi/` of the [examples repo](https://github.com/DL3KB/limenia-examples) (Python 3.10+, `fastapi`, `httpx`, `uvicorn`). Routes as in the [Go guide](#go). Files: `app/main.py` (routes, **login stub `current_user`**, config), `app/limenia.py` (client with retries, request hash), `app/signature.py`, `app/webhooks.py` (events, **placeholders** marked `TODO`).

```bash
cd limenia-examples/python-fastapi
python3 -m venv .venv && .venv/bin/pip install -r requirements-dev.txt
.venv/bin/pytest
.venv/bin/uvicorn app.main:create_app --factory   # env from .env, filled in by the user
```

## Webhook route and signature check

```python
@app.post("/limenia/webhook")
async def limenia_webhook(request: Request) -> Response:
    raw_body = await request.body()  # the raw bytes, exactly as signed
    if len(raw_body) > 1 << 20:
        return Response(status_code=413)
    try:
        verify_signature(request.headers.get("Limenia-Signature"), raw_body, config.webhook_secrets)
    except SignatureError as err:
        return JSONResponse({"code": err.code}, status_code=401)
    event = json.loads(raw_body)
    if processed.seen(event["id"]):
        return Response(status_code=204)  # duplicate: acknowledge only
    try:
        await webhooks.handle_event(event)
    except Exception:
        log.exception("limenia event failed", extra={"event_id": event["id"]})
        return Response(status_code=503)  # Limenia retries
    processed.add(event["id"])
    return Response(status_code=204)


def verify_signature(header: str | None, raw_body: bytes, secrets: Sequence[str], now: float | None = None) -> None:
    if not header:
        raise SignatureError("missing_signature")
    timestamp, signatures = None, []
    for part in header.split(","):
        key, sep, value = part.strip().partition("=")
        if not sep:
            raise SignatureError("malformed_signature")
        if key == "t":
            if timestamp is not None:
                raise SignatureError("malformed_signature")
            timestamp = value
        elif key == "v1":
            signatures.append(value)
    if timestamp is None or not re.fullmatch(r"[0-9]{1,12}", timestamp) or not signatures:
        raise SignatureError("malformed_signature")
    if abs((time.time() if now is None else now) - int(timestamp)) > 300:
        raise SignatureError("timestamp_out_of_range")
    signed_payload = timestamp.encode() + b"." + raw_body
    for secret in secrets:
        expected = hmac.new(secret.encode(), signed_payload, hashlib.sha256).hexdigest().encode()
        for signature in signatures:
            if hmac.compare_digest(expected, signature.encode()):
                return
    raise SignatureError("signature_mismatch")
```

The processed-ID set in the example is in memory; use a table with the event ID as primary key in production.

## Complaints and reviews

Add routes for complaints and reviews like the report route: user from the login, `Idempotency-Key`, store the returned ID with the user. See [Complaints](#complaints) and [Pre-moderation reviews](#pre-moderation-reviews).

---

# PHP with Laravel

Complete path for a Laravel 11 backend with drop-in files for the client, the controllers and the webhook. (https://limenia.eu/docs/guide-php/)

`php-laravel/` of the [examples repo](https://github.com/DL3KB/limenia-examples) contains files that drop into a Laravel 11 app (PHP 8.3): `app/Limenia/WebhookSignature.php` (plain PHP), `app/Limenia/LimeniaClient.php`, `app/Limenia/LimeniaEventHandler.php` (**placeholders**), `app/Http/Controllers/LimeniaController.php`, `app/Http/Controllers/LimeniaWebhookController.php`, `config/limenia.php` and `routes/limenia.php`.

## Setup

1. Copy the files into your app and include the routes from `routes/api.php` with `require __DIR__.'/limenia.php';`. The `api` route group has no CSRF check, which the webhook needs; Laravel prefixes these routes with `api`, so the webhook URL is `https://<your-host>/api/limenia/webhook`.
2. Put the app routes (`reports`, `me/moderation-status`, `devices/request-hash`, `devices/check`) behind your auth middleware (e.g. `auth:sanctum`). The webhook route has **no** auth middleware: the signature is the authentication.
3. The user sets `LIMENIA_API_KEY`, `LIMENIA_WEBHOOK_SECRET` (and optionally `LIMENIA_WEBHOOK_SECRET_PREVIOUS`, `LIMENIA_BASE_URL`) in `.env`; `config/limenia.php` reads them.

## Signature check

`WebhookSignature::verify`, called with `$request->getContent()`, the raw body:

```php
public static function verify(?string $header, string $rawBody, array $secrets, ?int $now = null): void
{
    if ($header === null || $header === '') {
        throw new InvalidSignature('missing_signature');
    }
    $timestamp = null;
    $signatures = [];
    foreach (explode(',', $header) as $part) {
        $pair = explode('=', trim($part), 2);
        if (count($pair) !== 2) {
            throw new InvalidSignature('malformed_signature');
        }
        [$key, $value] = $pair;
        if ($key === 't') {
            if ($timestamp !== null) {
                throw new InvalidSignature('malformed_signature');
            }
            $timestamp = $value;
        } elseif ($key === 'v1') {
            $signatures[] = $value;
        }
    }
    if ($timestamp === null || preg_match('/\A[0-9]{1,12}\z/', $timestamp) !== 1 || $signatures === []) {
        throw new InvalidSignature('malformed_signature');
    }
    if (abs(($now ?? time()) - (int) $timestamp) > 300) {
        throw new InvalidSignature('timestamp_out_of_range');
    }
    foreach ($secrets as $secret) {
        $expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
        foreach ($signatures as $signature) {
            if (hash_equals($expected, $signature)) { // constant time
                return;
            }
        }
    }
    throw new InvalidSignature('signature_mismatch');
}
```

The controller dedupes event IDs with the cache (`Cache::has('limenia:event:'.$id)`, kept 3 days); a table with a unique key on the event ID is safer in production.

## Complaints and reviews

Add controller actions for complaints and reviews like the report action: user from the login, `Idempotency-Key`, store the returned ID with the user. See [Complaints](#complaints) and [Pre-moderation reviews](#pre-moderation-reviews).

---

# AWS Lambda

Complete path for a Node.js function on AWS Lambda behind a function URL or API Gateway. (https://limenia.eu/docs/guide-aws-lambda/)

`aws-lambda/` of the [examples repo](https://github.com/DL3KB/limenia-examples): one Node.js 20 function without dependencies, behind a Lambda Function URL or an API Gateway HTTP API (payload format 2.0). Routes as in the [Go guide](#go). Files in `src/`: `handler.js` (routing, **login stub**: it reads the `sub` claim of an API Gateway JWT authorizer), `limenia.js`, `signature.js` (same as [Node.js](#webhook-route)), `events.js`, `actions.js` (**placeholders**), `event-store.js` (memory or DynamoDB via `LIMENIA_EVENTS_TABLE`), `device-ticket.js`.

```bash
cd limenia-examples/aws-lambda && npm test && npm run package   # function.zip
```

## Things specific to Lambda

- Lambda can hand over the body base64-encoded: decode `event.body` with `event.isBase64Encoded` before verifying the signature (`rawBody(event)` in `handler.js`).
- API Gateway ends requests after 30 s, so the example uses a 12 s timeout, two attempts and waits at most 5 s for `Retry-After`; longer waits go back to the app.
- Load `LIMENIA_API_KEY` and `LIMENIA_WEBHOOK_SECRET` from AWS Secrets Manager or SSM Parameter Store in production; plain Lambda environment variables are visible to anyone who can read the function configuration.

---

# Any other backend

What to build with any HTTP client and HMAC library when there is no example for your stack. (https://limenia.eu/docs/guide-other/)

Implement the five steps of [Choose your path](#what-every-integration-does) with your HTTP client and HMAC library, following the [API reference](#api-basics) and [Webhooks](#receiving-webhooks). Port the signature check from one of the examples (for instance [Go](#signature-check) or [Python](#webhook-route-and-signature-check)) and test it against the [test vector](#test-vector) before going live.

## Checklist for your own implementation

- **Configuration:** read `LIMENIA_BASE_URL`, `LIMENIA_API_KEY` and `LIMENIA_WEBHOOK_SECRET` from the environment or your secret store (see [Quickstart](#configure-your-backend)).
- **HTTP client:** `Authorization: Bearer $LIMENIA_API_KEY`, `Content-Type: application/json`, a client timeout of about 30 seconds, and retries with backoff on network errors, 429 and 5xx (see [Retries](#retries)).
- **Idempotency:** one stored `Idempotency-Key` per logical request on `POST /v1/reports`, `POST /v1/appeals`, `POST /v1/reviews` and `POST /v1/signals` (see [Idempotency](#idempotency)).
- **People from your login:** reporter, complaining person, author and device-check user come from your session, never from the request body of the app.
- **Webhook receiver:** read the raw body (at most 1 MiB is plenty), verify the signature before parsing, deduplicate by event ID, answer 2xx within 10 seconds, handle every event type (see [Webhook events](#webhook-events)).
- **Reconciliation:** `GET /v1/subjects/{externalUserId}/status` at login catches lost events.

A minimal report call with `curl`:

```bash
curl -sS -X POST "$LIMENIA_BASE_URL/v1/reports" \
  -H "Authorization: Bearer $LIMENIA_API_KEY" -H "Content-Type: application/json" \
  -H "Idempotency-Key: report-7f3c9a" \
  -d '{"source":"user","reasonCategory":"spam","reporter":{"externalUserId":"u_829"},"subject":{"externalUserId":"u_112"},"content":{"externalContentId":"comment_5521","contentType":"comment","text":"Text of the reported comment"}}'
```

Generate a typed client from the [OpenAPI specification](#openapi-specification) if your language has a generator.

---

# API basics

Base URL, API keys, versioning, idempotency, errors, rate limits, limits, pagination and timestamps of the /v1 API. (https://limenia.eu/docs/api-basics/)

## Base URL

The base URL is `https://app.limenia.eu/v1`. Every path starts with `/v1`. The API is for app backends only: it sends no CORS headers, so browsers cannot call it, and the API key must never reach a browser or mobile app anyway. Content type is `application/json` in both directions; errors are `application/problem+json`.

## Authentication

Send the API key of the app in the `Authorization` header:

```http
GET /v1/ping HTTP/1.1
Host: app.limenia.eu
Authorization: Bearer lm_live_...
```

- The scheme is `Bearer` with a capital B, followed by one space.
- The key determines tenant and app; Limenia never reads them from the body or the path. The only exception is the [RevenueCat webhook receiver](#revenuecat-webhook-receiver), which RevenueCat calls with its own header.
- A missing, malformed, unknown or revoked key answers 401 `unauthenticated`. Do not sign your app user out on this error: it is a problem of your backend's configuration.

## API keys

- An admin creates keys per app in the dashboard (tab **Connection → API keys**). An app can have several keys.
- Format: `lm_live_` plus 43 Base62 characters. Keys created in early versions of Limenia start with `lm_test_`; they keep working and behave exactly the same. The prefix does not select a sandbox: every key writes to the real system. Use a separate test app for tests (see [Testing](#testing)).
- The key is shown exactly once. Limenia stores only its SHA-256 hash and cannot show it again.
- Store it as `LIMENIA_API_KEY` in your backend's secret store, never in the app, in source control or in logs.
- **Rotation:** create a new key, deploy it, then revoke the old one. A revoked key stops working within 30 seconds.

Check a key with `GET /v1/ping`:

```bash
curl -sS "$LIMENIA_BASE_URL/v1/ping" -H "Authorization: Bearer $LIMENIA_API_KEY"
```

```json
{ "tenantId": "01K6…", "appId": "01K6…", "appSlug": "photoapp", "tenantStatus": "active" }
```

`tenantStatus` is `onboarding`, `active` or `suspended`. Reports are accepted only with `active`; `GET /v1/ping` works in every status. Use it at backend start or in a health check. Errors: 401, 429.

## Versioning

- The path version `/v1` stays stable. Changes within `/v1` are additive: new operations, new optional request fields, new response fields, new event types and new enum values.
- **Ignore unknown fields** in responses and webhook payloads, and handle unknown enum values (for example a new `action` or event `type`) gracefully: acknowledge the webhook with 2xx and log it.
- The version of the specification (currently in the header of the [OpenAPI specification](#openapi-specification) and on the [Overview](#overview)) follows semantic versioning. The [changelog](#changelog) lists every change that affects the public API.

## Requests

- **Body** at most 1 MiB. A larger body, invalid JSON or a wrong type (e.g. a date that is not RFC 3339) answers 400 `bad_request`.
- **Unknown fields** in request bodies are ignored, so a typo in a field name is not reported. Field names are matched case-insensitively; always send them exactly as documented.
- **Lengths** count characters (Unicode code points), not bytes. Exception: `context` objects are limited to 4 KB of serialized JSON.
- **URLs** (media, `externalUrl`, webhook) at most 2048 characters.
- **Timestamps** are RFC 3339. Limenia answers in UTC with up to 6 fractional digits.
- **IDs** of Limenia (`reportId`, `caseId`, `decisionId`, `appealId`, `reviewId`, `checkId`) are ULIDs: 26 characters, the first `0` to `7`. Webhook event IDs are `evt_` plus a ULID.
- **External IDs** (`externalUserId`, `externalContentId`, `externalReportId` and so on) are yours and scoped per app. Use stable, pseudonymous IDs, never e-mail addresses. Encode them in paths (`encodeURIComponent`).
- **Timeouts:** the first request after a pause can be slower. Use a client timeout of about 30 s.

## Idempotency

`POST /v1/reports`, `POST /v1/appeals`, `POST /v1/reviews` and `POST /v1/signals` require the header `Idempotency-Key`, 1 to 200 characters.

- Create one key per logical request (e.g. `report-<your report ID>`), store it with the request, and send the same key with the same body on every retry.
- Same key and same body (compared by field values, not bytes): Limenia returns the original response with the original status and creates nothing.
- Same key, different body: 409 `idempotency_key_reused`. Never reuse a key for a different request.
- Keys are kept per app for 24 hours, separately for reports, complaints, reviews and signals. After 24 hours the same key creates a new resource, so resend failed requests within 24 hours.
- A key is stored only on success. After a 400 you may send the corrected body with the same key.
- Without the header: 400 `validation_failed` with a field error at `Idempotency-Key`.
- `POST /v1/devices/check` takes no key: never retry it with the same token, get a new token instead.

## Retries

- Retry network errors, timeouts, 429 and 5xx with exponential backoff (1, 2, 4, 8 s) and the same key and body.
- On 429 wait at least the seconds in `Retry-After`. If a 503 carries `Retry-After`, respect it as well.
- Never retry other 4xx answers unchanged: fix the request.
- If it keeps failing, put the request in your own queue and resend it within 24 hours, so the idempotency key still deduplicates.

## Rate limits

- 10 requests per second per API key, with bursts up to 50, for every operation with an API key (including `GET` operations and repeated requests).
- A request with up to 100 signals counts once, so batch signals.
- Over the limit: 429 `rate_limited` with `Retry-After` in seconds. There are no rate limit headers on successful answers.
- Invalid keys: a key that does not exist or was revoked is answered 401. Many requests with different invalid keys from one address are answered 429 `rate_limited` with `Retry-After` for a while; keys in use are not affected.
- Need more: ask Limenia for more keys or a higher limit.

## Errors

Errors are `application/problem+json` (RFC 9457) with a machine-readable `code`:

```json
{
  "type": "about:blank",
  "title": "Bad Request",
  "status": 400,
  "detail": "The request contains invalid fields.",
  "code": "validation_failed",
  "errors": [{ "field": "/content/media/0/url", "code": "invalid", "message": "must be an https URL" }]
}
```

- Branch on `status` and `code`, never on `title`, `detail` or `message`; those are for people and may change. `detail` can be missing.
- `errors[]` lists field errors: `field` is a JSON pointer into the body (`/content/media/0/url`), a header name (`Idempotency-Key`) or a path parameter (`externalUserId`); `code` is `required`, `invalid`, `too_long`, `too_many`, `too_large`, `unknown`, `not_allowed` or `too_many_values` (a header sent twice); `message` is an optional hint.
- `reporter_suspended` adds `suspendedUntil`.

| Status | `code` | Meaning | Retry? |
|---|---|---|---|
| 400 | `validation_failed` | Field errors in `errors` | no, fix the body |
| 400 | `bad_request` | Not valid JSON, wrong type (e.g. a date that is not RFC 3339) or body over 1 MiB | no |
| 400 | `review_type_unknown` | `POST /v1/reviews`: the type is unknown or inactive | no |
| 400 | `signal_type_unknown` | `POST /v1/signals`: a type is unknown, inactive or a system type | no |
| 400 | `invalid_device_token` | `POST /v1/devices/check`: the provider rejected the token | no, get a new token |
| 401 | `unauthenticated` | Key missing, unknown, malformed or revoked | no (fix the key; do not sign your app user out) |
| 402 | `subscription_required` | The tenant's subscription expired (reviews, signals, device checks only) | no |
| 403 | `tenant_not_active` | Tenant still in setup or suspended; can last up to 30 s after setup completes | later |
| 403 | `feature_not_in_plan` | The plan does not include reviews, signals or the device connector | no |
| 403 | `reporter_suspended` | Reports of this reporter are suspended (Art. 23 DSA) until `suspendedUntil`; nothing was stored | no, not before `suspendedUntil` |
| 403 | `appeal_not_allowed` | This person may not complain against this decision | no |
| 404 | `not_found` | Unknown ID or path, or the ID belongs to another app | no |
| 405 | `method_not_allowed` | Wrong HTTP method for the path | no |
| 409 | `idempotency_key_reused` | The key was used for a different body | no, fix key generation |
| 409 | `appeal_window_closed` | The six months for a complaint are over | no |
| 409 | `appeal_already_open` | This person already has an open complaint against the decision | no |
| 409 | `device_connector_not_configured` | The platform is not active for the app, or `test` without test mode | no |
| 429 | `rate_limited` | Rate limit exceeded, header `Retry-After` in seconds | yes, after `Retry-After` |
| 500 | `internal` | Server error | yes |
| 502, 503, 504 | possibly without a problem body | Temporarily unavailable (e.g. during a deployment) | yes |

Reports, complaints and the two `subjects` operations are never refused because of the tenant's plan or subscription. Which codes an operation can return is listed on its page and in the [OpenAPI specification](#openapi-specification).

## Pagination

No `/v1` operation returns a list, so there is no pagination. Batch operations take at most 100 items per request (`POST /v1/signals`), and webhook events with many items are split (`reports.resolved`, see [Webhook events](#reportsresolved)).

## Plans

Reports, complaints and the user operations work with every plan and also after a subscription expired. Review requests, signals and device checks need a plan that includes them: otherwise they answer 403 `feature_not_in_plan`, and with an expired subscription 402 `subscription_required`. Do not publish unreviewed content when `POST /v1/reviews` fails; submit it again later.

---

# Reports

POST /v1/reports — report content or a user, with categories, media handling and how reports become cases. (https://limenia.eu/docs/reports/)

## POST /v1/reports

Report content or a user. Your backend calls it when a user reports something in your app (`source: user`) or when your app detected something itself (`source: system`).

```bash
curl -sS -X POST "$LIMENIA_BASE_URL/v1/reports" \
  -H "Authorization: Bearer $LIMENIA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: report-7f3c9a" \
  --data @- <<'JSON'
{
  "source": "user",
  "reasonCategory": "harassment_hate",
  "reasonText": "Insults me in every comment",
  "goodFaith": true,
  "reporter": { "externalUserId": "u_829" },
  "subject": { "externalUserId": "u_112", "displayName": "maxi_99" },
  "content": {
    "externalContentId": "comment_5521",
    "contentType": "comment",
    "text": "Text of the reported comment",
    "media": [{ "url": "https://storage.example.com/signed/abc.jpg?sig=…" }],
    "externalUrl": "https://app.example.com/p/77#comment_5521",
    "createdAt": "2026-10-01T09:12:00Z",
    "context": { "postId": "p_77" }
  },
  "externalReportId": "rep_77"
}
JSON
```

Response `201 Created` (also for a repeated request with the same key and body):

```json
{ "reportId": "01K6…", "caseId": "01K6…", "caseCreated": true }
```

`caseCreated` is `false` when the report was added to an open case. While a moderator has warned the reporter, the response also carries `"reporterWarning": { "issuedAt": "…" }`: show the reporter a notice that further unfounded reports can lead to a suspension of their reports (see [Complaints](#reporters-and-misuse)).

## Fields

| Field | Required | Limits and meaning |
|---|---|---|
| `source` | yes | `user`: a user reported it. `system`: your app detected it itself (the statement of reasons then says "own initiative"). |
| `reasonCategory` | yes | `^[a-z0-9_]{2,40}$`, usually the code of a policy of the tenant (see [Categories](#categories)) |
| `reasonText` | no | Free text of the reporter, at most 2000 characters |
| `goodFaith` | no | `true`: the reporter confirmed in good faith that the report is accurate and complete (Art. 16(2)(d) DSA). Only with `source: user`; with `system` any value is rejected (`validation_failed`, `invalid` at `/goodFaith`). Absent or `false` counts as not confirmed. Set it only if the person confirmed it. |
| `reporter.externalUserId` | no | Reporter's ID in your app, 1 to 128 characters; stored only as a hash. From your login. Omit with `source: system`; an empty string is rejected. |
| `subject.externalUserId` | `subject` or `content` | The reported user; for content its author. 1 to 128 characters, stable, not an e-mail address. |
| `subject.displayName` | no | At most 100 characters, trimmed; overwrites the stored name on every report |
| `subject.identifiers` | no | HMACs of the e-mail address and phone number of the reported user for ban evasion across apps (see [Identifiers](#ban-evasion-across-apps)). Never causes an error. |
| `content.externalContentId` | with `content` | 1 to 256 characters, stable ID of the content; comes back in decisions |
| `content.contentType` | with `content` | `^[a-z0-9_]{1,40}$`, your choice, e.g. `comment`, `image`, `profile`, `message` |
| `content.text` | no | At most 20 000 characters |
| `content.media[].url` | no | At most 10 entries, each at most 2048 characters, `https` only (see [Media](#media)) |
| `content.externalUrl` | no | Link to the content in your app, at most 2048 characters; reference only, never fetched |
| `content.createdAt` | no | RFC 3339 |
| `content.context` | no | JSON object, at most 4 KB serialized (`too_large`); IDs and technical details only. Keys of 1 to 128 bytes, no keys like `__x__`, no arrays in arrays, at most 10 levels (`invalid`) |
| `externalReportId` | no | Your report ID, 1 to 128 characters; comes back in `reports.resolved` |
| `trustedFlaggerId` | no | ULID of a trusted flagger of the tenant (Art. 22 DSA) the reporter acts for. Only with `source: user`. Unknown or inactive: `validation_failed`, `unknown` at `/trustedFlaggerId`. The case gets at least priority `high`. Set it only from your own records, never from the app. |

- At least one of `subject` and `content` is required. With reported content, always send its author as `subject`; without `subject` moderators cannot warn or suspend the user, without `content` they cannot act on the content.
- **Cases and snapshots:** reports on the same `externalContentId` of an app go into the same case while it is open or in review; after a decision the next report opens a new case. Reports without content are bundled per reported user. The snapshot (text, media, context, link) is taken at the first report on an `externalContentId`; later reports do not change it. To have an edited content judged again, give each version its own ID, e.g. `comment_5521@v2`.

## Errors

400 `validation_failed`, `bad_request`; 401; 403 `tenant_not_active`, `reporter_suspended` (with `suspendedUntil`; show the end and do not retry); 409 `idempotency_key_reused`; 429; 5xx. Reports are never refused because of the tenant's plan or subscription. All codes are in [API basics](#errors).

## Categories

Limenia only checks the pattern of `reasonCategory`. Use the codes of the tenant's policies (dashboard **Policies**), then the dashboard shows their titles. The default set created at setup:

| Code | Policy |
|---|---|
| `spam` | Spam |
| `harassment_hate` | Harassment and hate speech |
| `violence` | Violence |
| `sexual_content` | Sexual content |
| `child_safety` | Protection of minors |
| `fraud` | Fraud |
| `copyright` | Copyright |
| `privacy` | Privacy |
| `self_harm` | Self-harm |
| `other` | Other |

- Tenants can change and add policies, so agree on the codes with the tenant. The dashboard also understands the categories of the DSA transparency database (e.g. `scams_and_fraud`, `protection_of_minors`).
- **Child safety:** the reason codes `child_safety` and `protection_of_minors` make the case `urgent` immediately, and Limenia stores no copy of the media for such reports (it keeps only the URL). If copies were already stored for earlier reports on the same content, they are deleted. Urgent cases can be filtered in the dashboard; there is no separate alert yet.
- **Ban evasion:** `ban_evasion` means the user circumvents a ban or suspension, e.g. with another account. Your app may send it (priority `normal`, no special handling). Limenia also creates such reports itself with `source: system` and priority `high`, for example from the [RevenueCat webhook](#revenuecat-webhook-receiver).
- **Reserved:** `cross_app_ban` is used by Limenia itself for [ban evasion across apps](#ban-evasion-across-apps) (coming soon); do not send it.

## Media

- Limenia downloads media after answering, in the background. The result is visible only to moderators.
- The URL must be fetchable with a plain `GET` without login, e.g. a signed URL valid for at least one hour. `https` only, public addresses only; at most 3 redirects, each again `https` and public.
- Per attempt 10 s in total and at most 20 MB. Only HTTP 200 counts. A timeout, a connection error, 429 and 5xx are retried after 10 and 20 seconds; after the third attempt the medium fails (`unreachable` or `http_<status>`). Every other status fails at once.
- The same URL within one content is downloaded once.
- Each tenant has a quota of media downloads: about 300 per hour with bursts of up to 100. Media beyond it are not downloaded (`quota_exceeded` in the dashboard); the report itself is accepted as always. Need more: ask Limenia.
- The type is detected from the content: JPEG, PNG, GIF, WebP, MP4, WebM and QuickTime (MOV). HEIC, HEIF and AVIF are not supported (send JPEG, PNG or WebP). Other types are discarded.
- Limenia keeps a copy in private object storage and shows images blurred at first, only via short-lived signed links.

## Trusted flaggers

A trusted flagger (Art. 22 DSA) is an organisation the tenant has registered in the dashboard. When a report comes from a person who verifiably acts for one, your backend sets `trustedFlaggerId` to its ID. The case gets at least priority `high` and a marker in the dashboard, and the statement of reasons says the decision follows a report by a trusted flagger (`noticeSource: trusted_flagger`). Set it only from your own records, never from the app. See also [DSA](#trusted-flaggers-1).

---

# Users

PUT /v1/subjects/{externalUserId} and GET /v1/subjects/{externalUserId}/status — display names and the sanction status of a user. (https://limenia.eu/docs/subjects/)

A user in your app is a *subject* at Limenia, identified by your `externalUserId`. Limenia keeps a user file per app with the display name and the sanction status (see [Concepts](#user-file)). Both operations are never refused because of the tenant's plan or subscription.

## PUT /v1/subjects/{externalUserId}

Sets the display name of a user, e.g. after a rename, and/or passes the user's identifiers for ban evasion across apps (see [Identifiers](#ban-evasion-across-apps)). Optional.

```bash
curl -sS -X PUT "$LIMENIA_BASE_URL/v1/subjects/u_112" \
  -H "Authorization: Bearer $LIMENIA_API_KEY" -H "Content-Type: application/json" \
  -d '{"displayName":"maxi_100"}'
```

Body: `displayName` (at most 100 characters) and `identifiers` (see [Identifiers](#ban-evasion-across-apps)). Both are optional, but at least one is required (otherwise 400 `validation_failed`, field `/displayName`, code `required`).

- With `displayName` an unknown user is created as `active`, so send a display name only for users you have reported before. Without `displayName` the stored name stays.
- With only `identifiers`, an unknown user is created only while ban evasion across apps is on for the tenant; otherwise nothing is written. Identifiers never cause an error.

Response `200` with the status as in `GET /v1/subjects/{externalUserId}/status` below. Errors: 400, 401, 403 `tenant_not_active` (the tenant is in onboarding or suspended; nothing is written), 429.

## GET /v1/subjects/{externalUserId}/status

Current sanction status of a user. The fallback when a webhook was lost: call it at login or in a periodic reconciliation, not on every request.

```json
{ "externalUserId": "u_112", "status": "suspended", "suspendedUntil": "2026-10-08T08:00:00Z" }
```

- `status`: `active`, `warned`, `suspended` or `banned`; `suspendedUntil` only with `suspended`.
- Unknown users are `active`. A suspension whose `suspendedUntil` has passed is reported as `active` at once.
- Return it to the app only for the signed-in user. Errors: 401, 429.

## Status values

| `status` | Meaning | Set by |
|---|---|---|
| `active` | No restriction | default; `restore` with `restoreScope: "account"`; the end of a suspension |
| `warned` | Warned, not restricted | `warn_user` (if `active` or the suspension has already ended) |
| `suspended` | Blocked until `suspendedUntil` | `suspend_user` |
| `banned` | Blocked permanently | `ban_user` |

Changes arrive as webhooks: `decision.created` and, when a suspension ends or a complaint ends a restriction, `subject.status_changed` (see [Webhook events](#webhook-events)). Encode the `externalUserId` in the path (`encodeURIComponent`).

---

# Complaints

POST /v1/appeals and GET /v1/appeals/{appealId} — complaints against decisions (Art. 20 DSA), reporters and misuse. (https://limenia.eu/docs/appeals/)

Affected users and reporters have a right to complain against a decision (internal complaint handling, Art. 20 DSA). In the API a complaint is an *appeal*.

## POST /v1/appeals

A complaint against a decision (internal complaint handling, Art. 20 DSA). The affected user or a reporter complains in your app; your backend forwards it.

```bash
curl -sS -X POST "$LIMENIA_BASE_URL/v1/appeals" \
  -H "Authorization: Bearer $LIMENIA_API_KEY" -H "Content-Type: application/json" \
  -H "Idempotency-Key: appeal-4b1d0e" \
  -d '{"decisionId":"01K6G5H1TR8W4QZ3M0XCB7NDEC","appellant":{"type":"subject","externalUserId":"u_112"},"text":"The comment was a quote from a film, not an insult.","externalAppealId":"appeal_17"}'
```

Response `201 Created`: `{ "appealId": "01K6S1…", "status": "open" }`. Store `appealId` with the person.

| Field | Required | Limits and meaning |
|---|---|---|
| `decisionId` | yes | ULID of the decision, from `decision.created` (`decision.id`) or `reports.resolved` (`reports.decisionId`) |
| `appellant.type` | yes | `subject` (the affected user) or `reporter` (a user who reported the case) |
| `appellant.externalUserId` | yes | 1 to 128 characters, from your login. For a reporter, the same ID that was sent as `reporter.externalUserId` (Limenia compares hashes). |
| `text` | yes | Reasons of the person, 1 to 5000 characters, plain text |
| `externalAppealId` | no | Your ID, 1 to 128 characters; comes back in `appeal.resolved` |

Who may complain:

| `appellant.type` | Against |
|---|---|
| `subject` | restricting decisions on them: `remove_content`, `restrict_content`, `warn_user`, `suspend_user`, `ban_user`, `reject_submission` |
| `reporter` | any decision on a case they reported, especially `dismiss` |

- Deadline: six calendar months after `decidedAt` (if the target month is shorter, the last day of that month).
- At most one open complaint per decision and person.
- Decisions without a case (actions from the user file, reviews) have no reporters; only the affected user can complain.
- A reporter whose reports are suspended gets 403 `reporter_suspended`; affected users can always complain.

Errors: 400 `validation_failed`; 401; 403 `appeal_not_allowed`, `reporter_suspended`, `tenant_not_active`; 404 `not_found` (unknown decision or another app); 409 `appeal_window_closed`, `appeal_already_open`, `idempotency_key_reused`; 429.

## GET /v1/appeals/{appealId}

Status of a complaint; the fallback if `appeal.resolved` was missed. Return it only to the person who complained.

```json
{
  "id": "01K6S1…",
  "externalAppealId": "appeal_17",
  "decisionId": "01K6G5H1TR8W4QZ3M0XCB7NDEC",
  "appellantType": "subject",
  "status": "resolved",
  "createdAt": "2026-10-02T08:00:00Z",
  "outcome": "upheld",
  "statementText": "Decision on your complaint\n\n…",
  "resolvedAt": "2026-10-05T09:00:00.498765Z"
}
```

`status`: `open`, `in_review`, `resolved`. `outcome` (`upheld` or `changed`), `statementText` and `resolvedAt` only when resolved; `newDecisionId` only with `changed`. Errors: 401, 404, 429.

## Outcomes

Moderators handle complaints in their own queue; a human always decides. Results arrive as `appeal.resolved` (see [Webhook events](#appealresolved)):

- `upheld`: the decision stays; nothing changes in your app.
- `changed`: a new decision replaces the old one (`newDecisionId`) and arrives as its own `decision.created` with `appealId` and `replacesDecisionId`. Apply the action only when that `decision.created` arrives. After a complaint against `remove_content` or `restrict_content`, `restore` carries `restoreScope: "content"` and does not touch the account; after a complaint against `warn_user`, `suspend_user` or `ban_user` it carries `restoreScope: "account"`. If the new decision ends a ban or suspension, `subject.status_changed` comes as well.
- Show `statementText` completely, as plain text, to the person who complained (by e-mail if their account is blocked). It tells the person that a human decided and names the further options (out-of-court dispute settlement under Art. 21 DSA, courts).

## In short

- **Complaints:** forward them with `POST /v1/appeals`, show results from `appeal.resolved`, fall back to `GET /v1/appeals/{appealId}`. Remember which `appealId` belongs to which user and return the status only to them.
- **Reporters:** give every report an `externalReportId` or store the `reportId`; inform reporters on `reports.resolved` and offer a complaint until `appealDeadline` (see [Webhook events](#reportsresolved)).

## Reporters and misuse

Under Art. 23 DSA moderators may act against people who frequently send manifestly unfounded reports:

- **Warning:** a moderator warns the reporter. While the warning stands, the report response carries `reporterWarning` with `issuedAt`: show the reporter a notice.
- **Suspension:** after a delivered warning, a moderator can suspend the reports of that person for up to 365 days. Then `POST /v1/reports` answers 403 `reporter_suspended` with `suspendedUntil` in the problem, and nothing is stored. Show the end and do not retry. Complaints of that person as a reporter are refused the same way; complaints as an affected user are always possible.
- **Trusted flaggers (Art. 22 DSA):** the tenant registers them in the dashboard; your backend sets `trustedFlaggerId` only for people who verifiably act for one (see [Reports](#trusted-flaggers)).

---

# Pre-moderation reviews

POST /v1/reviews and GET /v1/reviews/{reviewId} — have content checked before you publish it. (https://limenia.eu/docs/reviews/)

A review request asks moderators to check content **before** you publish it (pre-moderation), e.g. profile photos, listings or usernames. The dashboard calls these queues **Approvals**. Do not confuse them with [store reviews](#store-reviews), the ratings of your app in the app stores.

## Setup

- Create the review types (codes) per app in the dashboard: tab **Moderation**, approval types. A type has a code, a name, guidelines for moderators, a target time (default 60 minutes, which sets `dueAt`), whether the outcome `restricted` is allowed, and the policies a rejection can be based on.
- Requires a plan with reviews. Copies of approved content are deleted after 30 days by default.

## POST /v1/reviews

```bash
curl -sS -X POST "$LIMENIA_BASE_URL/v1/reviews" \
  -H "Authorization: Bearer $LIMENIA_API_KEY" -H "Content-Type: application/json" \
  -H "Idempotency-Key: review-upload_881" \
  -d '{"type":"profile_photo","externalReviewId":"upload_881","subject":{"externalUserId":"u_112"},"content":{"externalContentId":"photo_881","contentType":"image","media":[{"url":"https://storage.example.com/signed/photo_881.jpg?sig=…"}]}}'
```

Response `201 Created`: `{ "reviewId": "01K6T2…", "status": "pending", "dueAt": "2026-10-03T10:00:00Z" }`. Until the result, show the content only to its author ("being reviewed").

| Field | Required | Meaning |
|---|---|---|
| `type` | yes | Code of an active review type of the app, `^[a-z0-9_]{2,40}$` |
| `content` | yes | Same format and limits as for [reports](#fields) |
| `subject` | recommended | The author, from your login, same format as in reports, including `identifiers` (see [Identifiers](#ban-evasion-across-apps)). Without it the decision belongs to no user. |
| `externalReviewId` | no | Your ID, 1 to 128 characters; comes back in `review.decided` |

- Every request is reviewed on its own (no bundling). A revised version may keep the `externalContentId`; each request gets its own copy.
- Media are downloaded as for reports. If you send every upload for review, mind the rate limit (10/s) and queue spikes.
- Your app must handle `approved`, `rejected` and, if the type allows it, `restricted`, regardless of the supported actions.

Errors: 400 `validation_failed`, `review_type_unknown` (type unknown or inactive, field `/type`); 401; 402 `subscription_required` (do not publish unreviewed; submit again later); 403 `feature_not_in_plan`, `tenant_not_active`; 409 `idempotency_key_reused`; 429.

## GET /v1/reviews/{reviewId}

Status of a review request; the fallback if `review.decided` was missed (e.g. for requests long past `dueAt`).

```json
{
  "id": "01K6T2…",
  "externalReviewId": "upload_881",
  "type": "profile_photo",
  "status": "decided",
  "submittedAt": "2026-10-03T09:00:00Z",
  "outcome": "rejected",
  "decidedAt": "2026-10-03T09:12:00.098765Z",
  "decisionId": "01K6T3…"
}
```

`status`: `pending`, `in_review`, `decided`. `outcome` (`approved`, `restricted`, `rejected`) and `decidedAt` only when decided; `decisionId` only with `restricted` and `rejected`. The statement of reasons comes with `decision.created`. A review is decided once; a later complaint does not change this response. Errors: 401, 404, 429.

## Outcomes

Results arrive as `review.decided` (see [Webhook events](#reviewdecided)). Publish only then:

| `outcome` | What your app does |
|---|---|
| `approved` | Publish. No `decision.created` and no statement of reasons follow. |
| `restricted` | Publish with a restriction (e.g. adults only, blurred). The decision with `restrict_content` follows as `decision.created`; show its statement of reasons to the author. |
| `rejected` | Do not publish. The decision with `reject_submission` follows as `decision.created`; show its statement of reasons. The author can complain. |

Decisions on review requests never change the account of the author.

---

# Signals

POST /v1/signals — send observations about users that the tenant's rules turn into cases, priorities or flags. (https://limenia.eu/docs/signals/)

## POST /v1/signals

Signals are observations about users that are not reports: score jumps, implausibly many actions, many new accounts. A signal creates no case; **rules** of the tenant (dashboard, tab **Moderation**) turn signals into a case, a higher priority or a flag on the user file. Limenia never sanctions on its own. Requires a plan with signals.

```bash
curl -sS -X POST "$LIMENIA_BASE_URL/v1/signals" \
  -H "Authorization: Bearer $LIMENIA_API_KEY" -H "Content-Type: application/json" \
  -H "Idempotency-Key: signals-6f1c0d2e" \
  -d '{"signals":[{"type":"score_jump","externalUserId":"u_112","value":4200,"context":{"level":"7"}}]}'
```

Response `202 Accepted`: `{ "accepted": 1 }`.

- `signals`: 1 to 100 entries, all or nothing (one invalid signal rejects the request). A request counts once against the rate limit, so batch.
- Each signal: `type` (code of an active signal type of the app, created in the dashboard; `^[a-z0-9_]{2,40}$`), `externalUserId` (1 to 128), `value` (optional number), `occurredAt` (optional, at most 24 hours back and 5 minutes ahead; default the time of receipt), `context` (optional, at most 4 KB, IDs and technical details only; keys of 1 to 128 bytes, no keys like `__x__`, no arrays in arrays, at most 10 levels), `identifiers` (optional, see [Identifiers](#ban-evasion-across-apps); a signal does not create a user, so identifiers for a user Limenia does not know yet are discarded).
- The system types `device_flagged` and `device_risk` (device connector) and `ban_evasion_cross_app` ([ban evasion across apps](#ban-evasion-across-apps)) are created by Limenia; you never send them.
- Values from a device can be faked: send signals from your backend where it can check them. Signals are kept briefly (default 30 days).

Errors: 400 `validation_failed`, `signal_type_unknown` (field error at `/signals/{i}/type`); 401; 402 `subscription_required`; 403 `feature_not_in_plan`, `tenant_not_active`; 409 `idempotency_key_reused`; 429.

## Signal types and rules

Create signal types and rules in the dashboard (tab **Moderation**), then send batches from your backend.

- A **signal type** has a code (the `type` you send), a name and an active switch. Types are never deleted, only deactivated.
- A **rule** has one or two conditions (combined with AND), one action and a cooldown per user (default one day).
  - Conditions: a number of signals of one type within a time window, optionally with a minimum `value`; or a number of different reporters within a time window (reports with `source: system` never count).
  - Actions: open a case (as a report with `source: system` at a chosen priority), raise the priority of open cases of the user to `high` or `urgent`, or put a flag on the user file.
- Rules can be tried out against the signals of the last days before switching them on. A moderator always decides; Limenia never sanctions because of a rule.

---

# Device checks

POST /v1/devices/check — check the device of a user at registration and login with Play Integrity or DeviceCheck. (https://limenia.eu/docs/device-checks/)

## POST /v1/devices/check

[Device connector](#device-connector): your backend forwards a fresh device token at registration and at every login, **also at the login of a banned account before rejecting it** (only then can Limenia mark the device). Requires a plan with the device connector.

Flow: (1) your backend picks a random nonce and computes `requestHash = base64url(SHA-256("limenia:" + externalUserId + ":" + nonce))` without padding for the signed-in user and keeps it a few minutes, single use; (2) the app gets a token with that hash (`limenia_device`); (3) the app sends `platform` and `token` to your backend; (4) your backend sends them with the user from its login and the hash it issued.

```bash
curl -sS -X POST "$LIMENIA_BASE_URL/v1/devices/check" \
  -H "Authorization: Bearer $LIMENIA_API_KEY" -H "Content-Type: application/json" \
  -d '{"externalUserId":"u_112","platform":"test","token":"test:emulator-1","event":"login"}'
```

| Field | Required | Meaning |
|---|---|---|
| `externalUserId` | yes | 1 to 128 characters, from your login |
| `platform` | yes | `android`, `ios` or `test` (test mode) |
| `token` | yes | Android: the integrity token, unchanged and **not decoded** (a second decode returns cleared verdicts). iOS: Base64 token of `DCDevice.generateToken`. Test: `test:<device>` or `test:<device>:risk`, `<device>` matching `[a-z0-9-]{1,40}`. At most 8000 characters. |
| `requestHash` | no | Android only: the `requestHash` (standard request) or `nonce` (classic request) of the token; checked if set. At most 500 characters. |
| `environment` | no | iOS only: `production` (default) or `development` for debug builds |
| `event` | no | `registration`, `login`, `report` or `other` (default) |
| `identifiers` | no | HMACs of the e-mail address and phone number of the user for ban evasion across apps (see [Identifiers](#ban-evasion-across-apps)). Never causes an error. |

## Response

Response `200`:

```json
{
  "checkId": "01K…",
  "platform": "android",
  "status": "evaluated",
  "deviceFlag": "banned",
  "flaggedSince": "2026-09",
  "deviceAction": "none",
  "integrity": { "device": "device", "appRecognized": true, "licensed": true, "risks": ["controlling_apps"], "testingResponse": false },
  "subject": { "externalUserId": "u_112", "status": "active" },
  "test": false
}
```

- `status`: `evaluated` or `unevaluated` (fail-open: Google or Apple unreachable, quota used up, or 429/5xx from them; then `deviceFlag` is `unknown`).
- `deviceFlag`: `none`, `suspended`, `banned` or `unknown` (bits not readable). The bits belong to the developer account, so a ban in another app of the same account marks the device too.
- `flaggedSince`: month of the marking (`YYYY-MM`), if known. `deviceAction`: what Limenia wrote now, `none`, `marked_banned`, `marked_suspended` or `reset`.
- `integrity` (Android only): `device` (`strong`, `device`, `basic`, `virtual`, `none`, `unevaluated`), `appRecognized`, `licensed` (absent if not evaluated), `risks` (`play_protect_off`, `play_protect_medium_risk`, `play_protect_high_risk`, `capturing_apps`, `controlling_apps`, `overlay_apps`, `high_activity`; later versions may add values), `testingResponse`.
- `subject`: the status as in [`GET /v1/subjects/{externalUserId}/status`](#get-v1subjectsexternaluseridstatus). `test`: `true` for test tokens.
- **A marked device is a hint, never proof.** Never reject or ban automatically because of `deviceFlag`; never reject because of `unevaluated` or `unknown`. Suggested: on `deviceFlag: banned` at registration, let a rule open a case or restrict the new account provisionally until a moderator decides.
- No `Idempotency-Key`; never retry with the same token. On network errors, 429 and 5xx treat the result as `unevaluated` or get a new token.

## Errors

Errors: 400 `validation_failed`, `invalid_device_token` (rejected by the provider, wrong package, `requestHash` mismatch, or token older than 15 minutes; do not retry; common causes: token already decoded, wrong hash, iOS debug build without `environment: development`); 401; 402 `subscription_required`; 403 `feature_not_in_plan`, `tenant_not_active`; 409 `device_connector_not_configured` (platform not active for the app, or `test` without test mode); 429.

Setup, test mode and data protection duties are on the [device connector](#device-connector) page.

---

# Ban evasion across apps

The optional identifiers field — HMACs of e-mail address and phone number that link the user files of a tenant's apps. Coming soon. (https://limenia.eu/docs/identifiers/)

> **Note:** Coming soon. Ban evasion across apps is not part of a plan yet and is available on request: ask Limenia to enable it for your tenant. Until it is enabled and switched on, Limenia accepts `identifiers` and discards them silently, so sending them does no harm.

## How it works

A tenant with several apps can let Limenia link the user files of its apps through the same e-mail address or phone number. Your backend never sends these values in plain text, only their HMAC with a key of the tenant. When a user whose linked user file in another app is **currently banned or suspended** becomes active in an app (a report about them, a review request, a signal, a device check, `PUT /v1/subjects`), Limenia creates the system signal `ban_evasion_cross_app` there, and a system rule of that app opens a case (category `ban_evasion`, priority `high`). A moderator decides; Limenia never sanctions on its own.

- Links exist only between different apps of the same tenant that take part, never within one app and never across tenants. A ban or suspension that has ended does not count.
- Apps with the same RevenueCat project are also linked by the same `externalUserId`, without identifiers.
- Nothing changes for your backend apart from the optional field: responses, errors and webhooks stay the same. There is no webhook event for a link; your app learns about a case only through the decision (`decision.created`). The statement of reasons does not name the other app.

## Setup

The owner sets it up in the dashboard: tenant settings, tab **Ban evasion**. Switch it on, confirm that a data protection impact assessment and a legal basis exist (the privacy notices of all chosen apps must cover the linking), and choose at least two apps that take part. New apps do not take part automatically. Then **create a key**:

- Format `lmid_{version}_{random}`, e.g. `lmid_1_` plus 43 characters of Base64url. The version (1 to 999) is part of the key.
- It is shown **exactly once**. Limenia does not keep it and cannot show it again; if it is lost, create a new version (rotation below).
- Store it as `LIMENIA_IDENTIFIER_KEY` in the secret store of the backend of **every** app that takes part: one key per tenant, so the same address gives the same HMAC in every app. Never put it in the mobile or web app; anyone could extract it from there and test addresses against it. The app never computes identifiers.
- The dashboard shows per version the last characters of the key, a fingerprint and the **check values** (below) to compare with your backend.

## Where to send them

Always for the user the request is about, never for the reporter.

| Operation | Field |
|---|---|
| `POST /v1/reports` | `subject.identifiers` |
| `POST /v1/reviews` | `subject.identifiers` |
| `POST /v1/signals` | `signals[i].identifiers` |
| `POST /v1/devices/check` | `identifiers` |
| `PUT /v1/subjects/{externalUserId}` | `identifiers` |

## When to send them

Recommended: `PUT /v1/subjects/{externalUserId}` with `identifiers` at registration (that is when an evader shows up) and on every change of the e-mail address or phone number. Optionally also with reports, review requests, device checks and signals. A request without identifiers still counts: Limenia uses the identifiers it already stored for the user. A signal does not create a user, so send the identifiers of a new user with `PUT /v1/subjects` first.

## Format

```json
{ "keyVersion": 1, "email": "42a675f77f1e0efc8301553470878dd507fac6c79f4eb6099c0a0832e174ae0c", "phone": "733b02f032c851ae4b3d64094a9607ea2168ad054ab200a69144e4ee7b25ea38" }
```

| Field | Meaning |
|---|---|
| `keyVersion` | Version of the key, 1 to 999; the number between `lmid_` and the next `_`. Default the newest active version, but always send it. |
| `email` | `hex(HMAC-SHA256(key, "email:" + normalised address))`, 64 lower-case hex characters. Optional. |
| `phone` | `hex(HMAC-SHA256(key, "phone:" + E.164 number))`, 64 lower-case hex characters. Optional. |

- `key` is the whole key string as UTF-8 bytes (`lmid_1_…`), not Base64-decoded. The message is the kind, a colon and the normalised value as UTF-8, so an e-mail HMAC never equals a phone HMAC.
- The whole object is at most 1 KB as JSON. Leave out a value you cannot normalise; never send an empty string.

## Normalising the e-mail address

Limenia never sees the address and cannot check your normalisation, so it is deliberately simple and the same in every language:

1. Remove leading and trailing whitespace (`trim()`, `strings.TrimSpace`, `strip()`).
2. Lower only the ASCII letters `A` to `Z`. Every other character stays as it is (Unicode lower-casing differs between languages, e.g. for `İ`).
3. If the result does not have exactly one `@` with something before and after it, send no `email`.

No provider rules: dots and `+` suffixes stay, also at Gmail (`m.a.x+2@gmail.com` stays as it is). Removing them would merge different people at other providers.

## Normalising the phone number

Bring it into E.164: `+`, country code, number without the national trunk prefix, digits only, at most 15 digits (`0151 2345678` taken in Germany becomes `+491512345678`). Use libphonenumber (`libphonenumber-js`, `phonenumbers`, `nyaruka/phonenumbers`, `phone_numbers_parser`) with the region in which the app took the number. Spaces and hyphens may be removed. If the result does not match `^\+[1-9][0-9]{6,14}$`, send no `phone`. Numbers are reassigned by carriers, so a link by phone is weaker than one by e-mail; the dashboard shows the kind of every link.

## Test vectors

With the documentation key `lmid_1_ExampleKeyForDocsOnly-NeverUseInProduction0` (never use it in production):

| Message (`kind:normalised value`) | HMAC |
|---|---|
| `email:max.mustermann@example.com` | `42a675f77f1e0efc8301553470878dd507fac6c79f4eb6099c0a0832e174ae0c` |
| `phone:+447700900123` | `733b02f032c851ae4b3d64094a9607ea2168ad054ab200a69144e4ee7b25ea38` |
| `email:selftest@limenia.invalid` | `1a0f78a6aefe96517a25604dc03dbe71f252da9b48425d6dc2d8ed886f7d78b5` |
| `phone:+447700900000` | `102f22e8bbbbb4c4f3837121507a585b63e64c0b86e72d3c547574ff369fd889` |
| `email:max+2@gmail.com` | `c7b7f4b74624d534ae0f112eee1934bf4b286e47e624d72a9d4dee0559399216` |
| `email:müller@example.com` | `cd86b1938c0d1f3714785d49ef66ba77f6f00b7f465c9ca3b84d03cab72b96b4` |
| `phone:+491512345678` | `8eaddc5bacb7dbd05ae38df9803d29d7efdc1564f5ae82d32c44d25cb2557f50` |

| Input | Normalised |
|---|---|
| `"  Max.Mustermann@Example.COM \n"` | `max.mustermann@example.com` |
| `"m.a.x@GMAIL.com"` | `m.a.x@gmail.com` (dots stay) |
| `"MÜLLER@Example.com"` | `mÜller@example.com` (only A to Z are lowered) |
| `"max"`, `"@example.com"`, `"max@"`, `"a@b@example.com"` | none, send no `email` |
| `" +44 7700 900123 "`, `"+49-151-2345678"` | `+447700900123`, `+491512345678` |
| `"01512345678"`, `"+49 (0)151 2345678"`, `"+123456"` | none (national, not E.164, too short), send no `phone` |

## Self-test with the check values

The check values in the dashboard are the HMACs of the fixed test values `email:selftest@limenia.invalid` (`CHECK_EMAIL`) and `phone:+447700900000` (`CHECK_PHONE`) with your key; they contain no personal data. Compute both with your implementation and `LIMENIA_IDENTIFIER_KEY` and compare them with the dashboard, e.g. in a unit test or at backend start. If they match, key and implementation are right. With the documentation key they are the third and fourth rows of the test vectors.

## Code

**Code.** Each snippet computes the `identifiers` object; all of them reproduce the test vectors.

Node.js (`node:crypto`):

```js
import { createHmac } from "node:crypto";

const key = process.env.LIMENIA_IDENTIFIER_KEY; // lmid_<version>_<random>, backend only
const keyVersion = Number(key.split("_")[1]);
const hmac = (kind, value) => createHmac("sha256", key).update(`${kind}:${value}`, "utf8").digest("hex");

function normalizeEmail(raw) {
  const email = raw.trim().replace(/[A-Z]/g, (c) => c.toLowerCase());
  const at = email.indexOf("@");
  return at > 0 && at < email.length - 1 && email.indexOf("@", at + 1) === -1 ? email : undefined;
}

function normalizePhone(e164) {
  const phone = e164.trim().replace(/[ \t-]/g, "");
  return /^\+[1-9][0-9]{6,14}$/.test(phone) ? phone : undefined;
}

export function computeIdentifiers({ email, phone }) {
  const identifiers = { keyVersion };
  const e = email ? normalizeEmail(email) : undefined;
  if (e) identifiers.email = hmac("email", e);
  const p = phone ? normalizePhone(phone) : undefined;
  if (p) identifiers.phone = hmac("phone", p);
  return identifiers;
}

// At registration and on every change of e-mail address or phone number:
// PUT /v1/subjects/{externalUserId} with { identifiers: computeIdentifiers({ email: user.email, phone: user.phone }) }
```

Go (`crypto/hmac`):

```go
var e164 = regexp.MustCompile(`^\+[1-9][0-9]{6,14}$`)

type Identifiers struct {
	KeyVersion int    `json:"keyVersion"`
	Email      string `json:"email,omitempty"`
	Phone      string `json:"phone,omitempty"`
}

func identifierHMAC(key, kind, value string) string {
	m := hmac.New(sha256.New, []byte(key))
	m.Write([]byte(kind + ":" + value))
	return hex.EncodeToString(m.Sum(nil))
}

func normalizeEmail(raw string) (string, bool) {
	email := strings.Map(func(r rune) rune {
		if r >= 'A' && r <= 'Z' {
			return r + ('a' - 'A')
		}
		return r
	}, strings.TrimSpace(raw))
	local, domain, ok := strings.Cut(email, "@")
	if !ok || local == "" || domain == "" || strings.Contains(domain, "@") {
		return "", false
	}
	return email, true
}

func normalizePhone(raw string) (string, bool) {
	phone := strings.NewReplacer(" ", "", "\t", "", "-", "").Replace(strings.TrimSpace(raw))
	return phone, e164.MatchString(phone)
}

// key is os.Getenv("LIMENIA_IDENTIFIER_KEY").
func computeIdentifiers(key, email, phone string) (Identifiers, error) {
	rest, ok := strings.CutPrefix(key, "lmid_")
	v, _, ok2 := strings.Cut(rest, "_")
	version, err := strconv.Atoi(v)
	if !ok || !ok2 || err != nil {
		return Identifiers{}, errors.New("LIMENIA_IDENTIFIER_KEY is not an identifier key")
	}
	ids := Identifiers{KeyVersion: version}
	if e, ok := normalizeEmail(email); ok {
		ids.Email = identifierHMAC(key, "email", e)
	}
	if p, ok := normalizePhone(phone); ok {
		ids.Phone = identifierHMAC(key, "phone", p)
	}
	return ids, nil
}
```

Python (`hmac`):

```python
import hashlib, hmac, os, re

KEY = os.environ["LIMENIA_IDENTIFIER_KEY"]  # lmid_<version>_<random>, backend only
KEY_VERSION = int(KEY.split("_")[1])

def identifier_hmac(kind: str, value: str) -> str:
    return hmac.new(KEY.encode("utf-8"), f"{kind}:{value}".encode("utf-8"), hashlib.sha256).hexdigest()

def normalize_email(raw: str) -> str | None:
    email = re.sub(r"[A-Z]", lambda m: m.group().lower(), raw.strip())
    local, at, domain = email.partition("@")
    return email if at and local and domain and "@" not in domain else None

def normalize_phone(e164: str) -> str | None:
    phone = re.sub(r"[ \t-]", "", e164.strip())
    return phone if re.fullmatch(r"\+[1-9][0-9]{6,14}", phone) else None

def compute_identifiers(email: str | None = None, phone: str | None = None) -> dict:
    identifiers = {"keyVersion": KEY_VERSION}
    if email and (e := normalize_email(email)):
        identifiers["email"] = identifier_hmac("email", e)
    if phone and (p := normalize_phone(phone)):
        identifiers["phone"] = identifier_hmac("phone", p)
    return identifiers
```

Dart backend (`package:crypto`; the Flutter package `limenia` runs in the app and therefore has no such helper):

```dart
import 'dart:convert';
import 'dart:io';

import 'package:crypto/crypto.dart';

final _key = Platform.environment['LIMENIA_IDENTIFIER_KEY']!; // lmid_<version>_<random>, backend only
final _keyVersion = int.parse(_key.split('_')[1]);
final _e164 = RegExp(r'^\+[1-9][0-9]{6,14}$');

String _hmac(String kind, String value) =>
    Hmac(sha256, utf8.encode(_key)).convert(utf8.encode('$kind:$value')).toString();

String? normalizeEmail(String raw) {
  final email = raw.trim().replaceAllMapped(RegExp('[A-Z]'), (m) => m[0]!.toLowerCase());
  final at = email.indexOf('@');
  return at > 0 && at < email.length - 1 && !email.contains('@', at + 1) ? email : null;
}

String? normalizePhone(String e164) {
  final phone = e164.trim().replaceAll(RegExp(r'[ \t-]'), '');
  return _e164.hasMatch(phone) ? phone : null;
}

Map<String, Object> computeIdentifiers({String? email, String? phone}) {
  final e = email == null ? null : normalizeEmail(email);
  final p = phone == null ? null : normalizePhone(phone);
  return {
    'keyVersion': _keyVersion,
    if (e != null) 'email': _hmac('email', e),
    if (p != null) 'phone': _hmac('phone', p),
  };
}
```

## Rotation

Limenia cannot convert old HMACs because it never knows the addresses, and identifiers only link within the same key version. To rotate (or after losing the key):

1. The owner creates a new version in the dashboard. The old one stays active; both are accepted (at most two active versions).
2. Deploy the new key to the backends of all apps that take part, compute with it from now on, and send the identifiers of your users again with `PUT /v1/subjects/{externalUserId}`, best for all users and at least for banned and suspended ones: their user files get identifiers of the new version only this way.
3. Retire the old version. Its stored identifiers stay until their retention ends and keep linking among themselves. If the key leaked, retire it **with deletion**: Limenia then also deletes all identifiers of that version.

Retiring the only active version means Limenia accepts nothing until a new version exists.

## Limenia never rejects anything because of identifiers

A request never fails and never answers differently because of `identifiers`, and the response does not say whether they were stored or linked. Limenia discards them silently when the feature is not enabled or switched off for the tenant, the app does not take part, the key version is unknown or retired, a value is not 64 hex characters, the object is not valid or over 1 KB, or (for signals) the user is unknown. The dashboard (tab **Ban evasion**) shows per app and day for the last 7 days how many identifiers were received, stored and discarded, with the reason. Check it after going live; discarded identifiers for a wrong format mean your normalisation or HMAC differs (compare the check values).

## Data protection

Identifiers live as long as the user file they belong to and are deleted with it. Switching the feature off stops it at once and deletes all stored identifiers. The tenant needs its own data protection impact assessment and must name the linking in the privacy notices of all apps that take part.

See also [Data protection](#data-protection-2).

---

# RevenueCat webhook receiver

POST /v1/integrations/revenuecat/{tenantId}/{appId} — the endpoint RevenueCat calls; not called by your backend. (https://limenia.eu/docs/revenuecat-webhook/)

## POST /v1/integrations/revenuecat/{tenantId}/{appId}

> **Note:** Not called by your backend. RevenueCat calls this endpoint when you set up the optional RevenueCat webhook of the [RevenueCat connector](#revenuecat-connector).

This is the receiver for webhooks of RevenueCat. RevenueCat calls it with the URL and the `Authorization` header value that the dashboard shows once when you set up the RevenueCat webhook (no API key; the scheme `Bearer ` is optional). With HMAC signing switched on in RevenueCat, the header `X-RevenueCat-Webhook-Signature: t=<unix>,v1=<hex>` is checked over the unchanged body (at most 5 minutes old).

## Events Limenia acts on

- `TRANSFER`: purchases of a banned or suspended user, or of one whose ban ended less than 90 days ago, move to another App User ID. Limenia creates a `ban_evasion` report with `source: system` and priority `high` on each target.
- `CANCELLATION` with `cancel_reason` `CUSTOMER_SUPPORT`: counted as a refund on the user file.

Everything else, including `TEST`, is answered 200 without action.

## Answers

| Status | Meaning |
|---|---|
| 200 | Processed, already processed or ignored |
| 400 | Not an event or over 1 MiB |
| 401 | Wrong header or signature |
| 404 | Unknown app or no RevenueCat webhook set up |
| 503 | Temporary; RevenueCat retries |

## Setup in RevenueCat

In RevenueCat, add a webhook integration with the URL and the authorization header value from the dashboard (tab **Connectors → RevenueCat**), send all events or at least `TRANSFER` and `CANCELLATION`, choose the environment Production, and switch on HMAC signing if you can. Set RevenueCat's restore behavior to "Keep with original App User ID".

---

# OpenAPI specification

The machine-readable description of every /v1 operation and webhook event, and how to use it. (https://limenia.eu/docs/openapi/)

## Download

<https://limenia.eu/openapi/v1.yaml>

The file is OpenAPI 3.0 (YAML). It contains:

- every `/v1` operation with request and response schemas, the error responses and examples,
- the security scheme `apiKey` (`Authorization: Bearer <API key>`),
- the webhook events under `x-webhooks` (OpenAPI 3.0 has no `webhooks` section) with the schemas `WebhookEvent` and `EventType`,
- the server `https://app.limenia.eu`.

The version in `info.version` is the API version; the [changelog](#changelog) lists what changed.

## Operations

| Operation | Page |
|---|---|
| `GET /v1/ping` | [API basics](#api-keys) |
| `POST /v1/reports` | [Reports](#reports) |
| `PUT /v1/subjects/{externalUserId}` | [Users](#users) |
| `GET /v1/subjects/{externalUserId}/status` | [Users](#users) |
| `POST /v1/appeals` | [Complaints](#complaints) |
| `GET /v1/appeals/{appealId}` | [Complaints](#complaints) |
| `POST /v1/reviews` | [Pre-moderation reviews](#pre-moderation-reviews) |
| `GET /v1/reviews/{reviewId}` | [Pre-moderation reviews](#pre-moderation-reviews) |
| `POST /v1/signals` | [Signals](#signals) |
| `POST /v1/devices/check` | [Device checks](#device-checks) |
| `POST /v1/integrations/revenuecat/{tenantId}/{appId}` | [RevenueCat webhook receiver](#revenuecat-webhook-receiver) (called by RevenueCat) |

## Using it

- **Generate a client:** see [Typed clients from the OpenAPI spec](#typed-clients-from-the-openapi-spec).
- **Validate webhook payloads** in tests against `WebhookEvent`.
- **Give it to a coding agent** together with this documentation: <https://limenia.eu/llms-full.txt> contains both in one file.
- **Exhaustive enums:** new enum values (for example a new decision `action` or event `type`) can be added within `/v1`. Generated code must not fail on unknown values (see [Versioning](#versioning)).

---

# Receiving webhooks

How Limenia calls your webhook — headers, signature check with test vector, retries, ordering, applying actions and showing the statement of reasons. (https://limenia.eu/docs/webhooks/)

Limenia tells your backend about decisions with webhooks. Set the URL in the dashboard (tab **Connection → Webhook**, see [Quickstart](#set-up-the-app-in-the-dashboard)). The events and their payloads are on [Webhook events](#webhook-events).

## Request

Limenia sends a `POST` with a JSON body to your webhook URL:

| Header | Content |
|---|---|
| `Content-Type` | `application/json` |
| `User-Agent` | `Limenia-Webhooks/1` |
| `Limenia-Event-Id` | `evt_` plus a ULID, equal to `id` in the body |
| `Limenia-Event-Type` | `decision.created`, `subject.status_changed`, `appeal.resolved`, `reports.resolved`, `review.decided` or `test.ping` |
| `Limenia-Signature` | `t=<unix seconds>,v1=<hex>` |

Limenia sends from no fixed address, so an IP allowlist is not possible. Rely on the signature.

## Verifying the signature

1. Split `Limenia-Signature` at commas. `t` must appear exactly once, `v1` at least once. Ignore unknown keys.
2. Reject the request if `t` is more than 300 seconds away from your clock, in either direction. Keep the server clock in sync (NTP).
3. Compute `hex(HMAC-SHA256(secret, t + "." + rawBody))` over the **raw** body exactly as received. Do not parse and re-serialize it first.
4. The signature is valid if any `v1` value matches, for the current secret or (while rotating) the previous one. Compare in constant time.
5. On failure answer 401 and do nothing else.

The signing secret is the whole string as shown in the dashboard, including the prefix `whsec_` (49 characters). Use it as the HMAC key byte for byte; do not decode it.

## Test vector

Test your code against it before going live:

| | |
|---|---|
| Secret | `whsec_test` |
| `t` | `1800000000` |
| Body | `{"id":"evt_1"}` |
| `v1` | `45705be2a45ab5acdd1395cc695e9e7073125385ec24194921c401dff44176f8` |

```bash
printf '%s' '1800000000.{"id":"evt_1"}' | openssl dgst -sha256 -hmac whsec_test
# → 45705be2a45ab5acdd1395cc695e9e7073125385ec24194921c401dff44176f8
```

(`t=1800000000` is far from now, so a correct receiver rejects this header with `timestamp_out_of_range`; use the vector in unit tests with an injected clock.)

Limenia signs every delivery attempt anew with a new `t`; the body stays the same across retries.

## Rotating the secret

Limenia signs only with the current secret and currently sends exactly one `v1`. After **Rotate secret**, deliveries fail until your receiver knows the new secret, but they are retried (first retry after 1 minute, for about 20 hours). Easiest: accept a list of secrets (`LIMENIA_WEBHOOK_SECRET` and `LIMENIA_WEBHOOK_SECRET_PREVIOUS`), add the new one, deploy, remove the old one later.

## Answers, retries, order

- Answer 2xx (e.g. `204`) within **10 seconds** (including connection setup). Do heavy work asynchronously, but acknowledge only after the event is safely stored.
- Every other answer, a timeout or a connection error is a failure, also 4xx and 3xx (redirects are not followed). Limenia retries up to 12 attempts, backoff from 1 minute doubling up to 6 hours, about 20 hours in total. Afterwards the delivery is `failed` in the **Delivery log**; an admin can resend it.
- **Pause after repeated failures:** after 5 timeouts, connection errors, 429 or 5xx answers in a row, Limenia pauses the webhook deliveries of the app for 5 minutes. Paused deliveries are not lost: they keep their retry schedule and their last attempt always runs. After the pause one delivery goes through; when it succeeds the others follow. A successful **Test webhook** ends the pause at once. Firebase, Supabase and RevenueCat actions are not held up by a slow webhook.
- Answer with an error only when you want a retry. Acknowledge duplicates, unknown event types and events you ignore with 2xx. An action your app does not support: acknowledge with 2xx and log it (IDs only).
- **At least once:** the same event can arrive several times with the same `id` and body but a new signature. Deduplicate by `id` (= `Limenia-Event-Id`), mark it processed only after handling it, and make actions idempotent (set a state, do not toggle it).
- **Order not guaranteed:** remember per user and per content the time of the last applied change and skip older events: `decision.decidedAt`, or `createdAt` for `subject.status_changed`. Skip only strictly older events, not equal ones. So a late `suspend_user` never overrides a later `restore`.

## Delivery log

Every delivery attempt appears in the dashboard under **Delivery log** with its status (`pending`, `delivered`, `failed`) and, on failure, an error code:

| Error code | Meaning | Retried? |
|---|---|---|
| `http_status` | Your receiver answered with something other than 2xx (also 3xx and 4xx) | yes |
| `timeout` | No answer within 10 seconds | yes |
| `connection_failed` | DNS, TLS or the connection failed | yes |
| `blocked_url` | The URL or the address it resolves to is not public `https` | no |

Limenia reads at most 64 KiB of your answer and ignores its content. A delivery that is `failed` after all attempts can be resent by an admin from the delivery log; it then gets a new series of attempts.

## Applying actions

Every decision has exactly one action; removing content and suspending its author are two decisions. Act on `action`, not on whether `content` or `subject` is present.

| `action` | Status in Limenia | What your app does |
|---|---|---|
| `dismiss` | unchanged | Nothing. Inform reporters via `reports.resolved`. |
| `remove_content` | unchanged | Remove or permanently hide `content.externalContentId` |
| `restrict_content` | unchanged | Restrict visibility (e.g. out of feeds and search). After a restricted review: publish restricted. |
| `warn_user` | `warned` (if `active` or the suspension has already ended) | Warn the user; do not restrict the account |
| `suspend_user` | `suspended` until `suspendUntil` | Block the account until `suspendUntil` (UTC). Lift it yourself at that time; `subject.status_changed` can come up to an hour later. |
| `ban_user` | `banned` | Block the account permanently |
| `restore` | `account`: `active`; `content`: unchanged | `restoreScope: "account"`: unblock the account. `restoreScope: "content"`: restore the content (with `reviewId`: publish the submitted content as submitted); do not touch the account. |
| `reject_submission` | unchanged | Reviews only: do not publish `content.externalContentId` |

Decisions with `reviewId` never change the account.

## Showing the statement of reasons

- Show `statementOfReasons.text` to the affected user for every decision except `dismiss` (for `restore` it is a notice of the lifting). If the account is blocked, use a channel outside the app (e-mail, login screen).
- The text is ready-made, with `\n` line breaks, in the tenant's language. Render it as **plain text**, never HTML or Markdown: it contains the moderator's free text.
- For your own layout or other languages use `structured`. Show the automation note when `automation` is `partial` or `full`.
- `decision.created` never names reporters.

Under the DSA you must show the statement of reasons to the affected user (Art. 17 DSA, see [DSA](#dsa)).

---

# Webhook events

Every webhook event with an example payload — decision.created, subject.status_changed, reports.resolved, appeal.resolved, review.decided and test.ping. (https://limenia.eu/docs/webhook-events/)

## Event format

Every event has `id`, `type`, `createdAt` (when the event was created) and `app` (`id`, `slug`), plus one payload member depending on the type. Timestamps are UTC RFC 3339 with up to 6 fractional digits. Ignore unknown fields.

| `type` | Payload member | When |
|---|---|---|
| `decision.created` | `decision` | A moderator decided |
| `subject.status_changed` | `subject` | A suspension ended, or a complaint ended a restriction |
| `reports.resolved` | `reports` | After a decision on a case with reports of users |
| `appeal.resolved` | `appeal` | A complaint was decided |
| `review.decided` | `review` | A review request was decided |
| `test.ping` | none | **Send test webhook** in the dashboard |

The schemas are in the [OpenAPI specification](#openapi-specification) under `x-webhooks` and `WebhookEvent`. How to verify and answer the requests is on [Receiving webhooks](#receiving-webhooks).

## `decision.created`

A moderator decided (on a case, from a user file, on a review request or on a complaint). Example, a temporary suspension:

```json
{
  "id": "evt_01K6G5H1TR8W4QZ3M0XCB7NDEA",
  "type": "decision.created",
  "createdAt": "2026-10-01T10:00:00.123456Z",
  "app": { "id": "01K6G5H1TR8W4QZ3M0XCB7NAPP", "slug": "photoapp" },
  "decision": {
    "id": "01K6G5H1TR8W4QZ3M0XCB7NDEC",
    "action": "suspend_user",
    "suspendUntil": "2026-10-08T08:00:00Z",
    "content": { "externalContentId": "comment_5521" },
    "subject": { "externalUserId": "u_112" },
    "policies": [{ "code": "harassment_hate", "title": "Harassment and hate speech" }],
    "statementOfReasons": {
      "locale": "en",
      "text": "Decision on your account\n\nMeasure: temporary suspension of the account until …",
      "structured": {
        "action": "suspend_user",
        "endsAt": "2026-10-08T08:00:00Z",
        "territorialScope": "app",
        "facts": "Repeated insults in comments.",
        "basedOnNotice": true,
        "noticeSource": "notice",
        "automatedDetection": false,
        "automatedDecision": false,
        "automation": "none",
        "grounds": [{ "basis": "terms", "policyCode": "harassment_hate", "title": "Harassment and hate speech" }],
        "redress": "…"
      }
    },
    "decidedAt": "2026-10-01T10:00:00.123456Z"
  }
}
```

| Field of `decision` | Meaning |
|---|---|
| `id` | Decision ID (for complaints) |
| `action` | `dismiss`, `remove_content`, `restrict_content`, `warn_user`, `suspend_user`, `ban_user`, `restore`, `reject_submission` (see [Applying actions](#applying-actions)) |
| `suspendUntil` | Only with `suspend_user` |
| `content.externalContentId` | Present if the case has content (independent of the action) |
| `subject.externalUserId` | Present if the case has a user. Decisions from the user file have only `subject`. |
| `policies[]` | `code`, `title`; may be empty for `dismiss` and `restore` |
| `statementOfReasons` | `locale` (`de` or `en`), `text` (ready-made), `structured` (see below) |
| `decidedAt` | Time of the decision; use it for ordering |
| `appealId`, `replacesDecisionId` | Only for a new decision after a complaint |
| `reviewId` | Only for decisions on a review request (also a new decision after a complaint against one) |
| `restoreScope` | Only with `restore`: `content` or `account` |

`structured`: `action`, `endsAt` (only with a temporary restriction), `territorialScope` (`app`), `facts`, `basedOnNotice`, `noticeSource` (`notice`, `trusted_flagger`, `own_initiative`), `automatedDetection` (the case has a report with `source: system`), `automatedDecision` (only with `automation: full`), `automation` (`none`; `partial`: a moderator confirmed an AI suggestion; `full`: automatic decision, not used yet), `grounds[]` (`basis` `terms` or `law`, `policyCode`, `title`, `lawReference` only with `law`), `redress`.

## `subject.status_changed`

Currently sent when a temporary suspension ends (by an hourly job, so up to about an hour after `suspendUntil`, or together with a decision that takes over its end), and when a new decision on a complaint ends the ban or suspension it replaces. Other status changes come only as `decision.created`.

```json
{
  "id": "evt_01K6R2…",
  "type": "subject.status_changed",
  "createdAt": "2026-10-08T08:15:02.481233Z",
  "app": { "id": "01K6G5H1TR8W4QZ3M0XCB7NAPP", "slug": "photoapp" },
  "subject": { "externalUserId": "u_112", "status": "active" }
}
```

`subject`: `externalUserId`, `status` (`active`, `warned`, `suspended`, `banned`), `suspendedUntil` (only with `suspended`). After a decision the status is the one after the decision, and `createdAt` equals its `decidedAt`. `suspend_user`, `ban_user`, `restore`, decisions on reviews and `restore` with `restoreScope: content` never trigger this event.

## `reports.resolved`

Sent after `decision.created` when the case had reports of users (`source: user`), so you can inform the reporters (Art. 16(5) DSA). Limenia knows reporters only as hashes, so it returns your report IDs.

```json
{
  "id": "evt_01K6G5H2…",
  "type": "reports.resolved",
  "createdAt": "2026-10-01T10:00:00.234567Z",
  "app": { "id": "01K6G5H1TR8W4QZ3M0XCB7NAPP", "slug": "photoapp" },
  "reports": {
    "decisionId": "01K6G5H1TR8W4QZ3M0XCB7NDEC",
    "action": "suspend_user",
    "policies": [{ "code": "harassment_hate", "title": "Harassment and hate speech" }],
    "decidedAt": "2026-10-01T10:00:00.123456Z",
    "appealDeadline": "2027-04-01T10:00:00.123456Z",
    "items": [{ "reportId": "01K6G4…", "externalReportId": "rep_77" }, { "reportId": "01K6G4…" }]
  }
}
```

- At most 100 items per event; larger cases get several events with the same `decisionId` (at most 100 events, i.e. 10 000 reports). Deduplicate by event ID, not by `decisionId`.
- System reports are not included. A later change after a complaint sends no new `reports.resolved`.
- Map `items` via `externalReportId` (or `reportId` from the 201 response) to your reports and users, tell them the outcome in short (e.g. "No violation found" for `dismiss`, "The content was removed" for `remove_content`) and that they can complain until `appealDeadline` (`POST /v1/appeals` with `appellant.type: "reporter"` and this `decisionId`). You write these texts yourself.

## `appeal.resolved`

A moderator decided on a complaint.

```json
{
  "id": "evt_01K6S1…",
  "type": "appeal.resolved",
  "createdAt": "2026-10-05T09:00:00.512345Z",
  "app": { "id": "01K6G5H1TR8W4QZ3M0XCB7NAPP", "slug": "photoapp" },
  "appeal": {
    "id": "01K6S1…",
    "externalAppealId": "appeal_17",
    "decisionId": "01K6G5H1TR8W4QZ3M0XCB7NDEC",
    "appellantType": "subject",
    "outcome": "changed",
    "statementText": "Decision on your complaint\n\n…",
    "resolvedAt": "2026-10-05T09:00:00.498765Z",
    "newDecisionId": "01K6S1…"
  }
}
```

`externalAppealId` only if you set it, `newDecisionId` only with `outcome: "changed"` (the new decision follows as its own `decision.created`). The complaint text is not sent back. Find the person via `appeal.id` or `externalAppealId` and show `statementText` as plain text (see [Complaints](#outcomes)).

## `review.decided`

A moderator decided on a review request. Publish only now.

```json
{
  "id": "evt_01K6T3…",
  "type": "review.decided",
  "createdAt": "2026-10-03T09:12:00.123456Z",
  "app": { "id": "01K6G5H1TR8W4QZ3M0XCB7NAPP", "slug": "photoapp" },
  "review": {
    "id": "01K6T2…",
    "externalReviewId": "upload_881",
    "type": "profile_photo",
    "outcome": "rejected",
    "decidedAt": "2026-10-03T09:12:00.098765Z",
    "decisionId": "01K6T3…",
    "content": { "externalContentId": "photo_881" }
  }
}
```

| `outcome` | What your app does |
|---|---|
| `approved` | Publish. No `decision.created` and no statement of reasons follow. |
| `restricted` | Publish with a restriction (e.g. adults only, blurred). The decision with `restrict_content` follows as `decision.created`; show its statement of reasons to the author. |
| `rejected` | Do not publish. The decision with `reject_submission` follows as `decision.created`; show its statement of reasons. The author can complain. |

`decisionId` only with `restricted` and `rejected`; `decision.created` may arrive first and carries `decision.reviewId`. The event contains neither content nor author; match it via `review.id` or `externalReviewId`. A complaint can later lead to a new decision (`restore` with `restoreScope: "content"`: publish as submitted; or `restrict_content` after a rejection), which comes as `appeal.resolved` plus `decision.created`, never as a second `review.decided`.

## `test.ping`

Sent only by **Send test webhook** in the dashboard. Acknowledge with 2xx within 5 seconds (the test waits less than the 10 seconds of real deliveries).

```json
{ "id": "evt_01K6…", "type": "test.ping", "createdAt": "2026-10-01T10:00:00.123456Z", "app": { "id": "01K6…", "slug": "photoapp" } }
```

---

# Firebase connector

Let Limenia disable and enable Firebase Authentication accounts directly when moderators suspend, ban or restore a user. (https://limenia.eu/docs/firebase-connector/)

Connectors carry out decisions directly in your services, **in addition** to the webhook; they never replace it. Your app still enforces restrictions itself. Setup is done by an admin in the dashboard (tab **Connectors**), which shows the exact commands with your IDs. None of them needs code in your app beyond the right user IDs. Connectors need a plan that includes them.

## What it does

On `suspend_user`/`ban_user` Limenia disables the Firebase Authentication account and revokes its refresh tokens; on `restore` with `restoreScope: account` and at the end of a suspension it enables it again. `restore` with `restoreScope: content` and decisions on reviews never touch the account.

## Requirements

The `externalUserId` you send is the Firebase UID (otherwise `user_not_found` in the delivery log, no retry).

## Setup

Enter the Firebase project ID; create a custom role with `firebaseauth.users.get`, `firebaseauth.users.update` and `resourcemanager.projects.get` and grant it to the service account the dashboard shows; prove ownership with the project label `limenia-tenant=<tenant ID in lower case>`; enable and press **Check access**. A Firebase project can be connected to one app only.

## Token lifetime

ID tokens already issued stay valid up to one hour (Firebase behaviour). Verify tokens with `verifyIdToken(token, true)` (check revoked) where bans must take effect immediately.

## Errors in the delivery log

Each connector call appears in the **Delivery log** next to the webhook delivery.

| Code | Meaning | Retried? |
|---|---|---|
| `user_not_found` | No Firebase user with this UID: the `externalUserId` is not the Firebase UID | no |
| `ownership_not_proven` | The project label `limenia-tenant` is missing or wrong | no |
| `permission_denied` | The service account lacks the custom role | yes |
| `project_not_found` | Wrong Firebase project ID | yes |
| `not_configured` | The connector was switched off or is incomplete | no |
| `timeout`, `unavailable` | Firebase did not answer in time or is unavailable | yes |

---

# Supabase connector

Let Limenia ban and unban Supabase Auth users directly when moderators suspend, ban or restore a user. (https://limenia.eu/docs/supabase-connector/)

Like every connector, it works **in addition** to the webhook and never replaces it; your app still enforces restrictions itself. An admin sets it up in the dashboard (tab **Connectors**).

## What it does

Calls `PUT /auth/v1/admin/users/{id}` of your project with `ban_duration`: `ban_user` → `876000h`; `suspend_user` → the remaining seconds until `suspendUntil`; `restore` (account) and the end of a suspension → `none`. Limenia never deletes users.

## Requirements

The `externalUserId` is the Supabase user UUID (`auth.users.id`).

## Setup

Create a separate secret key (`sb_secret_…`, name e.g. `limenia`) in Supabase, enter the project URL (`https://<ref>.supabase.co`, origin only) and the key, enable and press **Test connection**. Legacy JWT keys (`service_role`) are not accepted.

The stored key is bound to the host of the project URL: if you change the URL to another host, enter the key again. Limenia never sends a stored key to a new host. **Test connection** waits up to 5 seconds and can be repeated after 10 seconds.

## Session lifetime

Supabase cannot end sessions by user ID: an issued access token stays valid until it expires (default up to one hour). Where bans must take effect immediately, check with `getUser()` (asks the auth server) instead of `getClaims()`.

## Errors in the delivery log

| Code | Meaning | Retried? |
|---|---|---|
| `user_not_found` | No user with this UUID: the `externalUserId` is not the Supabase user ID | no |
| `supabase_unauthorized` | The secret key is wrong or was deleted | no |
| `supabase_rejected` | Supabase rejected the request | no |
| `blocked_url` | The project URL is not a public `https` address | no |
| `project_not_found` | The project URL does not point to a Supabase project | yes |
| `not_configured` | The connector was switched off or is incomplete | no |
| `timeout`, `connection_failed`, `unavailable` | Supabase did not answer in time or is unavailable | yes |

---

# RevenueCat connector

Let Limenia revoke promotional entitlements and end web subscriptions of banned users, and detect ban evasion through purchase transfers. (https://limenia.eu/docs/revenuecat-connector/)

Like every connector, it works **in addition** to the webhook and never replaces it. An admin sets it up in the dashboard (tab **Connectors**).

## What it does

On `ban_user` Limenia revokes promotional entitlements you configured and cancels RevenueCat Web Billing subscriptions at period end (optionally refunds Web Billing and Google Play after explicit moderator confirmation); on `suspend_user` it revokes promotional entitlements; on `restore` (account) and at the end of a suspension it grants them back. App Store and Amazon subscriptions cannot be ended by developers; the statement of reasons tells the user how to cancel.

## Requirements

The `externalUserId` is the RevenueCat App User ID (otherwise `revenuecat_customer_not_found`). Do not use e-mail addresses as App User IDs.

## Setup

RevenueCat API v2 secret key with `customer_information:customers:read_write` and `customer_information:subscriptions:read` (or `read_write` if bans cancel or refund), project ID (`proj…`), entitlement IDs of API v2; **Check connection**.

## Ban evasion through purchases

Set RevenueCat's restore behavior to "Keep with original App User ID". Optionally set up the RevenueCat webhook to Limenia ([RevenueCat webhook receiver](#revenuecat-webhook-receiver)) with all events or at least `TRANSFER` and `CANCELLATION`, environment Production, and HMAC signing.

The receiver is described in [RevenueCat webhook receiver](#revenuecat-webhook-receiver).

## What your backend sees

`decision.created` contains nothing about RevenueCat; the statement of reasons contains a generic "Purchases" sentence.

## Errors in the delivery log

| Code | Meaning | Retried? |
|---|---|---|
| `revenuecat_customer_not_found` | No customer with this App User ID: the `externalUserId` is not the RevenueCat App User ID | no |
| `revenuecat_unauthorized` | The secret key is wrong or lacks a permission | no |
| `revenuecat_project_not_found` | Wrong project ID | no |
| `revenuecat_rejected` | RevenueCat rejected the request | no |
| `not_configured` | The connector was switched off or is incomplete | no |
| `revenuecat_unavailable` | RevenueCat did not answer in time or is unavailable | yes |

---

# Device connector

Tie bans to devices without fingerprinting, with Play Integrity Device Recall on Android and Apple DeviceCheck on iOS. (https://limenia.eu/docs/device-connector/)

Ties a ban to the device without fingerprinting: **Android** Play Integrity with Device Recall, **iOS** Apple DeviceCheck. Google and Apple keep a few bits per device and developer account that survive reinstall and factory reset. Limenia sets them for banned/suspended users at their next device check and reads them on every check ([Device checks](#device-checks)).

The API call, its fields and its answers are described in [Device checks](#device-checks). The connector needs a plan that includes it.

## In the app

Get the token with the Flutter plugin `limenia_device` (`LimeniaDevice.requestToken(requestHash: …, cloudProjectNumber: …)`), send it to your backend, never to Limenia. Android needs the project number of the Cloud project linked to Play Integrity; minSdk 24, iOS 15.

## In the backend

Issue the request hash ([Device checks](#post-v1devicescheck)), take the user from the login, forward once, fail open.

## Setup

Android: link Play Integrity to a Cloud project, request Device Recall from Google, create a service account in that project and give the Limenia connector service account shown in the dashboard `roles/iam.serviceAccountTokenCreator` on it, prove ownership with the project label, then **Test connection**. iOS: create a DeviceCheck key (`.p8`), enter team ID, key ID and key, **Test connection**. Do not enable a platform if your developer account already uses these bits for something else.

## Test mode

Test mode is switched on per app in the dashboard. It accepts `platform: "test"` with tokens `test:<device>` (add `:risk` for a device without integrity) on emulators and simulators. Turn it off in the production app.

## Signals, webhooks and quota

- Limenia creates system signals `device_flagged` and `device_risk` for rules. Webhooks contain nothing about devices.
- Quota: Google allows 10 000 decodes per day per project (shared with Firebase App Check). Check only at registration, login and optionally reports.

## Duties of the tenant

The tenant must cover the device check in its privacy policy and store privacy labels, decide on consent for reading device information, and offer users a way to ask for a reset (Apple requires it); a moderator then requests the reset in the user file.

See [Data protection](#data-protection-2).

---

# Store reviews

Collect and answer the reviews of your app in the App Store and Google Play in Limenia — what you set up in App Store Connect, the Play Console and optionally GitHub. (https://limenia.eu/docs/store-reviews/)

The store reviews connector pulls the written reviews of your app from the App Store and Google Play into an inbox in the Limenia dashboard (**Reviews**). Moderators answer them there, group bug reports into tickets and, optionally, turn tickets into GitHub issues.

> **Note:** Store reviews are the ratings of your app in the app stores. They have nothing to do with [pre-moderation reviews](#pre-moderation-reviews) (`POST /v1/reviews`). Store reviews do not use the `/v1` API and send no webhooks to your backend; there is no code to write.

The connector needs a plan that includes store reviews. An admin or owner sets it up per app: tab **Connectors → Store reviews**. The dashboard shows every step with copyable commands.

## What it does

- **Collecting:** Limenia polls both stores every 15 minutes (neither store pushes reviews) and runs a daily full pass to catch edits. Fetching starts after the first successful **Test connection** and covers the last 30 days (Google Play: 7 days). Admins can trigger **Retrieve now** once every 5 minutes per store.
- **Google Play** delivers only reviews with text, of the production track, written or changed in the last 7 days. Older reviews cannot be imported, and an outage of more than 7 days leaves a gap.
- **App Store** returns no star-only ratings and no reviews of tvOS apps.
- **Inbox:** filter by app, status, period, store, stars, category, language, version and ticket. Reviews are separate items, not reports or cases, and are not part of the DSA case flow.
- **Answering:** a moderator writes a reply (from scratch, from a template, or from a suggestion of the optional AI), sees the final text and sends it, one review at a time. Limenia never sends replies automatically.
- **Checks before sending** (always, no override): not empty, within the store's length limit (Google Play 350 characters; App Store 1,000 by default), no HTML, no links except to the allowed link domains of the app (up to 10), no e-mail addresses or phone numbers, no request for a better rating, no incentive linked to a rating and no promise of a refund.
- **After sending:** Apple reviews replies for up to 24 hours before publishing them. Replies written directly in the store console are shown as such. Deleting replies is not supported; a new reply replaces the current one.
- **Spam and abuse:** there is no API to report reviews to the stores. The dashboard links the store console and suggests a reason text.
- **Tickets:** with the optional AI, bug reports of an app are grouped into tickets (title, summary, count, affected versions, stores, average stars, urgency). Moderators can also create, merge and split tickets by hand.
- **Optional AI:** the owner can switch on AI suggestions for store reviews. They classify each review (bug report, feature request, complaint, praise, question, spam or abuse, other), detect urgency and draft a reply in the language of the review. Classifications count against the monthly AI quota of the plan. Without AI, the inbox, templates, your own replies and manual tickets still work.

## App Store setup

1. The Account Holder of your Apple developer team must have requested access to the App Store Connect API once.
2. In App Store Connect open **Users and Access → Integrations** and create an API key **only for Limenia** with the role **Customer Support**. Download the `.p8` file; Apple allows the download only once.
   - A **team key** (default) sees all apps of the team; Limenia only queries the app you enter. Alternatively use an **individual key** of a user who sees only this app; it has no issuer ID and stops working when that user is removed.
   - Do not use an Admin key, and do not share the key with other tools: they would share Apple's rate limit.
3. Enter in the dashboard:
   - the **Apple ID** of the app (numeric, from **App Information**; not the bundle ID),
   - the type of key (team or individual),
   - the **key ID** (10 characters),
   - the **issuer ID** (team keys only, shown above the key list),
   - the `.p8` file (upload or paste).
4. Press **Test connection**. It reads one review. It cannot prove the right to reply; a missing right shows up when the first reply is sent.

The key is stored encrypted, never shown again and can be replaced at any time.

## Google Play setup

You use a service account in **your own** Google Cloud project. Limenia provides none.

1. Enable the Google Play Android Developer API in your project:

   ```bash
   gcloud services enable androidpublisher.googleapis.com --project=PROJECT_ID
   ```

2. Create a service account. It needs no role in the project:

   ```bash
   gcloud iam service-accounts create limenia-reviews --project=PROJECT_ID --display-name="Limenia Reviews"
   ```

3. In the Play Console open **Users and permissions** and invite the service account for **this app only**, with the permissions **View app information (read-only)** and **Reply to reviews**. Nothing more is needed. Only an account admin of the Play Console can invite; an invitation can take up to 36 hours to take effect.
4. Create a JSON key and upload it in the dashboard together with the **package name** (e.g. `com.example.app`):

   ```bash
   gcloud iam service-accounts keys create limenia-reviews-key.json \
     --iam-account=limenia-reviews@PROJECT_ID.iam.gserviceaccount.com
   ```

   Newer Google Cloud organisations block key creation with the policy `iam.managed.disableServiceAccountKeyCreation`; relax it for this one project only.
5. Press **Test connection**. Typical errors: invalid key, permission missing or app not shared yet, API not enabled, app not found.

**Without a key file:** instead of uploading a key, you can let Limenia impersonate your service account. Give the Limenia service account shown in the dashboard the role **Service Account Token Creator** (`roles/iam.serviceAccountTokenCreator`) on your service account (not on the project), prove ownership with the project label `limenia-tenant=<your tenant ID in lower case>` and a custom role `limeniaReviewsConnector` with `resourcemanager.projects.get` bound to the same Limenia account, and enter the service account e-mail together with the package name. The dashboard shows the exact commands. Organisations that restrict roles to their own domain (`iam.allowedPolicyMemberDomains`) must allow this for the project.

## Both stores

- A store app can belong to only one Limenia app.
- **Switching off** pauses fetching and sending and keeps the access data. **Disconnecting** deletes the stored key and stops everything at once; stored reviews, drafts and tickets remain until their retention ends.
- Google allows 200 reads per hour and 2,000 replies per day per app, shared with your other tools; Limenia stays below that and waits when it gets close. Apple allows 3,600 requests per hour per key.

## GitHub (optional)

Moderators can turn a ticket into a GitHub issue, one ticket at a time. Closing the issue sets the ticket to done, reopening it sets it to open again.

1. An admin opens **Reviews → Settings → GitHub → Connect with GitHub** and installs the GitHub App **Limenia Moderation** on **selected repositories**. It asks for **Issues: read and write** and **Metadata: read-only**, nothing else.
2. Sign in to GitHub to confirm the installation belongs to you. If an organisation owner must approve the installation, link it after the approval with **Link existing installation**.
3. Choose the target repository per app. A public repository needs an explicit confirmation, because issue texts become public.

Issues contain the ticket title, the AI summary (marked as such), counts per store, versions, period, average stars, urgency and a link back to Limenia. They never contain names of reviewers, device details, verbatim review texts or store review IDs. Only GitHub.com is supported. GitHub stores data in the USA; Limenia sends data there only when you create an issue.

## Data protection

- Names and nicknames of reviewers are never stored. Limenia stores stars, title, text, language, country (App Store), app version and device class (Google Play) and timestamps.
- The AI, if switched on, receives stars, title, text, store, app name and your reply hints, never names, device data or IDs.
- Reviews are not linked to user files.
- Retention: by default 183 days (owner setting, 30 to 730 days), counted from the review or the last reply sent.
- **Objection:** an admin can delete a single review with **Delete (objection)**. Limenia then blocks it from being imported again. The review stays in the store.
- The App Store Connect API and the Google Play Developer API are run by Apple and Google. As the tenant you are the controller for the reviews; mention the processing in your privacy policy. See [Data protection](#data-protection-2).

---

# DSA

What the Digital Services Act asks of your app, what Limenia does for you and what remains your job — notice and action, statements of reasons, complaints, trusted flaggers and transparency. (https://limenia.eu/docs/dsa/)

Limenia gives you the moderation workflow the EU Digital Services Act (DSA) expects from online platforms. The tenant stays the provider: it decides, it is responsible for its decisions and texts, and its app must carry out the decisions and talk to its users. This page is guidance for developers, not legal advice.

## Overview

| DSA | Limenia does | Your app does |
|---|---|---|
| Notice and action (Art. 16) | Accepts reports (`POST /v1/reports`), bundles them into cases, records `goodFaith`, never refuses reports because of the plan | Offers a report function for content and users, sets the reporter from the login, confirms receipt to the reporter |
| Informing reporters (Art. 16(5)) | Sends `reports.resolved` with the outcome and the deadline for complaints | Tells each reporter the outcome in its own words |
| Statement of reasons (Art. 17) | Creates it for every decision, as text and structured fields | Shows it to the affected user as plain text, also when the account is blocked |
| Internal complaint handling (Art. 20) | Accepts complaints for six months (`POST /v1/appeals`), a human decides, sends `appeal.resolved` with a reasoned answer | Offers a complaint function to affected users and reporters, shows the answer |
| Out-of-court dispute settlement (Art. 21) | Names it in the redress text and in every answer to a complaint | Nothing beyond showing the texts |
| Trusted flaggers (Art. 22) | Registry per tenant, priority for their reports | Sets `trustedFlaggerId` for people who verifiably act for one |
| Measures against misuse (Art. 23) | Warns and suspends reporters, refuses their reports with 403 `reporter_suspended` | Shows warnings and the end of a suspension |
| Transparency reports (Art. 15, 24) | Counts per month and exports the report templates of the Commission | The tenant completes and publishes the report |
| Transparency database (Art. 24(5)) | Optionally submits statements of reasons per app | Nothing |

## Notice and action

- Every user must be able to report content and other users in your app. Use the [report sheet](#flutter-packages) of the Flutter package or your own form, and forward reports with [POST /v1/reports](#reports).
- Let the reporter confirm that the report is accurate and complete and send `goodFaith: true` only if they did (Art. 16(2)(d)).
- Confirm the receipt in your app; Limenia returns a `reportId` you can show or store.
- After the decision, `reports.resolved` tells you which reports were handled. Tell each reporter the outcome briefly and that they can complain until `appealDeadline` (see [Webhook events](#reportsresolved)).

## Statement of reasons

Every decision carries a statement of reasons (Art. 17): the action, its duration, the facts, the policies or laws it is based on, whether it followed a notice (`noticeSource`: `notice`, `trusted_flagger`, `own_initiative`), whether automated means were used (`automatedDetection`, `automation`) and the redress options. The tenant sets the redress text in the dashboard (**DSA → Redress**).

Show `statementOfReasons.text` to the affected user for every decision except `dismiss`, as plain text. If the account is blocked, use a channel outside the app (e-mail, login screen). See [Showing the statement of reasons](#showing-the-statement-of-reasons).

## Complaints

Affected users can complain against restricting decisions, reporters against any decision on a case they reported, for six months. A human decides every complaint; the answer names the further options (out-of-court dispute settlement, courts). Your app needs a complaint function for both groups. See [Complaints](#complaints).

## Trusted flaggers

The tenant registers trusted flaggers in the dashboard (name, recognition reference, areas). Their reports get at least priority `high`, and statements of reasons say the decision followed a report by a trusted flagger without naming it. Limenia has no separate form or login for trusted flaggers: they report through your app or your own channel, and your backend sets `trustedFlaggerId`. See [Reports](#trusted-flaggers).

## Misuse

Moderators can warn reporters who frequently send manifestly unfounded reports, and after a delivered warning suspend their reports for up to 365 days. Complaints of affected users are never blocked. See [Reporters and misuse](#reporters-and-misuse).

## Transparency

- **Transparency reports:** Limenia counts reports, decisions and complaints per month. An admin exports the report templates of the Commission (CSV files) for a period, per app or for all apps. Some parts (orders of authorities, out-of-court disputes, staff, qualitative information) stay empty for the tenant to complete. Limenia never publishes the report.
- **Transparency database:** per app, an admin can let Limenia submit the statements of reasons of restricting decisions (`remove_content`, `restrict_content`, `reject_submission`, `suspend_user`, `ban_user`) to the DSA transparency database of the Commission, with the tenant's own token. No personal data and no external IDs are sent; facts are replaced by a standard text unless the tenant opts in. Small and micro enterprises are usually exempt; the tenant decides.

## Child safety

Reports with the categories `child_safety` and `protection_of_minors` make the case `urgent`, and Limenia keeps no copy of the media (only the URL you sent). Limenia does not report to authorities; securing evidence and any report to authorities (Art. 18) remain with the tenant. There is no separate alert for urgent cases yet; moderators filter them in the dashboard.

## Store requirements

The app tab **DSA → Store requirements** is a checklist of what the App Store and Google Play expect from apps with user-generated content. Four items are checked automatically (a report has arrived, the webhook is active, a redress text is set, an active policy exists); the others (filtering content, blocking users, contact information, accepting the terms before posting, account deletion in the app and on the web) an admin ticks off. It is guidance, not legal advice.

## What remains with the tenant

- Deciding, and being responsible for decisions, statements of reasons and answers to complaints, also when they are built from templates.
- Its terms of use and policies.
- Carrying out decisions in the app and informing its users; Limenia never contacts end users.
- Checking which DSA obligations apply (for example exemptions for small and micro enterprises).
- Publishing transparency reports.
- Data protection duties (see [Data protection](#data-protection-2)).

---

# Data protection

What to send to Limenia and what not, how reporters are pseudonymised, how long data is kept and where it is hosted. (https://limenia.eu/docs/data-protection/)

## Roles

The tenant is the controller for the data of its users. Limenia processes it on the tenant's behalf under a data processing agreement: [German original](https://limenia.eu/avv/), [English translation](https://limenia.eu/en/dpa/). Services the tenant connects itself (Firebase, Supabase, RevenueCat, Google Play Integrity, Apple DeviceCheck, the store APIs, GitHub) are the tenant's own services, not sub-processors of Limenia.

## What to send

Send only what moderators need to decide:

- The reported content and its context, everything else as IDs.
- No e-mail addresses, phone numbers, IP addresses, device identifiers or locations in `externalUserId`, `displayName` or `context`.
- `externalUserId`: a stable, pseudonymous ID of your system (for connectors the Firebase UID, the Supabase user UUID or the RevenueCat App User ID), never an e-mail address.
- `displayName`: only what other users see anyway.
- The only exception are HMACs of e-mail address and phone number in `identifiers` for [ban evasion across apps](#ban-evasion-across-apps), never the plain values.
- Never send device tokens, API keys or session tokens in any field.

## Pseudonymised reporters

Reporters are stored only as a truncated SHA-256 hash of app ID and reporter ID (a pseudonym). Limenia cannot tell you who reported something; `reports.resolved` returns your own report IDs instead. To check a complaint of a reporter, Limenia compares hashes.

## Hosting and security

- Data is stored in the EU. Media copies are kept in private object storage and shown to moderators only through short-lived signed links, blurred by default.
- Limenia logs IDs, never content.
- Reports with the categories `child_safety` and `protection_of_minors` keep no media copy at all, only the URL.
- The optional AI pre-screening runs in the EU or EFTA, only after the owner opted in, and receives content without user IDs, names or reporter information.
- Limenia trains its own moderation models only with anonymised data: names, user names, contact details, links and IDs are masked, and the text is cut off from tenant, app, user and time. Media, user and display names and child-safety cases are never used. The owner can opt out in the dashboard at any time ([DPA, Annex 5](https://limenia.eu/en/dpa/#anlage-5)).

## Retention

Retention is set by the tenant (owner, dashboard **Settings → Retention**); deletion is automatic, usually within a day after the period ends.

| Data | Default |
|---|---|
| Snapshots of reported content and media copies | 183 days |
| Decisions, decided cases, complaints, user files | 365 days |
| Copies of approved review requests | 30 days |
| Signals and device checks | 30 days |
| Store reviews and tickets | 183 days |
| Audit log | 730 days |
| Delivery log | 90 days |
| Idempotency keys | 24 hours |

- A **legal hold** on a case suspends its deletion until it is released.
- There is no deletion API for apps, and no per-user deletion. Data of a deleted account stays until its retention ends. For a request of a data subject, contact Limenia.
- [Identifiers](#ban-evasion-across-apps) live as long as the user file they belong to.

## Duties of the tenant

- Name the processing by Limenia in the privacy policy of the app (reports, moderation, complaints; device checks and store reviews if you use them).
- With the [device connector](#device-connector): cover the device check in the privacy policy and the store privacy labels, decide on consent for reading device information, and offer users a way to ask for a reset.
- With [ban evasion across apps](#ban-evasion-across-apps) (coming soon): a data protection impact assessment and a note in the privacy notices of all apps that take part.
- Keep logs of your own backend free of content and personal data (see the [hard rules](#hard-rules)).

---

# SDKs and tools

Flutter packages limenia and limenia_device, the example backends, typed clients from the OpenAPI spec, llms.txt and the prompt for coding agents. (https://limenia.eu/docs/sdks/)

## Flutter packages

| Package | What it does |
|---|---|
| [`limenia`](https://pub.dev/packages/limenia) | API models and validation, a report queue with retries, the user's own status, and ready-made widgets in `package:limenia/ui.dart`: report sheet, complaint form, statement of reasons, notice for restricted accounts. Flutter 3.35 or newer. |
| [`limenia_device`](https://pub.dev/packages/limenia_device) | Optional plugin for the [device connector](#device-connector): gets a Play Integrity or DeviceCheck token. Flutter 3.24 or newer, Android minSdk 24, iOS 15. |

```bash
flutter pub add limenia
flutter pub add limenia_device   # only with the device connector
```

- Both packages run in the app and never talk to Limenia directly: you implement `LimeniaTransport` against **your** backend, which holds the API key. See [Flutter with Firebase](#transport-over-callable-functions) and [Flutter with Supabase](#app-flutter-1).
- Pure Dart programs without Flutter (e.g. a Dart server) stay on `limenia` 0.11.x, which has no widgets.
- Source code and issues: <https://github.com/DL3KB/limenia-flutter> (Apache 2.0).

## Example backends

<https://github.com/DL3KB/limenia-examples> (Apache 2.0) has one complete backend per stack: Node.js with Express, Firebase Cloud Functions, Supabase Edge Functions, AWS Lambda, Go, Python with FastAPI and PHP with Laravel. Each one forwards reports, returns the user's status, runs the device check and receives verified webhooks, with tests against the [signature test vector](#test-vector). They use plain HTTP and the platform's crypto, no SDK. Start from the [integration guide](#choose-your-path) of your stack.

## Typed clients from the OpenAPI spec

There is no official server SDK package. The [OpenAPI specification](#openapi-specification) is complete enough to generate typed clients. For TypeScript, for example with `openapi-typescript` and `openapi-fetch`:

```bash
npx openapi-typescript https://limenia.eu/openapi/v1.yaml -o src/limenia.gen.ts
npm install openapi-fetch
```

```ts
import createClient from "openapi-fetch";
import type { paths } from "./limenia.gen";

const limenia = createClient<paths>({
  baseUrl: process.env.LIMENIA_BASE_URL ?? "https://app.limenia.eu",
  headers: { Authorization: `Bearer ${process.env.LIMENIA_API_KEY}` },
});

const { data, error, response } = await limenia.POST("/v1/reports", {
  params: { header: { "Idempotency-Key": "report-7f3c9a" } },
  body: {
    source: "user",
    reasonCategory: "spam",
    reporter: { externalUserId: "u_829" },
    subject: { externalUserId: "u_112" },
  },
});
if (error) console.error(response.status, error.code); // problem+json, see API basics
else console.log(data.reportId, data.caseId);
```

Other languages: use the OpenAPI generator of your choice. Keep retries, idempotency keys and the webhook signature check as described in [API basics](#api-basics) and [Receiving webhooks](#receiving-webhooks); generators do not add them.

## Documentation for coding agents

| File | Content |
|---|---|
| <https://limenia.eu/llms.txt> | Index of this documentation for language models ([llmstxt.org](https://llmstxt.org)) |
| <https://limenia.eu/docs/integration.md> | Every page of this documentation in one Markdown file |
| <https://limenia.eu/llms-full.txt> | All pages and the OpenAPI specification in one file |
| <https://limenia.eu/openapi/v1.yaml> | The OpenAPI specification |

## Prompt for coding agents

The dashboard has a card **Prompt for your coding agent** on the app tab **Connection** and in the setup wizard. Pick your stack, copy the prompt and paste it into Claude Code, Cursor or Copilot. The prompt names the app, the base URL, the stack and the connectors switched on, tells the agent to read this documentation and to follow the [hard rules](#hard-rules), and lists what to build. It never contains the API key: put the key into `LIMENIA_API_KEY` of your backend first, and do not paste it into the chat.

---

# Testing

How to test an integration safely — a test app, self-tests a coding agent can run, the dashboard's webhook test and an end-to-end check. (https://limenia.eu/docs/testing/)

## Test safely

- **There is no sandbox.** Every API key writes to the real system, whatever its prefix. Create a separate **test app** in the dashboard (for example `myapp-test`) with its own API key and webhook, and use it for development, CI and staging.
- Test reports appear as real cases in the test app. Decide them there; they never touch the production app.
- Use made-up external IDs (`selftest_author`) and no real content or personal data in tests.
- Your own production users are never affected by a test app: user files, cases and keys are separate per app.
- The [device connector](#device-connector) has a test mode per app that accepts `platform: "test"` tokens on emulators and simulators.
- Unit-test your webhook receiver with the [signature test vector](#test-vector) and an injected clock.

## Self-test

Steps a coding agent can run itself. They need `LIMENIA_API_KEY` set in the shell by the user (do not ask for the value) and, for a real end-to-end test, a **test app** in the dashboard.

**1. Key and address.**

```bash
curl -sS -w '\nHTTP %{http_code}\n' "$LIMENIA_BASE_URL/v1/ping" -H "Authorization: Bearer $LIMENIA_API_KEY"
```

Expected: `HTTP 200` and `"tenantStatus":"active"`. `401 unauthenticated`: wrong or revoked key. `"tenantStatus":"onboarding"`: the tenant has not finished setup; reports will answer 403 `tenant_not_active`.

**2. Send a test report** (to the test app only):

```bash
KEY="report-selftest-$(date +%s)"
BODY='{"source":"user","reasonCategory":"spam","reporter":{"externalUserId":"selftest_reporter"},"subject":{"externalUserId":"selftest_author","displayName":"Self test"},"content":{"externalContentId":"selftest_content_1","contentType":"comment","text":"Limenia integration self test"},"externalReportId":"selftest_1"}'
curl -sS -w '\nHTTP %{http_code}\n' -X POST "$LIMENIA_BASE_URL/v1/reports" \
  -H "Authorization: Bearer $LIMENIA_API_KEY" -H "Content-Type: application/json" \
  -H "Idempotency-Key: $KEY" --data "$BODY"
```

Expected: `HTTP 201` with `reportId`, `caseId` and `"caseCreated":true` (`false` if a case on `selftest_content_1` is still open).

**3. Idempotency.** Send the same command again (same `KEY`, same `BODY`): `HTTP 201` with the same `reportId` and `caseId`. Change the body (e.g. `"reasonCategory":"other"`) with the same key: `HTTP 409` with `"code":"idempotency_key_reused"`.

**4. Validation.** Without the `Idempotency-Key` header: `HTTP 400`, `"code":"validation_failed"`, `errors` with `"field":"Idempotency-Key"`.

**5. Status.**

```bash
curl -sS "$LIMENIA_BASE_URL/v1/subjects/selftest_author/status" -H "Authorization: Bearer $LIMENIA_API_KEY"
# {"externalUserId":"selftest_author","status":"active"}
```

**6. Your webhook receiver, locally.** Unit-test the signature check against the [test vector](#test-vector). Then send a signed `test.ping` to your running receiver:

```bash
BODY='{"id":"evt_local_1","type":"test.ping","createdAt":"2026-10-01T10:00:00Z","app":{"id":"a","slug":"demo"}}'
T=$(date +%s)
SIG=$(printf '%s' "$T.$BODY" | openssl dgst -sha256 -hmac "$LIMENIA_WEBHOOK_SECRET" -hex | sed 's/.* //')
curl -sS -w 'HTTP %{http_code}\n' -X POST http://localhost:3000/limenia/webhook \
  -H 'Content-Type: application/json' -H "Limenia-Signature: t=$T,v1=$SIG" --data "$BODY"
```

Expected: `HTTP 204` (or another 2xx). Send it again: still 2xx (duplicate). With a wrong `v1`, a changed body or `T=$(( $(date +%s) - 600 ))`: `HTTP 401`.

## The dashboard's webhook test

There is no API to trigger it; ask the user to open the test app, tab **Connection → Webhook**, and press **Send test webhook**. It sends one `test.ping` (5 s timeout, no retry; again after 10 s at the earliest) and works even while the webhook is switched off, as long as URL and secret are set. Your receiver must be reachable over public HTTPS (deployed, or through an HTTPS tunnel). Expected in the dashboard: an HTTP status 2xx and a duration; in your receiver's log: a `test.ping` event ID.

| Result | Cause |
|---|---|
| `http_status` 401 | Wrong secret, or the body was parsed before verifying |
| `http_status` 3xx | Redirect: enter the final URL (redirects are not followed) |
| `http_status` 404 or 405 | Wrong path or method of your route |
| `timeout` | The answer took over 10 s |
| `connection_failed` | DNS, TLS or connection problem: is the host public and the certificate valid? |
| `blocked_url` | The URL resolves to a private or internal address |

## Decide a test case

Ask the user to open **Cases** in the dashboard: the case of step 2 appears with the content `selftest_content_1` and the reported user `selftest_author`. Let them decide it in the test app (e.g. `dismiss`, or `remove_content`). Expected at your receiver within seconds: `decision.created` with that `externalContentId`, and `reports.resolved` with `"externalReportId":"selftest_1"`. Both appear in the **Delivery log** with their status.

## End to end in the app

Report something from the real app (through your backend), check that the reporter ID comes from the login, decide each action your app supports once in the test app, and confirm the app applies it and shows the statement of reasons.

Then go through the [go-live checklist](#go-live-checklist).

---

# Go-live checklist

Everything to check before your app goes live with Limenia — setup, reports, webhooks, complaints, optional features and operations. (https://limenia.eu/docs/go-live/)

## Setup

- [ ] The tenant is active: `GET /v1/ping` with the production key returns `tenantStatus: "active"`.
- [ ] The API key is only in the backend's secret store (`LIMENIA_API_KEY`), not in the app, the repository or logs. Key rotation is practised (create, deploy, revoke).
- [ ] The webhook URL is `https`, public, without redirects, and the webhook is **active**. The secret is in `LIMENIA_WEBHOOK_SECRET`.
- [ ] Supported actions in the dashboard match what the app can carry out.

## Reports

- [ ] External IDs are stable and pseudonymous (Firebase UID, Supabase user UUID or RevenueCat App User ID where a connector needs it).
- [ ] The reporter, complaining person, author and device-check user come from the backend login, never from the app.
- [ ] Reported content always includes its author as `subject`.
- [ ] Every report has a stored idempotency key that stays the same on retries; retries with backoff on network errors, 429 and 5xx, `Retry-After` respected; a queue resends within 24 hours.
- [ ] `reasonCategory` codes are agreed with the tenant; suspected abuse of minors uses `child_safety`.
- [ ] Media URLs are `https`, fetchable without login, valid for at least an hour, in a supported format and at most 20 MB.
- [ ] No e-mail addresses, IP addresses or similar data in any field. Logs contain IDs only.

## Webhooks

- [ ] The signature is verified over the raw body, constant time, 300 s tolerance, clock synced, tested with the test vector; previous secret accepted during rotation.
- [ ] The receiver answers 2xx within 10 s and does heavy work asynchronously.
- [ ] Duplicates are detected by event ID; actions are idempotent; older events do not overwrite newer ones.
- [ ] Every action of [Applying actions](#applying-actions) is handled (`reject_submission` only with reviews), `restore` follows `restoreScope`, unsupported actions are acknowledged with 2xx and logged.
- [ ] The app lifts suspensions itself at `suspendUntil`.
- [ ] The statement of reasons reaches the affected user as plain text, also when the account is blocked.
- [ ] A reconciliation via `GET /v1/subjects/{externalUserId}/status` (e.g. at login) catches lost events.

## Complaints and reporters

- [ ] The backend accepts complaints, sets `appellant.externalUserId` from the login and stores `appealId` per person.
- [ ] `appeal.resolved` answers reach the person completely as plain text.
- [ ] Reports carry `externalReportId` (or `reportId` is stored); on `reports.resolved` reporters learn the outcome and the `appealDeadline`.
- [ ] `reporterWarning` and `403 reporter_suspended` are shown to the reporter; `trustedFlaggerId` is set only from the backend's own records.

## Reviews, signals, connectors (only if used)

- [ ] Review types are active in the dashboard; submitted content is visible only to its author until `review.decided`; `restricted` and `rejected` are handled; `GET /v1/reviews/{reviewId}` catches lost events.
- [ ] Signal types and rules exist; signals are batched (at most 100), keyed and contain no personal data of third parties.
- [ ] Each connector shows a successful check in the dashboard and the user IDs match its requirement.
- [ ] Ban evasion across apps: the identifier key is only in the backend's secret store (`LIMENIA_IDENTIFIER_KEY`), never in the app; your implementation reproduces the check values of the dashboard; identifiers are sent at registration and on every change of e-mail address or phone number; the dashboard shows no identifiers discarded for a wrong format or key version.
- [ ] Device connector: check at registration and every login (also of banned accounts before rejecting), Android tokens forwarded undecoded with a backend-issued request hash, fail-open, never ban on the device flag alone, test mode off in production, privacy texts updated.

## Test and operations

- [ ] **Send test webhook** succeeded, and every supported action was tested end to end in a test app ([Testing](#testing)).
- [ ] Someone watches the **Delivery log** for `failed` deliveries and resends them.
- [ ] Someone reads the [troubleshooting](#troubleshooting) page before the first incident.

---

# Troubleshooting

Common errors when integrating Limenia and how to fix them — API answers, webhook signatures, deliveries, connectors and media. (https://limenia.eu/docs/troubleshooting/)

## API answers

| Symptom | Cause | Fix |
|---|---|---|
| 401 `unauthenticated` | Key missing, mistyped, revoked, or the header is not `Authorization: Bearer <key>` | Check `$LIMENIA_API_KEY` with `GET /v1/ping`; create a new key if it was revoked. Do not sign your app user out. |
| 403 `tenant_not_active` | The setup wizard of the tenant is not finished | An owner finishes it in the dashboard; it can take up to 30 s to take effect. |
| 400 `validation_failed` with field `Idempotency-Key` | The header is missing, empty, longer than 200 characters or sent twice | Send exactly one key of 1 to 200 characters. |
| 400 `validation_failed` at `/subject` | Neither `subject` nor `content` was sent | Send at least one; with content always its author as `subject`. |
| 400 `validation_failed` at `/goodFaith` | `goodFaith` sent with `source: system` | Send `goodFaith` only with `source: user`. |
| 400 `bad_request` | Invalid JSON, a wrong type, a date that is not RFC 3339, or a body over 1 MiB | Validate the body; send media as URLs, not inline. |
| 404 `not_found` on `GET /v1/appeals/{appealId}` or a decision | The ID belongs to another app (another API key) or a typo | Use the key of the app the decision belongs to. |
| 404 `not_found` for a path | Wrong base URL, e.g. `/v1` twice | `LIMENIA_BASE_URL` is `https://app.limenia.eu` without `/v1`. |
| 409 `idempotency_key_reused` | The same key was used for a different body | Derive the key from your own request ID; never reuse it for another request. |
| 429 `rate_limited` | More than 10 requests per second per key | Wait `Retry-After`, batch signals, queue spikes of review requests. |
| 403 `feature_not_in_plan`, 402 `subscription_required` | Reviews, signals or device checks are not in the plan or the subscription expired | An owner changes the plan; reports and complaints keep working. |
| 403 `reporter_suspended` | The reporter's reports are suspended (Art. 23 DSA) | Show `suspendedUntil`; do not retry. |
| 409 `appeal_window_closed`, `appeal_already_open` | Six months passed, or the person already has an open complaint | Show the reason to the user. |
| 403 `appeal_not_allowed` | E.g. the affected user complains against `dismiss`, or someone who did not report the case complains as reporter | Offer complaints only to the people who may complain (see [Complaints](#complaints)). |
| 400 `review_type_unknown`, `signal_type_unknown` | The code is not an active type of this app | Create or activate the type in the dashboard (tab **Moderation**). |
| Requests time out after a pause | The first request after a quiet period can be slower | Use a client timeout of about 30 s and retry. |

## Webhook signature fails

- **The body was parsed before verifying.** Frameworks that parse JSON first (Express `express.json()`, `JSON.stringify(req.body)`, Laravel `$request->all()`) change bytes. Verify over the raw body: `express.raw()`, `req.rawBody` in Cloud Functions, `await req.arrayBuffer()` in Deno, `$request->getContent()` in Laravel, `await request.body()` in FastAPI.
- **Wrong secret.** The secret is the whole string including `whsec_`. After **Rotate secret** the old one stops working at once: accept both during the switch (`LIMENIA_WEBHOOK_SECRET_PREVIOUS`).
- **`timestamp_out_of_range`.** Your server clock is off by more than 300 seconds; sync it with NTP. The documentation test vector always fails this check unless you inject the clock.
- **Hex compare.** `v1` is lower-case hex of the HMAC; compare the decoded bytes or the hex strings in constant time.
- **Body decoded on Lambda.** Decode `event.body` when `event.isBase64Encoded` is set before verifying.

## Webhooks do not arrive

- **The webhook is not active.** Without URL and secret, or when switched off, decisions are not delivered, also not later. Reconcile with `GET /v1/subjects/{externalUserId}/status`.
- **`blocked_url`.** The URL resolves to a private or internal address. Use a public HTTPS endpoint.
- **`http_status` 3xx.** Limenia does not follow redirects: enter the final URL (watch out for `http` to `https` and trailing-slash redirects).
- **`http_status` 401 or 403.** An auth middleware or a firewall in front of your route blocks Limenia. The webhook route must be public; the signature is the authentication. Limenia sends from no fixed IP address, so IP allowlists do not work.
- **`timeout`.** Answer within 10 seconds; store the event and process it asynchronously.
- **Deliveries are `failed`.** After 12 attempts (about 20 hours) Limenia gives up. Fix the receiver, then resend from the **Delivery log**.
- **Events arrive twice or out of order.** That is expected: deduplicate by event ID and skip events older than the last applied change (see [Answers, retries, order](#answers-retries-order)).

## Connectors

- **`user_not_found` (Firebase, Supabase) or `revenuecat_customer_not_found`.** The `externalUserId` you send is not the user ID of that service. The connector needs the Firebase UID, the Supabase user UUID or the RevenueCat App User ID.
- **`ownership_not_proven` (Firebase).** The project label `limenia-tenant=<tenant ID in lower case>` is missing.
- **Banned users stay signed in.** Issued tokens stay valid up to an hour; check revocation where bans must take effect at once (see [Firebase connector](#token-lifetime), [Supabase connector](#session-lifetime)).
- **`invalid_device_token`.** The token was decoded before (Android tokens must be forwarded unchanged), the request hash does not match, the token is older than 15 minutes, or an iOS debug build was sent without `environment: "development"`.
- **`device_connector_not_configured`.** The platform is not switched on for the app, or a `test` token was sent without test mode.

## Media are missing in a case

- The URL must be fetchable with a plain `GET` without login for at least an hour (e.g. a signed URL), over `https`, from a public address, with at most 3 redirects.
- At most 20 MB per file; supported are JPEG, PNG, GIF, WebP, MP4, WebM and QuickTime. HEIC, HEIF and AVIF are not supported.
- For `child_safety` and `protection_of_minors` Limenia keeps no copy on purpose.
- See [Media](#media).

## Identifiers are discarded

Ban evasion across apps is coming soon and discards identifiers until it is enabled for your tenant. Once enabled, compare the check values in the dashboard with your implementation (see [Self-test with the check values](#self-test-with-the-check-values)).

---

# FAQ

Short answers to the questions developers ask most when integrating Limenia. (https://limenia.eu/docs/faq/)

## Can my app call Limenia directly?

No. The API key must stay in your backend, so the app talks only to your backend, and your backend calls Limenia. The `/v1` API sends no CORS headers for this reason. In Flutter, implement `LimeniaTransport` against your backend (see [SDKs and tools](#flutter-packages)).

## Is there a sandbox or test mode?

No. Every API key writes to the real system; the key prefix (`lm_live_`, older keys `lm_test_`) does not change that. Create a separate test app (see [Testing](#testing)). The device connector has its own test mode for emulators.

## Does Limenia store my users' content?

Only what you send with a report or review request: a snapshot of the content and copies of the media. Limenia never reads your database or your app. See [Data protection](#data-protection-2).

## Do I need to send the reporter?

For reports of users, yes: send the reporter's ID from your login. Limenia stores it only as a hash, needs it to bundle reports, to check complaints of reporters and to act against misuse (Art. 23 DSA). Omit it for `source: system`.

## What happens if my webhook is down?

Limenia retries for about 20 hours (12 attempts). After that the delivery is `failed` and an admin can resend it from the delivery log. As a safety net, call `GET /v1/subjects/{externalUserId}/status` at login. Decisions taken while the webhook is switched off are never delivered.

## Why did I get the same event twice?

Delivery is at least once. Deduplicate by the event ID (`Limenia-Event-Id`) and make your actions idempotent (see [Receiving webhooks](#answers-retries-order)).

## Who lifts a suspension when it ends?

Your app, at `suspendUntil`. Limenia also sends `subject.status_changed` when a suspension has ended, up to about an hour later. With the Firebase or Supabase connector, Limenia also enables the account again.

## Can a decision be taken back?

Yes, through a complaint (`changed`) or a new decision with `restore`. Both arrive as a new `decision.created`. See [Complaints](#outcomes).

## Can moderators decide automatically?

No. A human decides every case, complaint and review request. The optional AI pre-screening only suggests; fully automated decisions are not used.

## Can I delete data of a user through the API?

No. There is no deletion API. Data is deleted automatically when its retention ends; for a request of a data subject, contact Limenia. See [Retention](#retention).

## Can I send reports in languages other than English or German?

Yes, content in any language is accepted. Statements of reasons come in the tenant's language (German or English); use the structured fields for other languages.

## What about bans across several of my apps?

Ban evasion across apps is coming soon and available on request. You can already send the optional `identifiers`; they are discarded until the feature is enabled. See [Ban evasion across apps](#ban-evasion-across-apps).

## Where do I report a problem with the documentation or the API?

Write to Limenia through the contact page of <https://limenia.eu>. Problems with the Flutter packages or the examples can go to their GitHub repositories.

---

# Changelog

Changes of the public API (/v1 and webhook events), newest first. (https://limenia.eu/docs/changelog/)

The current API version is **0.33.0** (2026-10-15). The list contains only versions that changed the public API (the `/v1` operations and the webhook events); versions in between changed nothing you can see. All changes within `/v1` are additive unless marked otherwise, so ignore unknown fields and handle new enum values (see [Versioning](#versioning)).

## 0.33.0 (2026-10-15)

- Requests with an API key that does not exist: after many of them from one client address, `/v1` answers 429 `rate_limited` with `Retry-After` instead of 401. Keys that were used successfully shortly before are not affected.
- Media URLs: each URL is fetched once per content, a fetch may take 10 seconds in total, and timeouts, connection errors, 429 and 5xx of the source are final after the third attempt. Above a fair-use quota per tenant, media are skipped with the reason `quota_exceeded`; the report itself is always accepted.
- Webhooks: after 5 failed deliveries in a row (timeout, connection error, 429 or 5xx) the deliveries of the app pause for 5 minutes and then resume on their schedule; nothing is lost, and a successful webhook test ends the pause at once.

## 0.32.0 (2026-10-15)

- `POST /v1/reports` and `POST /v1/reviews` check `content.context` like `POST /v1/signals`: an empty key, a key longer than 128 bytes or of the form `__x__`, an array in an array or more than 10 levels answer 400 `validation_failed` with code `invalid` at `/content/context`. Before, such a request failed with 500 or, with an array in an array, was stored.
- `POST /v1/signals`: a `context` key longer than 128 bytes answers 400 `validation_failed` with code `invalid` (before: 500).
- `PUT /v1/subjects/{externalUserId}` answers 403 `tenant_not_active` while the tenant is in onboarding or suspended, like the other writing operations, and writes nothing. `GET /v1/subjects/{externalUserId}/status` keeps answering in every state.

## 0.28.0 (2026-10-12)

- New optional `identifiers` object (`keyVersion`, `email`, `phone`: HMACs, never plain values) for [ban evasion across apps](#ban-evasion-across-apps) (coming soon) on `POST /v1/reports` and `POST /v1/reviews` (`subject.identifiers`), `POST /v1/signals` (per signal), `POST /v1/devices/check` and `PUT /v1/subjects/{externalUserId}`. Identifiers never cause an error and never change a response.
- `PUT /v1/subjects/{externalUserId}`: `displayName` is no longer required; send at least one of `displayName` and `identifiers`. Without `displayName` the stored name is kept.
- New reserved `reasonCategory` `cross_app_ban` for reports Limenia creates itself.

## 0.22.0 (2026-10-07)

- `POST /v1/reports`: new optional `goodFaith` (the reporter confirmed the report is accurate and complete, Art. 16(2)(d) DSA). Only with `source: user`.

## 0.20.0 (2026-10-05)

- New `POST /v1/devices/check` for the [device connector](#device-connector), with errors `invalid_device_token` and `device_connector_not_configured`. Fail-open: when the provider is unreachable the answer is 200 with `status: unevaluated`.
- `POST /v1/signals` rejects the system signal types (`device_flagged`, `device_risk`) with `signal_type_unknown`.

## 0.19.0 (2026-10-05)

- `statementOfReasons.structured` has the new field `automation` (`none`, `partial`, `full`). `automatedDecision` is `true` only with `full`. Earlier decisions report `none`.

## 0.18.0 (2026-10-05)

- New `POST /v1/signals`: 1 to 100 signals per request, all or nothing, `202 Accepted`. Requires `Idempotency-Key`. Error `signal_type_unknown`.

## 0.16.0 (2026-10-05)

- `POST /v1/reports`: new optional `trustedFlaggerId` (Art. 22 DSA) and, in the response, `reporterWarning` while a warning against the reporter stands.
- New error 403 `reporter_suspended` with `suspendedUntil` on `POST /v1/reports` and on complaints of reporters (Art. 23 DSA).
- `statementOfReasons.structured` has the new field `noticeSource` (`notice`, `trusted_flagger`, `own_initiative`).

## 0.15.1 (2026-10-04)

- When a complaint against `ban_user` or `suspend_user` ends with a milder decision, the ban or suspension is lifted: you get `subject.status_changed` in addition to `decision.created`.

## 0.15.0 (2026-10-03)

- New `POST /v1/integrations/revenuecat/{tenantId}/{appId}`, the receiver for RevenueCat webhooks (called by RevenueCat, not by your backend).
- Reserved `reasonCategory` codes documented: `child_safety` and `protection_of_minors` (urgent, no media copy) and `ban_evasion`. `source: system` also covers reports Limenia creates itself.

## 0.14.0 (2026-10-03)

- With the RevenueCat connector, `statementOfReasons.text` can contain generic sentences about purchases.

## 0.13.2 (2026-10-03)

- `decision.created`: new `decision.restoreScope` (`content` or `account`) for `restore`.
- `PUT /v1/subjects/{externalUserId}` and `GET /v1/subjects/{externalUserId}/status` are never blocked by the plan; an expired suspension is reported as `active` at once.
- Field errors (`errors`) also come with specific codes such as `review_type_unknown`.

## 0.13.0 (2026-10-03)

- `POST /v1/reviews` requires a plan with reviews (403 `feature_not_in_plan`) and a subscription that has not expired (402 `subscription_required`). Reports and complaints are never blocked by the plan.

## 0.12.1 and 0.12.2 (2026-10-03)

- `decision.created`: new `decision.reviewId` for decisions on review requests, also for a new decision after a complaint against one.

## 0.12.0 (2026-10-03)

- New `POST /v1/reviews` and `GET /v1/reviews/{reviewId}` for [pre-moderation](#pre-moderation-reviews), new webhook event `review.decided`, new action `reject_submission`, new error `review_type_unknown`.

## 0.11.0 (2026-10-02)

- New `POST /v1/appeals` and `GET /v1/appeals/{appealId}` for [complaints](#complaints), new webhook events `appeal.resolved` and `reports.resolved`.
- `decision.created`: new `appealId` and `replacesDecisionId`. `POST /v1/reports`: new optional `externalReportId`.

## 0.9.0 (2026-10-02)

- **Breaking:** API keys start with `lm_live_` or `lm_test_`; the webhook headers are `Limenia-Event-Id`, `Limenia-Event-Type` and `Limenia-Signature`.

## 0.6.0 (2026-10-01)

- Webhooks: events `decision.created`, `subject.status_changed` and `test.ping`, signed with HMAC-SHA256.
- New error code `unavailable`.

## 0.4.0 (2026-10-01)

- First public API: `GET /v1/ping`, `POST /v1/reports`, `PUT /v1/subjects/{externalUserId}`, `GET /v1/subjects/{externalUserId}/status`, with API keys, idempotency keys and errors as `application/problem+json`.
