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:
- Forged webhook requests: Anyone who discovers your
/webhookendpoint canPOSTa fakesalepayload and mint unlimited keys. - Timing side-channels & parsed-JSON re-serialization bugs: Comparing signatures with
===leaks byte-level timing, and verifying an HMAC overJSON.stringify(req.body)breaks when whitespace or key order differs from the raw payload. - Key sharing across 20 Discord accounts: Without atomic seat-cap binding, one leaked key gets redeemed by an entire server.
- Chargeback buyers keeping VIP roles forever: If your webhook only listens for
payment.succeededand ignorescharge.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:
- Database revocation happens before Discord API calls. Even if Discord returns HTTP 429 or the user temporarily left the server (
Unknown Membererror10007), they can never re-activate the key later. - Idempotent webhook handling: Store processed
event.idvalues in awebhook_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
vipRoleIdin Discord Server Settings → Roles, otherwisemember.roles.addandmember.roles.removefail with50013 Missing Permissions. - Separate secrets: Keep
WEBHOOK_SECRET(from Stripe/Gumroad) completely separate fromLICENSE_SIGNING_SECRETso 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_idandmax_seatsare read exclusively from your server-sidelicensestable.
Try It Live in Your Browser (Zero Login)
If you want to test this exact flow interactively before writing boilerplate:
- ShopCord Interactive Sandbox (Free): Simulate
/shop,/buy,/redeem, and/verifywith real Web Crypto HMAC-SHA256 signatures, seat-limit rejections, refund revocation, and instantcommands.json/discord.jsv14 snippet export at https://nino-demos.pages.dev/shopcord/ - ShopCord Pro ($24 Full Kit): Ready-to-deploy Discord store & license bot source with Stripe/Gumroad webhooks, SQLite/Postgres schema, and auto-revocation at https://vietanh1109a.itch.io/shopcord-pro-discord-store-license-bot
- ShipFast Static HTML5 Builder (Free): Need a sub-5KB zero-framework landing page for your bot or indie product? Customize and download a single-file HTML5 site at https://nino-demos.pages.dev/shipfast/
- All 62 Free Browser Dev Tools: https://nino-demos.pages.dev/


