# Likizao AntiCheat — Installation & Integration Guide

---

## 1. Installation

1. Drop the resource into your `resources/` folder and make sure it starts **before** your
   framework scripts that spawn vehicles/objects — it validates entities as they are
   created, so it has to be running before they exist.
2. Edit the files inside `config/`:
   - `shared_flags.lua` — feature flags (section 3).
   - `shared_func.lua` — framework bridge functions (section 2).
   - `shared_commands.lua` — commands and permissions (section 8).
   - `shared_weapons.lua` — hash → display-name map used by the wall and by logs.
   - `sv_detections.lua` — per-detection behaviour (section 4).
   - `sv_webhooks.lua` — Discord webhooks.
   - `sv_report_handler.lua` — report filter, admin notification and ban function.
3. Start the resource and confirm the console prints `(likizao_ac) -> Carregado com sucesso!`.

> **One server per license.** A license cannot be shared between multiple servers — only one
> active server is allowed per license. If you need a second server (a test or development
> one, for example), it needs its own license.

---

## 2. Framework functions (`config/shared_func.lua`)

The anticheat never talks to your framework directly — it only calls the functions below.
Fill them in with whatever your framework uses. The default file is written for vRP.

### `Config.Functions.getUserId(source)`

Returns a **unique, stable ID per account**, derived from the player's `source`.

- vRP: `vRP.getUserId(source)`
- ESX: `ESX.GetPlayerFromId(source).identifier`
- QBCore: `QBCore.Functions.GetPlayer(source).PlayerData.citizenid`
- No account system at all: just `return source` — it works fine, the value is only used
  for logs, ban calls and the wall label.

It must return `nil` when the player is not loaded yet; the anticheat handles that case and
logs the report using the raw identifiers instead.

```lua
Config.Functions.getUserId = function(source)
    return vRP.getUserId(source)
end
```

### `Config.Functions.getUserSource(user_id)`

The reverse of `getUserId`: given the ID, return the current `source`, or `nil` if offline.
Used to notify online admins.

### `Config.Functions.hasPermission(user_id, permission)`

Returns `true`/`false`. `permission` is whatever string you set in `shared_commands.lua`
(`player.wall`, `player.propmanager`, `player.cleanarea`).

### `Config.Functions.getUsersByPermission(permission)`

Returns a list of `user_id` that hold the permission. Used by `Config.NotifyAdmins` to find
who should receive detection alerts (it queries `player.noclip` by default).

### `Config.Functions.getIdentity(user_id)`

Returns the character identity for the wall. Any of these shapes is accepted:
`{ name, firstname }`, `{ name, name2 }` or `{ nome, sobrenome }`. Returning `nil` makes the
wall show `SEM NOME`.

### `Config.Functions.getUserGroupByType(user_id, 'job')`

Returns the player's job name (string) for the wall label, or `nil`/`false`.

### `Config.Functions.Notify(src, type, message)`

Your notification system. `type` is one of `sucesso`, `negado`, `importante`. Map those to
your own notification types in the `VALID_TYPES` table right above the function.

### `Config.Labels`

Wall/permission message strings. Translate freely.

---

## 3. Flags (`config/shared_flags.lua`)

Flags are just strings in `Config.Flags`. Anything not listed there is disabled.

```lua
Config.Flags = {
    '--heartbeat-v2',
    '--enable-custom-object',
    '--enable-vehicle-check',
}
```

| Flag | Effect |
|------|--------|
| `--enable-custom-object` | Enables the object and ped protection. Objects have to be whitelisted (section 7) and non-player peds are blocked. Without it, no object or ped is validated. |
| `--enable-vehicle-check` | Enables vehicle spawn validation: a vehicle created by a player has to be authorized first (section 6). Server-side vehicles are accepted automatically. |
| `--enable-sv.vehicle-spawn` | For servers that spawn vehicles **only** on the server side: every new vehicle has to be confirmed as legitimate instead of being trusted, so client spawns are not kept. |
| `--enable-explosions` | Allows explosions and projectiles for players who have an authorized weapon. Without it, explosions and projectiles are blocked server-wide. |
| `--disable-player-constraints` | Loosens the bucket rules for the weapon checks and enables the noclip watcher. Use on servers that rely heavily on routing buckets. |
| `--disable-weapon-handler` | Turns the weapon module off completely. Debugging only. |
| `--disable-unarmed-damage` | Skips the unarmed damage validation. Useful with custom melee damage. |
| `--disable-attachment-check` | Disables the check for objects attached to another player's entity. It can produce false positives from owner mismatch, since server-side entities have no client owner and end up looking like someone else's. |
| `--disable-citizen-check` | Client-side: disables the client integrity checks. |
| `--disable-scenario-check` | Disables the scenario spam check. |
| `--anticl2` | One session per license: if the same license joins twice, both sessions are dropped. |
| `--set-population` | For servers that use ambient population (AI traffic, pedestrians, scenario NPCs). |
| `--heartbeat-v2` | Improved heartbeat. Recommended — keep it enabled by default. |
| `--canary` | New handling for server-side vehicle spawns. Enable it if you run into problems with server-side vehicles. |

