Unprofane

Nakama profanity filter in one server module

Chat, player names and group names, checked before other players see them, with before hooks you paste into your Nakama server.

Your game’s lobby, on NakamaExample

lobby3 players

  1. mira_07anyone up for ranked?
  2. daxafter this match
  3. river_ottergg wp everyone

    river_otterthis lag is ******* unbearable

    Message not sent.Only you see this

gg wp everyonethis lag is fucking unbearablei hate you and everyone in this lobby hates you tooMessage #lobby

Unprofane
allow
Your module
sent as typed
Unprofane
blockprofanitya listed word
Your module
sent masked
Unprofane
blockinsultthe model’s reading
Your module
not sent
Try a line

Live in four steps

Build with a test key, 100 checks a month; switch to a live key when you ship.

  1. Before you start

    • Nakama 3, with its TypeScript, Go or Lua runtime.

      The module was run on Nakama 3.41.0.

    • An Unprofane key from the keys page of the dashboard: a test key (up_test_…) to build with, a live key (up_live_…) in production.

  2. Store the key

    • Add the key under runtime.env in your Nakama config.

      The module reads it from there, and your game client never holds it.

    config.yml

    runtime:
      env:
        - "UNPROFANE_API_KEY=up_live_YOUR_KEY"
  3. Add the module

    • One file, in the language your server code is written in. Every hook it adds is listed at the end of it.

    // Unprofane for Nakama: chat, player names and group names, checked before other players see them.
    // Set UNPROFANE_API_KEY under runtime.env in your Nakama config. Build to ES5, as Nakama's runtime needs.
    
    const UNPROFANE = 'https://api.unprofane.com/v1/check';
    // Who the game is for: kids, teen, standard or strict (https://unprofane.com/docs/policies/).
    const POLICY = 'teen';
    // The field of a chat message's JSON content that holds what the player typed.
    const MESSAGE_FIELD = 'message';
    
    interface Check {
      allowed: boolean;
      censored: string;
      matches: Array<{ category: string }>;
      decided_by: Array<{ from: 'words' | 'context' }>;
    }
    
    /** One check, or null when Unprofane did not answer: each caller decides what that means. */
    function check(
      ctx: nkruntime.Context,
      logger: nkruntime.Logger,
      nk: nkruntime.Nakama,
      text: string,
      context: string,
    ): Check | null {
      try {
        const res = nk.httpRequest(
          UNPROFANE,
          'post',
          { Authorization: 'Bearer ' + ctx.env.UNPROFANE_API_KEY, 'Content-Type': 'application/json' },
          JSON.stringify({ text: text, context: context, policy: POLICY }),
          2000,
        );
        if (res.code === 200) return JSON.parse(res.body);
        logger.warn('Unprofane answered %v: %v', res.code, res.body);
      } catch (e) {
        logger.warn('Unprofane did not answer: %v', String(e));
      }
      return null;
    }
    
    /** An error the player's client receives with this message. */
    function refusal(message: string, code = nkruntime.Codes.INVALID_ARGUMENT): nkruntime.Error {
      return { message: message, code: code };
    }
    
    /**
     * A chat line as the channel will read it: unchanged when it is allowed, masked when
     * the words that decided it can be hidden, and refused when there is no word to hide.
     */
    function chatLine(
      ctx: nkruntime.Context,
      logger: nkruntime.Logger,
      nk: nkruntime.Nakama,
      content: string,
    ): string {
      let body: { [field: string]: unknown };
      try {
        body = JSON.parse(content);
      } catch {
        return content;
      }
      const text = body && typeof body === 'object' ? body[MESSAGE_FIELD] : undefined;
      if (typeof text !== 'string' || !text.trim()) return content;
      const r = check(ctx, logger, nk, text, 'gaming');
      // No answer: chat keeps flowing, unchecked. To hold every line instead, throw here.
      if (!r || r.allowed) return content;
      if (r.decided_by.every((d) => d.from === 'words')) {
        body[MESSAGE_FIELD] = r.censored;
        return JSON.stringify(body);
      }
      throw refusal('Message not sent.');
    }
    
    function beforeChannelMessageSend(
      ctx: nkruntime.Context,
      logger: nkruntime.Logger,
      nk: nkruntime.Nakama,
      envelope: nkruntime.EnvelopeChannelMessageSend,
    ): nkruntime.EnvelopeChannelMessageSend {
      const message = envelope.channelMessageSend;
      message.content = chatLine(ctx, logger, nk, message.content);
      return envelope;
    }
    
    function beforeChannelMessageUpdate(
      ctx: nkruntime.Context,
      logger: nkruntime.Logger,
      nk: nkruntime.Nakama,
      envelope: nkruntime.EnvelopeChannelMessageUpdate,
    ): nkruntime.EnvelopeChannelMessageUpdate {
      const message = envelope.channelMessageUpdate;
      message.content = chatLine(ctx, logger, nk, message.content);
      return envelope;
    }
    
    /** Throws the words the player reads when a name or a description cannot be used. */
    function guard(
      ctx: nkruntime.Context,
      logger: nkruntime.Logger,
      nk: nkruntime.Nakama,
      text: string | undefined,
      context: string,
      what: string,
    ): void {
      if (!text) return;
      const r = check(ctx, logger, nk, text, context);
      // No answer is not a yes: refused for now, and the player tries again.
      if (!r)
        throw refusal('The ' + what + ' could not be checked. Try again.', nkruntime.Codes.UNAVAILABLE);
      if (r.allowed) return;
      throw refusal(
        r.matches[0]?.category === 'reserved'
          ? 'That name is reserved.'
          : 'Pick a different ' + what + '.',
      );
    }
    
    /** A sign-up by any method. A returning player sends a name that exists, so only a new one is checked. */
    function signUpName<T extends { username?: string }>(
      ctx: nkruntime.Context,
      logger: nkruntime.Logger,
      nk: nkruntime.Nakama,
      data: T,
    ): T {
      if (data.username && nk.usersGetUsername([data.username]).length === 0)
        guard(ctx, logger, nk, data.username, 'username', 'username');
      return data;
    }
    
    /** A change to the profile. Only what changes is checked, however much of it the client sends. */
    function beforeUpdateAccount(
      ctx: nkruntime.Context,
      logger: nkruntime.Logger,
      nk: nkruntime.Nakama,
      data: nkruntime.UserUpdateAccount,
    ): nkruntime.UserUpdateAccount {
      const user = nk.accountGetId(ctx.userId!).user;
      if (data.username !== user.username)
        guard(ctx, logger, nk, data.username, 'username', 'username');
      if (data.displayName !== user.displayName)
        guard(ctx, logger, nk, data.displayName, 'display_name', 'display name');
      return data;
    }
    
    /** A group or clan, made or changed: its name, and its description. */
    function groupText<T extends { name?: string; description?: string }>(
      ctx: nkruntime.Context,
      logger: nkruntime.Logger,
      nk: nkruntime.Nakama,
      data: T,
    ): T {
      guard(ctx, logger, nk, data.name, 'username', 'group name');
      guard(ctx, logger, nk, data.description, 'gaming', 'group description');
      return data;
    }
    
    function InitModule(
      ctx: nkruntime.Context,
      logger: nkruntime.Logger,
      nk: nkruntime.Nakama,
      initializer: nkruntime.Initializer,
    ) {
      if (!ctx.env.UNPROFANE_API_KEY)
        throw new Error('Set UNPROFANE_API_KEY under runtime.env in your Nakama config.');
      // Chat: a line, and an edit to one.
      initializer.registerRtBefore('ChannelMessageSend', beforeChannelMessageSend);
      initializer.registerRtBefore('ChannelMessageUpdate', beforeChannelMessageUpdate);
      // Names: a sign-up by any method, and a change later.
      initializer.registerBeforeAuthenticateDevice(signUpName);
      initializer.registerBeforeAuthenticateEmail(signUpName);
      initializer.registerBeforeAuthenticateCustom(signUpName);
      initializer.registerBeforeAuthenticateApple(signUpName);
      initializer.registerBeforeAuthenticateGoogle(signUpName);
      initializer.registerBeforeAuthenticateFacebook(signUpName);
      initializer.registerBeforeAuthenticateFacebookInstantGame(signUpName);
      initializer.registerBeforeAuthenticateGameCenter(signUpName);
      initializer.registerBeforeAuthenticateSteam(signUpName);
      initializer.registerBeforeUpdateAccount(beforeUpdateAccount);
      // Groups and clans.
      initializer.registerBeforeCreateGroup(groupText);
      initializer.registerBeforeUpdateGroup(groupText);
      logger.info('Unprofane checks chat, names and groups under the %v policy.', POLICY);
    }
    1. Line 6Who the game is for. teen lets a taunt about play through and masks swearing; standard also lets swearing at the game through, and kids acts on both.
    2. Line 8The field your client puts the text in. A message without it goes out as sent, and costs no check.
    3. Line 31Two seconds at most: the player is waiting for the line to send.
    4. Line 64Read as game chat: gg ez is a taunt, not an insult, and a threat outside the game still counts.
    5. Line 65When Unprofane does not answer, the line goes out unchecked, so chat never stops. Raise an error here to hold it instead.
    6. Line 67The listed words decided it, and censored hides them: the channel reads the masked line.
    7. Line 71The model decided it, with no listed word to hide: the sender’s client gets Message not sent. and nobody else sees the line.
    8. Line 125A returning player sends the name they already have, so only a new name is checked and a sign-in costs nothing.
    9. Line 138Only what changes is checked, however much of the profile the client sends.
    10. Line 164Without the key, Nakama refuses to start, so a missing key shows at deploy, not in a player’s chat.
    11. Line 167Edits too: an edited line is checked like a new one.

    Complete as printed: it reads the key from the config. Chat goes as context: "gaming", names as "username", both under the teen policy.

    TypeScript

    Put the file at src/main.ts in your Nakama TypeScript project. It builds with Heroic Labs’ usual tsconfig.json: ES5, into one build/index.js.

    tsconfig.json

    {
      "compilerOptions": {
        "target": "es5",
        "lib": ["es2015"],
        "outFile": "./build/index.js",
        "typeRoots": ["./node_modules"],
        "strict": true,
        "removeComments": false,
        "skipLibCheck": true
      },
      "files": ["./node_modules/nakama-runtime/index.d.ts"],
      "include": ["src/**/*"]
    }

    Install Nakama’s runtime types beside TypeScript 5.9: Nakama needs ES5, which TypeScript 6 marks deprecated.

    npm install --save-dev typescript@5.9.3 github:heroiclabs/nakama-common#v1.48.0

    Build it, and point runtime.js_entrypoint at build/index.js.

    npx tsc

    Nakama runs one InitModule. If you have one, rename this one initUnprofane and call it from yours.

    Go

    Put main.go in a folder of its own, beside this go.mod. Its nakama-common must be the version your Nakama uses.

    go.mod

    module unprofane-nakama
    
    go 1.27.1
    
    require github.com/heroiclabs/nakama-common v1.48.0
    
    require google.golang.org/protobuf v1.36.12 // indirect

    Fetch what it needs with the plugin builder image tagged with your Nakama’s exact version.

    docker run --rm -w /builder -v "$PWD:/builder" heroiclabs/nakama-pluginbuilder:3.41.0 mod tidy

    Build it with the same image.

    docker run --rm -w /builder -v "$PWD:/builder" heroiclabs/nakama-pluginbuilder:3.41.0 build -buildmode=plugin -trimpath -o ./unprofane.so .

    Put unprofane.so in data/modules beside your own plugin: Nakama runs the InitModule of each.

    Lua

    Put unprofane.lua in data/modules. Nakama loads every Lua file there when it starts; there is nothing to build.

  4. Check that it works

    • Say this lag is fucking unbearable in any channel: the other players read this lag is ******* unbearable.

    • Sign up as admin: the client gets That name is reserved. Sign up as river_otter: it goes through.

    What the run sent, as two players, and what came backNakama 3.41.0nakama-js 2.8.0TypeScript 5.9.3Postgres 16

    1. Chat gg wp everyoneothers read "gg wp everyone"
    2. Chat this lag is fucking unbearableothers read "this lag is ******* unbearable"
    3. Chat i hate you and everyone in this lobby hates you toorefused: "Message not sent."the model's reading
    4. Edit sh1t teamothers read "**** team"
    5. Sign-up sh1tH3ad_69refused: "Pick a different username."
    6. Sign-up adminrefused: "That name is reserved."
    7. Sign-up river_ottersigned up
    8. Display name xXsh1tXxrefused: "Pick a different display name."
    9. Group name Sh1tH3adsrefused: "Pick a different group name."
    10. Group name moderatorsrefused: "That name is reserved."
    11. Group name River Ottersmade
    12. Group description f u c k offrefused: "Pick a different group description."
    13. Unprofane held past the two-second timeout
    14. Chat this lag is fucking unbearableothers read "this lag is fucking unbearable"
    15. Sign-in river_ottersigned in, no check
    16. Sign-up new_recruitrefused: "The username could not be checked. Try again."

