Unprofane

Firebase username check in one Cloud Function

A Cloud Function on profile writes that clears a bad username and records why.

A profile in FirestoreExample

profilestest

username
"sh1tH3ad_69"null
usernameProblem
"Pick a different username."
theme
"dark"

onDocumentWrittenguardUsername

profilestest

username
"admin"null
usernameProblem
"That name is reserved."
theme
"dark"

onDocumentWrittenguardUsername

profilestest

username
"river_otter"
theme
"dark"

onDocumentWrittenguardUsername

Unprofane
blockleetspeak
guardUsername
update({ username: null, usernameProblem: "Pick a different username." })
Unprofane
blockreserved
guardUsername
update({ username: null, usernameProblem: "That name is reserved." })
Unprofane
allow
guardUsername
no write
Try a name

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

    • A Firebase project on the Blaze plan, which Cloud Functions need, and the Firebase CLI.

    • Profiles in Firestore at profiles/{uid} with a username field.

      Change the path in the code if yours differs.

    • npm install @unprofane/sdk in functions/.

  2. Store the key

    • Run firebase functions:secrets:set UNPROFANE_API_KEY and paste the key when asked.

    • The function binds it with secrets, so it is in process.env.UNPROFANE_API_KEY only while the function runs.

      That is why the client is made on first use: Firebase loads the code at deploy, before the secret is there.

  3. Where the file goes

    • functions/src/index.ts, beside your other functions.

      Deploy with firebase deploy --only functions:guardUsername.

    // functions/src/index.ts: runs after every write to profiles/{uid}
    import { onDocumentWritten } from 'firebase-functions/v2/firestore';
    import { Unprofane } from '@unprofane/sdk';
    
    let unprofane: Unprofane | undefined;
    
    /** Returns the reason a username cannot be shown, or null when it can. Throws when Unprofane cannot answer. */
    export async function usernameProblem(username: string): Promise<string | null> {
      unprofane ??= new Unprofane(process.env.UNPROFANE_API_KEY!, { timeoutMs: 3_000, retries: 1 });
      const r = await unprofane.check({ text: username, context: 'username', policy: 'teen' });
      if (r.allowed) return null;
      return r.matches[0]?.category === 'reserved'
        ? 'That name is reserved.'
        : 'Pick a different username.';
    }
    
    export const guardUsername = onDocumentWritten(
      // Binding the secret puts it in process.env.UNPROFANE_API_KEY while the function runs.
      { document: 'profiles/{uid}', secrets: ['UNPROFANE_API_KEY'] },
      async (event) => {
        const before = event.data?.before.data();
        const after = event.data?.after.data();
        // Nothing to check: a delete, no username, or a username that did not change.
        if (!after?.username || after.username === before?.username) return;
        // A throw fails this run; set retry on the function to have Firebase run it again.
        const problem = await usernameProblem(after.username);
        if (problem) await event.data!.after.ref.update({ username: null, usernameProblem: problem });
      },
    );
    1. Line 9The client is made on first use: Firebase loads the module at deploy, before the secret exists.
    2. Line 10Read as a handle: glued words are split, leetspeak and look-alike letters are read, and the name is tried backwards too. The teen policy lets mild words through and turns the rest away; pick the one for your audience.
    3. Line 13admin, support and your own brand come back reserved, so the person reads taken, not rude.
    4. Line 19Binds the secret, so the key is in the environment only while the function runs.
    5. Line 24Skips a delete, an empty name, an unchanged one and its own write.
    6. Line 27Clears the name and keeps the reason, for your app to show.

    Complete as printed: it reads the key from the environment. Every name goes with context: "username" and the teen policy.

  4. Check that it works

    • Write { username: "sh1tH3ad_69" } to profiles/test from the console or the app.

      A moment later username is null and usernameProblem is Pick a different username.

    • admin gives That name is reserved.; river_otter stays.

    • If nothing changes, read the logs:

      firebase functions:log --only guardUsername

    What the run sends, and what comes backfirebase-functions 7.4.0firebase-admin 14.5.0@unprofane/sdk 0.1.2Node 24

    1. sh1tH3ad_69update({ username: null, usernameProblem: "Pick a different username." })
    2. adminupdate({ username: null, usernameProblem: "That name is reserved." })
    3. river_otterno write
    4. Unprofane unreachablethrows, and the name stays

It reads the name, not a list

Six usernames a word list gets wrong, and what this check answered.

  1. sh1tH3ad_69

    Digits for letters

    Misses it

    blockreads shitheadleetspeak
  2. ilovesh1t

    Words run together

    Misses it

    blockreads shitleetspeakconcatenation
  3. tihs_xX

    Written backwards

    Misses it

    blockreads shitreversed
  4. admin

    Not rude: a claim to be staff

    Passes it

    blockreserved
  5. Dickinson

    A poet’s surname

    Blocks it

    allow
  6. therapist_jo

    A job

    Blocks it

    allow
Out of 6

4 let through2 innocent blocked

4 turned away2 innocent let through

76.5%

Unprofane

Balanced mode, as the recipes run it

32.5%

Perspective API

Set to flag as much clean text as Unprofane

Toxic usernames caught. Held-back judged test set, run of .How it was measured

How it behaves in production

When it runs, what it does with each answer, and what usually goes wrong.

When the check runs
  1. Typed
  2. Saved and shown
  3. Unprofane checks
  4. Cleared when refused

After the write. Firestore saves the profile first and the function runs afterwards, so the name can be read until the function clears it. The client watches usernameProblem and asks again. For an answer before the write, make an HTTPS callable function from the same usernameProblem, call it from the form first, and keep this trigger as the backstop.

Allow, review and block
allow
Goes through
review
Turned away, like a block
block
Turned away

allowed is true only when action is allow. The recipes turn away review as well as block: a username has no moderator queue, and asking for another name costs the person a few seconds. To accept a name held for review and look at it later, test action !== "block" instead and keep the user id where a person will read it. A name that claims to be the platform or its staff, such as admin, comes back with matches[0].category set to reserved, and the code says so in its own words.

The function clears the name rather than deleting the profile, and writes the reason to usernameProblem for the client to show.

Every field of the answer is in the API reference.

When Unprofane does not answer

When Unprofane does not answer, the run throws and the name stays. Firebase does not run a failed event again unless you set retry: true in the options; the code is safe to run twice.

How this recipe is run on every change

Typechecked and run: the module loaded without the key, as a deploy loads it, then the handler called with document changes: the three names below, its own write, an unchanged name, and once with Unprofane unreachable. Firestore and Cloud Functions are stood in for.

The deploy fails with pass an API key

Something makes the SDK client when the module loads. Keep the ??= inside usernameProblem.

UNPROFANE_API_KEY is undefined when the function runs

The secret is not bound. Keep secrets: ["UNPROFANE_API_KEY"] in the options and deploy again.

A client can write usernameProblem itself

Let your security rules allow the client to read that field and not to write it.

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, elsewhere

Each recipe is a complete file, run the same way.

Run this recipe with your API key

Paste the file, set the key, and send it sh1tH3ad_69, admin and river_otter.

Get your API key