---

## 4. Detections (`config/sv_detections.lua`)

```lua
Config.Detections = {
    ['Weapon Spawn 12'] = true,   -- instant ban
    ['Weapon Spawn 10'] = 2,      -- ban after 2 detections
    ['Spawn de Objeto']  = false, -- log only
}
```

- `true` → ban on the first detection.
- `number` → ban after that many detections (counter resets every 50 seconds).
- `false` or missing → log to the `suspicious` webhook only, no action.


Bans can be globally switched off with the convar `set likizao_enable_ban 0` (default `1`).

Extra optional keys you may add to the config:

| Key | Purpose |
|-----|---------|
| `Config.DefaultBucket` | The bucket your players normally live in. When set to `0`, **any** bucket greater than 0 disables the weapon check for that player. When set to anything else (or left unset), the threshold is `1000000` (see section 5). |
| `Config.ObjectsWhitelist` | Extra object whitelist merged into the object module on start, same format as section 7 (`[model] = amount`, model as hash or string). |
| `Config.Locales` | `[detection_name] = "translated name"`, applied to the log/notification text. |
| `Config.SendLog(type, user_id, src, reason, additionalData)` | Define it to take over logging entirely; the built-in Discord embed is then skipped. `type` is `'suspicious'` or `'banned'`. |

### `Config.ReportHandler(src, reason, additionalData)`

Called before anything else on every report. **Return `false` to discard the report** (no log,
no count, no ban). Use it for staff bypasses, event whitelists, etc.

### `Config.NotifyAdmins(user_id, src, report_type, report_reason)`

Called after the log. `report_type` is `'suspicious'` or `'banned'`.

### `Config.BanUser(user_id, src, identifiers)`

Your ban implementation. `identifiers` is the raw `GetPlayerIdentifiers(src)` table. The player
is dropped with `Config.DisconnectMessage` right after this call.

---

## 5. Weapons

### Giving a weapon vs. only whitelisting it

There are two different things you can do, and this is the most common source of confusion:

**`exports.likizao_ac:giveWeapons(src, weapons)` — gives the weapon AND whitelists it.**

```lua
exports.likizao_ac:giveWeapons(source, {
    ['WEAPON_PISTOL'] = 250,                                        -- ammo only
    ['WEAPON_CARBINERIFLE'] = { ammo = 120, isHidden = false, bForceInHand = true },
})
```

The ped actually receives the weapon (`GiveWeaponToPed`) and it is registered as authorized.
Keys accept a weapon name or a hash; the value is either the ammo count or a table.

**`TriggerEvent('likizao_ac:setWeapons', src, weapons)` — only whitelists, gives nothing.**

```lua
TriggerEvent('likizao_ac:setWeapons', source, {
    ['WEAPON_PISTOL'] = true,
    ['WEAPON_CARBINERIFLE'] = true,
})
```

This **replaces** the player's authorized weapon list without touching the ped. Use it when
your inventory already hands out the weapon on the client and you only need the anticheat to
stop reporting it. To add a single weapon without wiping the list, use:

```lua
TriggerEvent('likizao_ac:setPlayerWeapon', source, 'WEAPON_PISTOL', 250)
```

Other weapon exports:

| Export | Description |
|--------|-------------|
| `exports.likizao_ac:removeWeapons(src)` | Removes every weapon from the ped (`RemoveAllPedWeapons`). |
| `exports.likizao_ac:addAmmo(src, _, weapon, newValue)` | Sets the ammo for that weapon. The second argument is ignored (kept for compatibility). |
| `exports.likizao_ac:SetWeaponsAlias(aliasTable)` | Replaces the alias table used to map custom/skin weapon hashes to their base weapon: `[hash] = "WEAPON_BASE"` or `[hash] = { "WEAPON_A", "WEAPON_B" }`. Aliases from the `skins` and `skin-weapon` resources are loaded automatically when those resources exist. |

