Vibe coding with Claude Code course Β· Module 9: Discord clone

Roles and Permissions: Tests First, Then a Lock on the Server

9 min read
In this lesson11

Blackbeard has crept onto the guild server and is flooding the announcement channel with spam. An ordinary deckhand can do nothing, the captain is away, and first mate Anne does not know whether she may kick anyone. The server needs clear rules: who writes in announcements, who kicks, who mutes for an hour. Discord stores such rules as permission bits in roles and overwrites in channels. In this lesson Claude Code builds that mechanism and you check it with tests and on the server, because here the agent writes code that works on the screen and quietly lets everyone through.

What you will learn

  • describe permissions as bits and compute them from roles and channel overwrites;
  • ask first for tests of the hasPermission function, and only then for its code;
  • check the permission in a Route Handler and see a 403 in the response;
  • ask Claude to review all routes, and open every route it points at yourself.

Permissions as bits

Every permission is one bit in a number. 1 << 11 is a one shifted by 11 places, that is a number with a single bit switched on. The | (OR) operator combines permissions, & (AND) checks whether a bit is on, and & ~ switches a bit off. Open types/permissions.ts:

export const Permission = {
  KICK_MEMBERS: 1 << 1,
  BAN_MEMBERS: 1 << 2,
  ADMINISTRATOR: 1 << 3,
  SEND_MESSAGES: 1 << 11,
  MANAGE_ROLES: 1 << 28,
  MODERATE_MEMBERS: 1 << 29, // in Discord 1 << 40
} as const;

This is a fragment of the list, and the values are as in the Discord documentation, with one exception. MODERATE_MEMBERS, needed for a timeout, has bit 40 in Discord. Bitwise operators in JavaScript, however, work on 32 bits: node -e "console.log(1 << 40)" printed 256 for us, a completely different bit, and 1 << 31 gives a negative number. Discord sends permissions as strings with a big number and advises big-number libraries. The clone has fewer permissions, so it fits within bits up to 30.

A channel overwrite is two numbers: what to add and what to take away.

export interface ChannelOverwrite {
  id: string; // role id or member id
  type: "role" | "member";
  allow: number;
  deny: number;
}

The #announcements channel gets two overwrites: Crew has deny: SEND_MESSAGES, and Officer has allow: SEND_MESSAGES. types/server.ts gets an overwrites?: ChannelOverwrite[] field in the channel.

Rules from the Discord documentation

The Discord documentation describes the order of computing: the server owner has everything; for the others the permissions of their roles are summed; ADMINISTRATOR gives everything and skips the channel overwrites; role overwrites first take away (deny), then add (allow), and the overwrite of a specific member acts last. Discord also starts from the @everyone role; in the clone the Crew role plays its part.

Request for Claude Code: tests first

This task has one correct answer for each case, so it is a perfect fit for the tests from lesson 4_1.

Request for Claude Code:

First tests for hasPermission(member, permission, server, channel?)
in lib/permissions.test.ts, with the types from @types/permissions.ts:
the owner can do everything, ADMINISTRATOR skips channel overwrites,
role bits add up, a deny from a role takes away the right to write in
the channel, an allow from another role wins because deny goes before
allow, a member overwrite acts last. Run the tests and show the failure.
Then lib/permissions.ts. Do not change the tests to make them pass.
Show the command and the result.

The first run fails, because the function does not exist yet. In ours Vitest wrote: Failed to resolve import "@/lib/permissions" from "lib/permissions.test.ts". Does the file exist?. Before you accept the code, read the test file in Cursor and check that every case from the request has its own test.

What Claude wrote: hasPermission

Open lib/permissions.ts. The first part is the owner, the sum of roles and the administrator:

if (member.id === server.ownerId) return true;

let permissions = 0;
for (const role of server.roles) {
  if (member.roleIds.includes(role.id)) permissions |= role.permissions;
}
if ((permissions & Permission.ADMINISTRATOR) === Permission.ADMINISTRATOR) return true;

|= adds the bits of every role the member has, so Anne with the Officer and Crew roles gets the sum of both. The administrator leaves the function before the channel can take anything from them. The second part is the overwrites:

permissions &= ~deny;
permissions |= allow;

const own = channel.overwrites.find((o) => o.type === "member" && o.id === member.id);
if (own) {
  permissions &= ~own.deny;
  permissions |= own.allow;
}
return (permissions & permission) === permission;

Above, a loop collected allow and deny from all the member's roles. First everything the roles forbid is switched off, then what they allow is switched on, so Anne writes in #announcements although her Crew role is banned there. The last word belongs to the member overwrite: Blackbeard got his own deny in #general. All 6 tests passed.

A typical agent mistake: names instead of numbers