Every chat line, one of three ways

What the other players read depends on what decided the answer.

  1. allowSent as typed

    Typedgg wp everyone

    Others readgg wp everyone

    Nothing to hide.

  2. blockSent masked

    Typedthis lag is fucking unbearable

    Others readthis lag is ******* unbearable

    Listed words decided it, so the module sends censored.

  3. blockNot sent

    Typedi hate you and everyone in this lobby hates you too

    Others readNothing. The sender's client gets Message not sent.

    The model decided it, with no word to mask. Only the sender is told.

Names refused before they are saved

The same module checks every name a player types and every group a player makes.

Where the module checks a name or a description, how Unprofane reads it, and what the player reads when it is refused
WhereNakama hooksRead asThe player reads
Sign-upDevice, email, custom ID, Apple, Google, Facebook, Facebook Instant Games, Game Center, SteamusernamePick a different username.
Username changeUpdate accountusernamePick a different username.
Display nameUpdate accountdisplay_namePick a different display name.
Group nameCreate group, update groupusernamePick a different group name.
Group descriptionCreate group, update groupgamingPick a different group description.

A name that claims to be the game or its staff, such as admin or moderators, gets That name is reserved. instead.

How it behaves in production

When it runs, what it costs, and what usually goes wrong.

When the check runs
  1. Sent by the player
  2. Unprofane checks
  3. Stored and delivered