### Routing buckets and the weapon check

Weapon damage validation is skipped depending on the shooter's routing bucket:

- If `Config.DefaultBucket == 0`: any bucket **> 0** skips the check.
- Otherwise: any bucket **> 1000000** skips the check. This is the recommended way to run
  minigames, arenas, shooting ranges or any custom event — put the players in a bucket above
  1000000 and the weapon protection is ignored for them.


---

## 6. Events to authorize actions

All of these are **server-side** `TriggerEvent` calls (they are not net events, so a cheater
cannot fire them from the client).

### Vehicles

```lua
-- Authorize a model for one player, optionally restricted to a position
TriggerEvent('likizao_ac:onVehicleSpawn', { src = source, name = 'adder', position = coords })
TriggerEvent('likizao_ac:onSpawnVehicle', { src = source, name = 'adder' })

-- Whitelist coordinates: any vehicle spawned within 30m of these points is accepted
TriggerEvent('likizao_ac:setCoordsBypass', { vec3(x, y, z), vec3(x2, y2, z2) })
```

`exports.likizao_ac:setSpawnClient(src, model)` does the same as `onSpawnVehicle` and also
pre-authorizes the matching object model.

**Server-side spawns.** Vehicles created with `CreateVehicle` on the server have no client
owner, so with `--enable-vehicle-check` they are accepted without being announced — the
events above are only needed for vehicles the **client** creates. If server-created vehicles
ever get deleted or reported (for instance when `--set-population` is also enabled), turn on
`--canary`, which handles those spawns for you.

### Peds

```lua
-- Allow a player to spawn a ped model for `ttl` seconds (default 30)
TriggerEvent('likizao_ac:allowPedModel', source, 'a_m_y_business_01', 30)
TriggerEvent('likizao_ac:allowPedModel', source, { 'model_a', 'model_b' }, 60)
TriggerEvent('likizao_ac:allowPedModel', source, '*', 15)  -- any ped model
```

### Forcing a report from your own scripts

```lua
TriggerEvent('AC:ForceBan', source, {
    reason = 'My custom detection',
    additionalData = 'extra info',
    forceBan = true,
})
```

The anticheat also emits `AC:Suspect` with `{ reason, user_id }` whenever a non-banning
report happens, and `likizao:PropManager:DeleteEntitys` (`user_id`, entities, isMassDelete)
when an admin deletes entities — hook those for your own logging.

---

## 7. Releasing objects in the config

Object control only runs when `--enable-custom-object` is enabled. The whitelist can be extended from the config with `Config.ObjectsWhitelist` or at runtime with the exports below.

```lua
Config.ObjectsWhitelist = {
    ['prop_cs_phone_01'] = 1,
    [GetHashKey('prop_beer_box_01')] = 1,
    ['cdev_pets_bowl1_a'] = 999,
}
```

**The number is the maximum amount of that object a single player may have at the same time.**

- `= 1` → the player may have **only one** of that object at a time. A second one spawned  is treated as a duplicate abuse.
- `> 1` (e.g. `2`, `10`, `999`) → **several instances at the same time are allowed**, no duplicate check is performed. Use this for props like pet beds, cones, lights or anything a player legitimately places more than once.

Value `0` or a missing entry means the object is **not** whitelisted: it gets cancelled and
the player is reported with `Spawn de Objeto`.


Runtime exports:

| Export | Description |
|--------|-------------|
| `exports.likizao_ac:RegisterModel(model, amount)` | Whitelists one model. `model` accepts a hash or a name. Same `1` vs `> 1` rule. |
| `exports.likizao_ac:RegisterModels({ [model] = amount, ... })` | Whitelists several models at once. |
| `exports.likizao_ac:IsObjectAllowed(owner, model, coords)` | Returns `true`/`false` using the same rules (whitelist + 30m + duplicate check). |
| `exports.likizao_ac:SetBypass(src, 'entities')` | The player is fully ignored by the object/ped module. Pass `nil` to remove. |
| `exports.likizao_ac:setUserBypass(src, true)` | Global bypass: every report from that player is discarded. Pass `false` to remove. |
| `exports.likizao_ac:DisableBan()` | Disables banning inside the entity module (logs only). |