A tempting mistake is allow and deny as lists of names, for example ["SEND_MESSAGES"]. Readable for a human, but TypeScript rejects ~deny on a list. An agent that wants to silence the error will add Number(...): Number(["SEND_MESSAGES"]) is NaN, ~NaN is -1, and x | NaN is x, so the overwrites quietly do nothing. In ours that version passed npx tsc --noEmit and npm run lint, and the tests told the truth:

Γ— a deny from a role takes away the right to write in the channel
Γ— a member overwrite acts last
AssertionError: expected true to be false // Object.is equality
Tests  2 failed | 4 passed (6)

The "allow wins" test passed by accident, because Crew has the right to write anyway. That is why the tests for prohibitions are the most important ones here.

A lock on the server

The function is only half of it. A "Kick" button hidden from a deckhand protects nothing: anyone can send a request without your screen.

Request for Claude Code:

Add a Route Handler POST /api/members/[id]/kick. Take the logged-in
member from getCurrentMember() in @lib/session.ts, never from the
request body. Check KICK_MEMBERS on the server through hasPermission,
then the hierarchy: you may not kick the owner or anyone with an equal
or higher rank. First tests in route.test.ts next to it: an ordinary
member gets 403, an officer kicks a crew member, an officer cannot kick
the captain.

Open app/api/members/[id]/kick/route.ts. The beginning of the function is the lock:

export async function POST(_request: Request, ctx: RouteContext<"/api/members/[id]/kick">) {
  const { id } = await ctx.params;
  const me = await getCurrentMember();

  if (!hasPermission(me, Permission.KICK_MEMBERS, mainServer)) {
    return Response.json({ error: "Missing permission KICK_MEMBERS" }, { status: 403 });
  }

Code 403 means "I know who you are, but you are not allowed". Next the function looks up the member (404 if there is none) and checks the hierarchy with the outranks function. The Discord documentation describes this rule for bots: you can kick only someone whose highest role stands lower. The test replaces lib/session.ts with vi.mock, so it checks the route without a browser. Check it live too: in lib/session.ts change the logged-in member to jack and type in the session:

!curl -i -X POST http://localhost:3000/api/members/blackbeard/kick

In ours the server answered HTTP/1.1 403 Forbidden and {"error":"Missing permission KICK_MEMBERS"}, and Anne trying to kick the captain got 403 with {"error":"This person has an equal or higher rank"}.

Moderator tools in three steps

You order screens separately. RoleManager shows roles sorted descending by position, on a copy of course: [...roles].sort(...). Next to each permission stands a checkbox:

const bit = Permission[name];
const granted = (selected.permissions & bit) === bit;
// onChange:
update({ permissions: granted ? selected.permissions & ~bit : selected.permissions | bit });

The variable is called granted, not hasPermission, so that it does not shadow the function of that name. The save goes to PATCH /api/roles/[id], which checks MANAGE_ROLES. ModeratorTools gets ready decisions from the member page, computed on the server:

const higher = outranks(me, target, mainServer);
const allowed = {
  kick: higher && hasPermission(me, Permission.KICK_MEMBERS, mainServer),
  timeout: higher && hasPermission(me, Permission.MODERATE_MEMBERS, mainServer),
};

A timeout has its own permission: according to the Discord documentation it needs MODERATE_MEMBERS and lasts at most 28 days. The component itself is a Client Component with useState imported at the top of that file: the choice of action, the reason (without a reason "Confirm" is disabled) and the duration.

A review of all routes

After a few requests there are three routes in app/api. Each should have the same lock, but the agent wrote them at different moments.

Request for Claude Code:

Review all routes in app/api and list those that do not check the
session and the moderator role. For each give the file and the line.
Do not fix anything yet.

The report is a dispatch, not proof: open in Cursor every route it points at and every route it skipped. In ours the timeout route called getCurrentMember() but not hasPermission. Jack, an ordinary deckhand, used it to mute Anne: HTTP/1.1 200 OK. After the fix with a test the same command gave {"error":"Missing permission MODERATE_MEMBERS"} and 403.

Captain's review

  1. Numbers, not names. allow and deny are number, with no Number(...) and no as.
  2. Prohibitions in tests. The "deny takes away" test and the member overwrite test must exist and pass.
  3. Bits up to 30. No 1 << 31 or higher.
  4. A lock in every route. A hidden button is courtesy, a 403 from the server is a lock.
  5. Proof. Tests, lint, npx tsc --noEmit after npx next typegen (without it RouteContext does not know the new routes) and npm run build.

Next step

Ask for a commit, for example "Bitwise permissions, moderation routes with a server-side check". You will return to security later in this module: secrets, login and a review of the whole branch before deployment.

In the editor below a permission calculator is waiting: pick a pirate, a channel and a permission, see every step of the computation and turn on the agent bug with names instead of numbers.

Remember: a hidden button is not a lock, and a lock nobody has checked with a test is only a lock painted on a door.

Code for this lesson: App.jsx
// Pirate's Cove permission calculator: the same steps as hasPermission in lib/permissions.ts.
// The "agent bug" switch keeps allow and deny as lists of names converted with Number(...).
import { useState } from 'react';

const Permission = {
  KICK_MEMBERS: 1 << 1,
  BAN_MEMBERS: 1 << 2,
  ADMINISTRATOR: 1 << 3,
  SEND_MESSAGES: 1 << 11,
  MANAGE_ROLES: 1 << 28,
  MODERATE_MEMBERS: 1 << 29,
};

const server = {
  ownerId: 'redbeard',
  roles: [
    { id: 'captain', name: 'Captain', position: 3, permissions: Permission.ADMINISTRATOR },
    { id: 'officer', name: 'Officer', position: 2, permissions: Permission.KICK_MEMBERS | Permission.MODERATE_MEMBERS },
    { id: 'crew', name: 'Crew', position: 1, permissions: Permission.SEND_MESSAGES },
  ],
  members: [
    { id: 'redbeard', name: 'Kapitan Redbeard (owner)', roleIds: [] },
    { id: 'mary', name: 'Mary Read (Captain)', roleIds: ['captain', 'crew'] },
    { id: 'anne', name: 'Anne Bonny (Officer)', roleIds: ['officer', 'crew'] },
    { id: 'jack', name: 'Jack Rackham (Crew)', roleIds: ['crew'] },
    { id: 'blackbeard', name: 'Blackbeard (Crew)', roleIds: ['crew'] },
  ],
};

const channels = [
  { id: 'brak', name: '(no channel)', overwrites: [] },
  {
    id: 'announcements',
    name: '#announcements',
    overwrites: [
      { id: 'crew', type: 'role', allow: 0, deny: Permission.SEND_MESSAGES, names: { allow: [], deny: ['SEND_MESSAGES'] } },
      { id: 'officer', type: 'role', allow: Permission.SEND_MESSAGES, deny: 0, names: { allow: ['SEND_MESSAGES'], deny: [] } },
    ],
  },
  {
    id: 'general',
    name: '#general',
    overwrites: [
      { id: 'blackbeard', type: 'member', allow: 0, deny: Permission.SEND_MESSAGES, names: { allow: [], deny: ['SEND_MESSAGES'] } },
    ],
  },
];

function bits(value, buggy, names) {
  return buggy ? Number(names) : value; // Number(['SEND_MESSAGES']) is NaN
}

function explain(member, permission, channel, buggy) {
  const steps = [];
  if (member.id === server.ownerId) {
    steps.push('Server owner: everything is allowed.');
    return { ok: true, steps };
  }
  let permissions = 0;
  for (const role of server.roles) {
    if (member.roleIds.includes(role.id)) {
      permissions |= role.permissions;
      steps.push('Role ' + role.name + ' adds bits: ' + role.permissions);
    }
  }
  if ((permissions & Permission.ADMINISTRATOR) === Permission.ADMINISTRATOR) {
    steps.push('ADMINISTRATOR: everything is allowed, channel overwrites skipped.');
    return { ok: true, steps };
  }
  if (channel.overwrites.length > 0) {
    let allow = 0;
    let deny = 0;
    for (const o of channel.overwrites) {
      if (o.type === 'role' && member.roleIds.includes(o.id)) {
        allow |= bits(o.allow, buggy, o.names.allow);
        deny |= bits(o.deny, buggy, o.names.deny);
      }
    }
    permissions &= ~deny;
    steps.push("First the roles' deny: left with " + permissions);
    permissions |= allow;
    steps.push("Then the roles' allow: now " + permissions);
    const own = channel.overwrites.find((o) => o.type === 'member' && o.id === member.id);
    if (own) {
      permissions &= ~bits(own.deny, buggy, own.names.deny);
      permissions |= bits(own.allow, buggy, own.names.allow);
      steps.push('Member overwrite last: now ' + permissions);
    }
  }
  const ok = (permissions & permission) === permission;
  steps.push('Bit check: (' + permissions + ' & ' + permission + ') === ' + permission + ' gives ' + ok);
  return { ok, steps };
}

export default function App() {
  const [memberId, setMemberId] = useState('jack');
  const [channelId, setChannelId] = useState('announcements');
  const [permName, setPermName] = useState('SEND_MESSAGES');
  const [buggy, setBuggy] = useState(false);
  const [response, setResponse] = useState(null);

  const member = server.members.find((m) => m.id === memberId);
  const channel = channels.find((c) => c.id === channelId);
  const result = explain(member, Permission[permName], channel, buggy);

  // Fake Route Handler POST /api/members/blackbeard/kick: the lock on the server.
  function kickBlackbeard() {
    const allowed = explain(member, Permission.KICK_MEMBERS, channels[0], false).ok;
    setResponse(allowed ? '200 OK {"kicked":"blackbeard"}' : '403 Forbidden {"error":"Missing permission KICK_MEMBERS"}');
  }

  return (
    <div className="min-h-screen space-y-4 bg-gray-100 p-4 text-gray-900">
      <div className="grid gap-3 sm:grid-cols-3">
        <label className="text-sm">
          Pirate
          <select value={memberId} onChange={(e) => { setMemberId(e.target.value); setResponse(null); }} className="mt-1 block w-full rounded border border-gray-300 bg-white p-1">
            {server.members.map((m) => <option key={m.id} value={m.id}>{m.name}</option>)}
          </select>
        </label>
        <label className="text-sm">
          Channel
          <select value={channelId} onChange={(e) => setChannelId(e.target.value)} className="mt-1 block w-full rounded border border-gray-300 bg-white p-1">
            {channels.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
        </label>
        <label className="text-sm">
          Permission
          <select value={permName} onChange={(e) => setPermName(e.target.value)} className="mt-1 block w-full rounded border border-gray-300 bg-white p-1">
            {Object.keys(Permission).map((name) => <option key={name} value={name}>{name} (1 &lt;&lt; {Math.log2(Permission[name])})</option>)}
          </select>
        </label>
      </div>

      <label className="flex items-center gap-2 text-sm">
        <input type="checkbox" checked={buggy} onChange={(e) => setBuggy(e.target.checked)} />
        Agent bug: allow and deny as lists of names with Number(...)
      </label>

      <section className={'rounded-lg border p-4 ' + (result.ok ? 'border-green-600 bg-green-50' : 'border-red-600 bg-red-50')}>
        <h2 className="font-bold">hasPermission: {result.ok ? 'allowed' : 'denied'}</h2>
        <ol className="mt-2 list-decimal space-y-1 pl-5 text-sm">
          {result.steps.map((step, i) => <li key={i}>{step}</li>)}
        </ol>
      </section>

      <section className="space-y-2 rounded-lg border border-gray-300 bg-white p-4">
        <h2 className="font-bold">The server checks again</h2>
        <p className="text-sm">The button sends the request as the chosen pirate, even if the screen would hide it.</p>
        <button onClick={kickBlackbeard} className="rounded bg-red-600 px-3 py-1 text-white">POST /api/members/blackbeard/kick</button>
        {response && <pre className="rounded bg-gray-900 p-2 text-xs text-green-200">{response}</pre>}
      </section>
    </div>
  );
}

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. How does Pirate's Cove compute whether a member may do something?

  2. 2. How is KICK_MEMBERS written in the Permission object?

These are 2 of 8 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Click in order

    Click to build an entry from the Permission object: ADMINISTRATOR: 1 << 3

  • Code editor

    Role management interface

  • Horizontal ordering

    Arrange the line from the Route Handler that refuses a member without permission: return Response.json({ error: "Missing permission KICK_MEMBERS" }, { status: 403 });

  • Vertical ordering

    Arrange the steps of the hasPermission function in the order from the code:

  • Click in order

    Click to build the line that switches off bits forbidden by overwrites: permissions &= ~deny;

  • Horizontal ordering

    Arrange the check whether a member has a given role: member.roleIds.includes(role.id)

  • Vertical ordering

    Arrange the steps of reviewing the routes in app/api from the lesson:

  • Code editor

    Moderation panel

  • Vertical ordering

    Arrange the steps of how the getHighestRole function works:

  • Horizontal ordering

    Arrange the arguments of the call from the Route Handler: hasPermission(me, Permission.KICK_MEMBERS, mainServer)

  • Click in order

    Click to build the check whether a permission is set: (permissions & permission) === permission

  1. QuestionQuiz: How permissions are computed
  2. QuestionQuiz: Defining a permission bit
  3. Click in orderOrdering: Defining the ADMINISTRATOR bit
  4. Coding taskPractice: Role manager
  5. QuestionQuiz: hasPermission and ADMINISTRATOR
  6. Put in orderOrdering: The 403 response
  7. Put in orderOrdering: Steps of hasPermission
  8. QuestionQuiz: Channel overwrite order
  9. Click in orderOrdering: Switching off forbidden bits
  10. QuestionQuiz: The timeout permission
  11. Put in orderOrdering: Checking a member's role
  12. Put in orderOrdering: Reviewing API routes
  13. Coding taskPractice: Moderator tools
  14. Put in orderOrdering: getHighestRole steps
  15. Put in orderOrdering: Calling hasPermission (argument order)
  16. QuestionQuiz: The position field in Role
  17. Click in orderOrdering: Checking a permission bit
  18. QuestionQuiz: Discord vs Slack
  19. QuestionQuiz: An offline member with a hoisted role

Useful articles