Before anyone reads it. Nakama runs a before hook ahead of its own work, so a chat line is checked before it is stored in the channel’s history or sent to anyone, and a name before it is saved. A line the module refuses never reaches the channel.

Allow, mask and refuse

A chat line has no moderator queue, so the module treats review like block. A line whose listed words decided it is sent with those words masked; a line the model decided, with no word to mask, is not sent. A name or a description is refused outright, with words the player can act on: Pick a different username., or That name is reserved. for a name that claims to be the game or its staff.

Every field of the answer is in the API reference.

When Unprofane does not answer

Each check waits two seconds at most. When Unprofane does not answer in time, or answers with an error, chat goes out unchecked, so a slow check never stops a match; a comment in the code marks the line to change to hold chat instead. A new name or description is refused, with words such as The username could not be checked. Try again., so nothing unchecked is saved. A returning player still signs in: their name is not checked again.

What it costs

Every chat line with text is one check, and so is every new name or description. A returning player’s sign-in, an unchanged name and a message with no text field cost none. The plans are on the pricing page.

Messages your server sends

The hooks run on what players send. A message your own server code sends with channelMessageSend passes no hook: check it in that code before you send it.

How this module was run

Each module was built as this page says, loaded into Nakama 3.41.0 in Docker with a fresh Postgres 16, and played by two players on Heroic Labs’ JavaScript client 2.8.0: every step of the log, then the same with Unprofane held past the two-second timeout. Unprofane was its API run locally with the model stood in for, so a line the model decides was decided by the stand-in. The modules ran exactly as printed here, with only the API’s address changed.

