Dev.to WebDev 🛠 Dev 👁 0 📖 7 min read

Building a Zero-Trust Discord License Key Bot in discord.js v14: HMAC-SHA256 Webhooks, Seat Caps & Refund Revocation

Most indie Discord license bots start as a 60-line script: accept a JSON webhook from Stripe or Gumroad, generate crypto.randomUUID(), store it in a JSON file, and grant a VIP role when someone runs /redeem. Within a we

Most indie Discord license bots start as a 60-line script: accept a JSON webhook from Stripe or Gumroad, generate crypto.randomUUID(), store it in a JSON file, and grant a VIP role when someone runs /redeem.

Within a week of real traffic, four abuse vectors show up:

  1. Forged webhook requests: Anyone who discovers your /webhook endpoint can POST a fake sale payload and mint unlimited keys.
  2. Timing side-channels & parsed-JSON re-serialization bugs: Comparing signatures with === leaks byte-level timing, and verifying an HMAC over JSON.stringify(req.body) breaks when whitespace or key order differs from the raw payload.
  3. Key sharing across 20 Discord accounts: Without atomic seat-cap binding, one leaked key gets redeemed by an entire server.
  4. Chargeback buyers keeping VIP roles forever: If your webhook only listens for payment.succeeded and ignores charge.refunded / charge.dispute.created, refunded buyers keep gated channels permanently.

Here is a zero-trust architecture using node:crypto, discord.js v14, and transactional state so every webhook, key claim, and refund is cryptographically verified and auditable.

1. Pattern 1: Raw-Buffer Webhook Verification (createHmac + timingSafeEqual)

Never verify a webhook signature against parsed JSON. Always capture the exact raw Buffer before any JSON middleware runs, enforce a replay timestamp window, and compare fixed-length digests with crypto.timingSafeEqual.

import crypto from 'node:crypto';

const MAX_DRIFT_SEC = 300; // 5-minute replay window

export function verifyWebhookSignature({ rawBody, signatureHeader, timestampHeader, secret }) {
  if (!Buffer.isBuffer(rawBody) || !signatureHeader || !timestampHeader) {
    return false;
  }

  const ts = Number(timestampHeader);
  if (!Number.isFinite(ts) || Math.abs(Math.floor(Date.now() / 1000) - ts) > MAX_DRIFT_SEC) {
    return false;
  }

  // Bind timestamp + raw payload bytes to prevent replay with a stale signature
  const signedPayload = Buffer.concat([Buffer.from(String(ts) + '.'), rawBody]);
  const expectedHex = crypto.createHmac('sha256', secret).update(signedPayload).digest('hex');

  const expectedBuf = Buffer.from(expectedHex, 'hex');
  const providedBuf = Buffer.from(signatureHeader.trim(), 'hex');

  // timingSafeEqual throws if byte lengths differ; check lengths first
  if (expectedBuf.length === 0 || expectedBuf.length !== providedBuf.length) {
    return false;
  }

  return crypto.timingSafeEqual(expectedBuf, providedBuf);
}

In Express or Fastify, mount the raw body parser specifically on the webhook route so req.body arrives as a Buffer:

app.post('/webhooks/billing', express.raw({ type: 'application/json', limit: '256kb' }), async (req, res) => {
  const sig = req.header('x-webhook-signature');
  const ts = req.header('x-webhook-timestamp');

  if (!verifyWebhookSignature({ rawBody: req.body, signatureHeader: sig, timestampHeader: ts, secret: process.env.WEBHOOK_SECRET })) {
    return res.status(401).json({ error: 'Invalid signature' });
  }

  const event = JSON.parse(req.body.toString('utf8'));
  await handleVerifiedEvent(event);
  return res.status(200).json({ received: true });
});

2. Pattern 2: HMAC-Signed Human-Readable Keys & Atomic Seat Caps

Random UUIDs are ugly to paste into Discord and give you zero offline tamper check. Instead, derive a short uppercase key (NINO-XXXX-XXXX-XXXX-XXXX) where the first two groups carry a unique token ID and the last two groups carry a truncated HMAC-SHA256 tag over (orderId, keyId, maxSeats).