---

## 8. Other exports

| Export | Description |
|--------|-------------|
| `exports.likizao_ac:setValidation(detection_name, callback)` | Registers an extra validation for a detection (section 8.1). |
| `exports.likizao_ac:removeValidation(detection_name)` | Removes the validation. Returns `false` if none was registered. |
| `exports.likizao_ac:getValidations()` | Returns the table of currently registered validations. |
| `exports.likizao_ac:registerReportOverride(detection_name, callback)` | Rewrites or drops a report before it is processed (section 8.2). |
| `exports.likizao_ac:overrideConfig({ ['Detection'] = value })` | Changes `Config.Detections` entries at runtime (section 8.3). |
| `exports.likizao_ac:Report(src, reason, forceBan, additionalData)` | Reports a player (one report per reason per cycle). |
| `exports.likizao_ac:ReportAfterCount(src, reason, maxCount, ban, additionalData)` | Reports only after `maxCount` occurrences. |

### Where each hook runs

Every report goes through this pipeline, in this order:

1. `Config.ReportHandler(src, reason, additionalData)` — return `false` to drop it.
2. **`setValidation`** callback for that detection — return `true` to drop it.
3. **`registerReportOverride`** callback for that detection — return `false` to drop it, or a
   table to rewrite the report.
4. `Config.Detections[reason]` (or whatever **`overrideConfig`** last set) decides log vs. ban.

### 8.1 `setValidation`

Registers a per-detection check that decides, at the moment of the report, whether that
player should be ignored. **Returning `true` means "this is legitimate, drop the report".**

> The callback must be passed across resources (a CFX function reference), so call this
> export from **another resource**, not from inside `likizao_ac` itself. Validations are
> automatically removed when the resource that registered them stops.

```lua
-- Called as callback(src, ...) where the extra arguments depend on the detection.
exports.likizao_ac:setValidation('Weapon Spawn', function(src, weaponHash)
    -- 'EXPLOSION' is passed instead of a hash when the check comes from an
    -- explosion/projectile event (only with --enable-explosions).
    if weaponHash == 'EXPLOSION' then
        return isPlayerInEventZone(src)
    end

    -- Otherwise weaponHash is the signed weapon hash already resolved through the alias table.
    return myInventory.hasWeapon(src, weaponHash)
end)
```

Any detection name works, not only `Weapon Spawn`; for every other detection the callback
receives just the source:

```lua
exports.likizao_ac:setValidation('Spawn de Objeto', function(src)
    return isStaffOnDuty(src)
end)

exports.likizao_ac:removeValidation('Spawn de Objeto')
```

Only one validation can exist per detection — registering a second one overrides the first
and prints a warning in the console.

### 8.2 `registerReportOverride`

Runs after the validation and lets you **change** the report instead of only accepting or
rejecting it. The callback receives `(src, report)`, where `report` is
`{ reason, additionalData, forceBan }`, and must return either:

- `false` (or `nil`) → the report is discarded;
- a table → its fields are merged into the report before it is logged/banned.

```lua
exports.likizao_ac:registerReportOverride('TASK_SPAM', function(src, report)
    local task = GetPedScriptTaskCommand(GetPlayerPed(src))

    if task == -129606530 then
        return false -- ignore it?
    end

    if task == -874453556 then
        return {                       -- same detection, different name in the logs
            reason = 'Crashar Players (02)',
            additionalData = '',
        }
    end

    return { additionalData = 'Task: ' .. task }  -- keep the report, just enrich the log
end)
```

Returning `{ forceBan = true }` promotes that specific report to an instant ban regardless of
what `Config.Detections` says.

### 8.3 `overrideConfig`

Changes `Config.Detections` at runtime, with the same semantics as the config file
(`true` = instant ban, number = ban after N detections, `false` = log only). Useful to soften
detections during an event and restore them afterwards.

```lua
exports.likizao_ac:overrideConfig({
    ['Weapon Spawn']   = false,  -- log only
    ['Spawn de Objeto'] = 3,     -- ban after 3 detections
    ['Super Soco (1)']  = true,  -- instant ban
})
```

Each change is printed to the server console.

### 8.4 Custom reports from your own resource