Nakama stops at start with Set UNPROFANE_API_KEY under runtime.env

The key is not in the config Nakama read. Add it under runtime.env, or pass --runtime.env UNPROFANE_API_KEY=…, and start Nakama again.

Chat arrives unchecked

Your client puts the text in a field other than message: set MESSAGE_FIELD to it. Otherwise Nakama’s log says why, in a line that starts Unprofane answered or Unprofane did not answer.

TypeError: Object has no member when Nakama starts

Your Nakama is older than the hook named. Remove that one registration, or upgrade Nakama.

The Go plugin will not load: plugin was built with a different version of package

Build it with the nakama-pluginbuilder image tagged with your Nakama’s exact version, and keep nakama-common in go.mod at the version that Nakama uses.

TypeScript reports that target: ES5 is deprecated

That is TypeScript 6. Install typescript@5.9.3, as the install line above does.

401: no valid API key

The key is not where the code reads it, or it was revoked. Set it again and deploy again.

402: a plan is required

A live or publishable key needs a plan. Build with a test key (up_test_…), which needs none.

429: too many requests

A test key’s free checks are capped across the account, a month’s with no plan and a day’s on one, and every plan has a per-minute limit. The answer’s type says which.

Every error, and what to send instead, is on the errors page.

The same check, in your client

A name screen can hint while the player types; the module above still decides.

Run this module with your API key

Add the file, set the key, and say this lag is fucking unbearable in your lobby.

Get your API key