import crypto from 'node:crypto';

const ALPHABET = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; // Crockford-style, no 0/O/1/I

function toBase32Block(bytes, len = 4) {
  let out = '';
  for (let i = 0; i < len; i++) {
    out += ALPHABET[bytes[i] % ALPHABET.length];
  }
  return out;
}

export function mintLicenseKey(orderId, maxSeats, signingSecret, prefix = 'NINO') {
  const idBytes = crypto.randomBytes(8);
  const seg1 = toBase32Block(idBytes.subarray(0, 4));
  const seg2 = toBase32Block(idBytes.subarray(4, 8));
  const keyId = seg1 + seg2;

  const mac = crypto
    .createHmac('sha256', signingSecret)
    .update(prefix + ':' + keyId + ':' + orderId + ':' + maxSeats)
    .digest();

  const sig1 = toBase32Block(mac.subarray(0, 4));
  const sig2 = toBase32Block(mac.subarray(4, 8));
  return [prefix, seg1, seg2, sig1, sig2].join('-');
}

export function verifyKeyStructure(rawKey, orderId, maxSeats, signingSecret) {
  const parts = String(rawKey).trim().toUpperCase().split('-');
  if (parts.length !== 5) return false;
  const [prefix, seg1, seg2, sig1, sig2] = parts;
  const keyId = seg1 + seg2;

  const mac = crypto
    .createHmac('sha256', signingSecret)
    .update(prefix + ':' + keyId + ':' + orderId + ':' + maxSeats)
    .digest();

  const expected = Buffer.from(toBase32Block(mac.subarray(0, 4)) + toBase32Block(mac.subarray(4, 8)));
  const provided = Buffer.from(sig1 + sig2);
  return expected.length === provided.length && crypto.timingSafeEqual(expected, provided);
}

Enforcing Seat Caps Without Race Conditions

If two Discord users run /activate with the same key in the same 10ms window, a naive if (seats.length < maxSeats) check in memory will let both through. Wrap seat binding inside a database transaction (for example, better-sqlite3 db.transaction(...) or PostgreSQL SELECT ... FOR UPDATE):

export function claimSeatTx(db, { keyHash, discordUserId, orderId, maxSeats }) {
  return db.transaction(() => {
    const license = db.prepare('SELECT status, max_seats FROM licenses WHERE key_hash = ?').get(keyHash);
    if (!license) return { ok: false, reason: 'NOT_FOUND' };
    if (license.status !== 'ACTIVE') return { ok: false, reason: 'REVOKED' };

    const existing = db
      .prepare('SELECT 1 FROM license_seats WHERE key_hash = ? AND discord_user_id = ?')
      .get(keyHash, discordUserId);
    if (existing) return { ok: true, idempotent: true };

    const { used } = db
      .prepare('SELECT COUNT(*) AS used FROM license_seats WHERE key_hash = ?')
      .get(keyHash);

    if (used >= license.max_seats) {
      return { ok: false, reason: 'SEAT_CAP_REACHED', used, max: license.max_seats };
    }

    db.prepare(
      'INSERT INTO license_seats (key_hash, discord_user_id, claimed_at) VALUES (?, ?, ?)'
    ).run(keyHash, discordUserId, Date.now());

    return { ok: true, idempotent: false, seatsRemaining: license.max_seats - (used + 1) };
  })();
}

Store crypto.createHash("sha256").update(key).digest("hex") (key_hash) in the database rather than the plaintext key so a read-only database leak cannot immediately replay unused seats.

3. Pattern 3: discord.js v14 Activation & Automatic Refund Revocation

In discord.js v14, every activation reply must be ephemeral: true (or MessageFlags.Ephemeral) so other members never see license metadata or error states. More importantly, role grants must never be one-way: when a refund or dispute webhook arrives, revoke the key in the database first, then strip the role from every bound Discord user.

import { Events, MessageFlags } from 'discord.js';
import crypto from 'node:crypto';