```lua
exports.likizao_ac:Report(src, 'Minha Detecção', false, 'extra info')
exports.likizao_ac:ReportAfterCount(src, 'Minha Detecção', 3, true, 'extra info')
```

`Report` only fires once per `src`+`reason` per cycle. `ReportAfterCount` only reports after
`maxCount` occurrences, and `ban` decides whether that final report bans the player.

---

## 9. Commands

### Player/staff commands (configurable in `config/shared_commands.lua`)

```lua
Config.Wall        = { command = 'wall',        permission = 'player.wall',        outline = true, opacity = 246 }
Config.PropManager = { command = 'propmanager', permission = 'player.propmanager' }
Config.CleanArea   = { command = 'cleanarea',   permission = 'player.cleanarea' }
```

| Command | Permission | Description |
|---------|-----------|-------------|
| `/wall` | `player.wall` | Toggles the ESP wall (names, jobs, admin/newbie tags, detection counters). |
| `/propmanager` | `player.propmanager` | Opens the prop manager UI to inspect and delete networked entities and their owners. |
| `/cleanarea` | `player.cleanarea` | Deletes peds and objects within 60m. Passing any argument (e.g. `/cleanarea veh`) also deletes vehicles within 40m. |
| `/wallconfig` | — (client, only affects the caller's own wall) | `linhas`, `nome`, `source`, `logs`, `killer`, `distancia <n>`. Settings are persisted per client. |

Setting `Config.Wall`, `Config.PropManager` or `Config.CleanArea` to `nil` disables that
module entirely.

### Server console commands

| Command | Description |
|---------|-------------|
| `likizao_toggle_veh_check` | Toggles the vehicle check module between v1 and v2 behaviour. |
| `likizao_ac_debug_vehicle` | Toggles verbose logging for the server-side vehicle module. |
| `likizao_block_object <hash>` | Blocks a model hash instantly and deletes every existing instance of it. |

### Convars

| Convar | Default | Description |
|--------|---------|-------------|
| `likizao_enable_ban` | `1` | Set to `0` to log detections without ever banning. |

---

## 10. Recommended first setup

1. Pick your flags with "Which flags does my server need?" below, and leave
   `Config.Detections` empty (only the mandatory comment line). Any detection that is not
   listed there is log-only, so nobody gets banned while you are still tuning.
2. Fill in `Config.Functions` and confirm `/wall` shows the correct names — that proves
   `getUserId`, `getIdentity` and `hasPermission` are wired correctly.
3. Enable one module at a time (`--enable-custom-object`, then `--enable-vehicle-check`),
   watching the `suspicious` webhook for false positives.
4. Authorize your own scripts with the events in section 6 and the object whitelist in
   section 7 until the logs are clean.
5. Only then switch the detections you trust to `true` or to a numeric threshold.

### Which flags does my server need?

Answer these four questions and you have your `Config.Flags`.

Start with `--heartbeat-v2`, which is recommended on every server, then answer the rest.

**Do you use ambient population (AI traffic, pedestrians, scenario NPCs)?**
Add `--set-population`. Without it every non-player ped is cancelled, so a server with
ambient life will look completely empty. If your server has no AI population at all (peds
and traffic disabled), leave it out — the protection is stricter that way.

**Who spawns your vehicles?**

- **Client and server mixed** (garages, admin menus, jobs on the client side): use
  `--enable-vehicle-check`. Client spawns have to be announced with the events in section 6,
  and server-side spawns are accepted automatically, so this flag alone covers both cases.
- **Server side only** (every vehicle comes from `CreateVehicle` on the server): use
  `--enable-sv.vehicle-spawn`, which confirms each vehicle instead of trusting it. Do not
  use it if any part of your server still spawns vehicles from the client.

Either way, turn on `--canary` if you run into problems with server-side vehicles.

**Do players place props (inventory items, pets, fishing rods, signs, work objects)?**
Add `--enable-custom-object` and whitelist those models as described in section 7. This is
the flag that goes together with the vehicle one on almost every server.

**Do you use routing buckets a lot (instances, houses, minigames)?**
Add `--disable-player-constraints` so the weapon checks stop fighting your buckets, and
remember that any bucket above 1000000 ignores the weapon protection entirely (section 5).

A typical roleplay server with ambient population, client and server vehicles, and props
ends up with:

```lua
Config.Flags = {
    '--heartbeat-v2',
    '--set-population',
    '--enable-vehicle-check',
    '--enable-custom-object',
}
```