export function registerLicenseHandlers(client, db, { vipRoleId, guildId, signingSecret }) {
  client.on(Events.InteractionCreate, async (interaction) => {
    if (!interaction.isChatInputCommand() || interaction.commandName !== 'activate') return;

    await interaction.deferReply({ flags: MessageFlags.Ephemeral });
    const rawKey = interaction.options.getString('key', true).trim().toUpperCase();
    const keyHash = crypto.createHash('sha256').update(rawKey).digest('hex');

    const row = db
      .prepare('SELECT order_id, max_seats, status FROM licenses WHERE key_hash = ?')
      .get(keyHash);

    if (!row || !verifyKeyStructure(rawKey, row.order_id, row.max_seats, signingSecret)) {
      return interaction.editReply('Invalid license key.');
    }

    const claim = claimSeatTx(db, {
      keyHash,
      discordUserId: interaction.user.id,
      orderId: row.order_id,
      maxSeats: row.max_seats,
    });

    if (!claim.ok) {
      const msg =
        claim.reason === 'REVOKED'
          ? 'This license key has been revoked due to a refund or chargeback.'
          : 'All seats for this license key are already claimed.';
      return interaction.editReply(msg);
    }

    const guild = await client.guilds.fetch(guildId);
    const member = await guild.members.fetch(interaction.user.id);
    if (!member.roles.cache.has(vipRoleId)) {
      await member.roles.add(vipRoleId, 'License activated: ' + row.order_id);
    }

    return interaction.editReply(
      'Access granted. Seats remaining: ' + (claim.seatsRemaining ?? 0)
    );
  });
}

export async function revokeOrderAccess(client, db, { orderId, guildId, vipRoleId, reason }) {
  const boundUsers = db.transaction(() => {
    const license = db
      .prepare('SELECT key_hash, status FROM licenses WHERE order_id = ?')
      .get(orderId);

    if (!license) return [];

    db.prepare("UPDATE licenses SET status = 'REVOKED', revoked_reason = ? WHERE key_hash = ?")
      .run(reason, license.key_hash);

    return db
      .prepare('SELECT discord_user_id FROM license_seats WHERE key_hash = ?')
      .all(license.key_hash)
      .map((r) => r.discord_user_id);
  })();

  if (boundUsers.length === 0) return;

  const guild = await client.guilds.fetch(guildId);
  for (const userId of boundUsers) {
    try {
      const member = await guild.members.fetch(userId);
      if (member.roles.cache.has(vipRoleId)) {
        await member.roles.remove(vipRoleId, 'Order revoked: ' + orderId + ' (' + reason + ')');
      }
    } catch (err) {
      // Member left the guild; seat is already REVOKED in DB so re-joining cannot re-claim
      if (err?.code !== 10007) console.error('Failed to strip role for', userId, err);
    }
  }
}

Notice two critical invariants in revokeOrderAccess:

  1. Database revocation happens before Discord API calls. Even if Discord returns HTTP 429 or the user temporarily left the server (Unknown Member error 10007), they can never re-activate the key later.
  2. Idempotent webhook handling: Store processed event.id values in a webhook_events(event_id PRIMARY KEY) table inside the same transaction so duplicate webhook retries never double-mint keys or crash.

4. Production Hardening Checklist

  • Bot role hierarchy: Ensure the bot role sits strictly above vipRoleId in Discord Server Settings → Roles, otherwise member.roles.add and member.roles.remove fail with 50013 Missing Permissions.
  • Separate secrets: Keep WEBHOOK_SECRET (from Stripe/Gumroad) completely separate from LICENSE_SIGNING_SECRET so rotating a webhook secret never invalidates issued keys.
  • Audit log: Persist (event_type, order_id, discord_user_id, created_at) in an append-only table whenever seats are claimed or revoked.
  • Never trust client-supplied order IDs: The Discord user only submits the key; order_id and max_seats are read exclusively from your server-side licenses table.

Try It Live in Your Browser (Zero Login)

If you want to test this exact flow interactively before writing boilerplate:

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.