DEV Community

kaka
kaka

Posted on

Building a Secret Santa draw in Next.js: derangements, HMAC links, and not leaking emails

Every December someone ships a Secret Santa app, and every December the same three things go wrong: the shuffle loops forever on a tricky exclusion list, the "private" assignment link contains the recipient's email in plain text, and the organizer dashboard quietly shows the whole pairing in a mode that was supposed to be blind.

I built one this year. These are the parts that were not obvious, with the code that ended up working.

1. A shuffle is not a draw

The obvious implementation is: shuffle the participant list, pair everyone with the next person, check the rules, retry if it fails.

// don't do this
do {
  names = shuffle(names)
} while (!isValid(names))
Enter fullscreen mode Exit fullscreen mode

This has two problems. With a tight exclusion list (couples, families) the valid-permutation rate collapses and the loop runs for a long time. Worse, when no valid assignment exists it never terminates — you get a spinner and a support email.

A valid draw is a perfect matching in a bipartite graph: givers on one side, receivers on the other, an edge wherever an assignment is allowed (not yourself, not an excluded pair). So the draw is a graph problem, not a sorting problem.

I used Kuhn's augmenting-path algorithm over a randomized adjacency order:

const pairs: DrawPair[] = []

for (const giver of shuffle([...people])) {
  const receiver = findAugmentingPath(giver)
  if (!receiver) {
    throw new UnsolvableDrawError("No valid assignment exists for these exclusions")
  }
  pairs.push({ giver, receiver })
}
Enter fullscreen mode Exit fullscreen mode

Three properties fall out of this for free:

  • It terminates. O(V·E), instant at 100 participants.
  • Unsolvable input is proven unsolvable, not "we gave up". Max matching < n is a fact you can report to the user instead of a stack trace.
  • It can never return a rule-violating result, because invalid edges do not exist in the graph.

Randomness comes from shuffling the giver order plus each giver's candidate list, so repeated draws differ.

2. Use a CSPRNG, not Math.random()

The draw decides who buys a gift for whom. Math.random() is a seeded PRNG; anyone who can reconstruct the seed can reconstruct the assignment. Since the whole point is that it is not predictable, shuffle with crypto.randomInt:

function shuffle<T>(arr: T[]): T[] {
  for (let i = arr.length - 1; i > 0; i--) {
    const j = randomInt(i + 1) // unbiased, rejection sampling
    ;[arr[i], arr[j]] = [arr[j], arr[i]]
  }
  return arr
}
Enter fullscreen mode Exit fullscreen mode

randomInt is also unbiased, which Math.floor(Math.random() * n) is not.

3. No accounts means HMAC, not a token table

Requiring signup to find out who you are buying for is a conversion killer. But "no accounts" cannot mean "no auth" — the assignment link is the auth.

Stateless signed tokens, HMAC-SHA256:

export function signToken(payload: TokenPayload): string {
  const body = Buffer.from(JSON.stringify(payload)).toString("base64url")
  const sig = crypto.createHmac("sha256", secret()).update(body).digest("base64url")
  return `${body}.${sig}`
}
Enter fullscreen mode Exit fullscreen mode

Two details worth copying:

const a = Buffer.from(sig)
const b = Buffer.from(expected)
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return null
Enter fullscreen mode Exit fullscreen mode

Compare with timingSafeEqual, and check lengths first — it throws on mismatched lengths, which is its own denial-of-service if you let it bubble.

And keep the payload minimal. Mine looks like this:

type TokenPayload =
  | { t: "a"; x: string; p: string; g: number } // assignment: exchange + giver + generation
  | { t: "o"; x: string }                        // organizer manage link
  | { t: "j"; x: string }                        // join link
  | { t: "r"; x: string; p: string }             // remove-my-data link
Enter fullscreen mode Exit fullscreen mode

Participant ids only. No names, no addresses, no recipient — definitely no email. A base64url payload is readable by anyone who copies the link; signing protects integrity, not confidentiality.

4. The generation counter is what makes redraw safe

This is the bug I would have shipped: organizer redraws, and every link sent five minutes ago now points at an assignment that no longer exists — or worse, still resolves to the old pairing because the token is still valid.

Assignments embed the draw generation:

{ t: "a", x: exchangeId, p: giverId, g: 3 }
Enter fullscreen mode Exit fullscreen mode

Verification compares g against the exchange's current generation. Redraw bumps the counter and every previously issued assignment token becomes inert, without a revocation list or a cron sweep.

If you skip this, "reset the draw" silently means "two valid pairings coexist", and the person who opens the old link buys for the wrong person.

5. Centralize the visibility policy or it will leak

Secret Santa has a mode where the organizer should not see who drew whom. In practice the flag gets checked in the dashboard, then someone adds a CSV export and forgets, then a "resend email" button renders a recipient name, and blind mode is now fiction.

The fix is not discipline, it is one function that everything reads:

export function exchangePolicy(exchange: ExchangeFlags | null | undefined): ExchangePolicy {
  const blind = Boolean(exchange?.blind_mode)
  const deliveryMode = exchange?.delivery_mode === "link" ? "link" : "email"

  return {
    deliveryMode,
    blind,
    showPairings: !blind,
    canExportPairs: !blind,
    sendsEmail: deliveryMode === "email",
    canResendEmail: deliveryMode === "email" && !blind,
    showsPrivateLinks: deliveryMode === "link",
  }
}
Enter fullscreen mode Exit fullscreen mode

The dashboard, the CSV export and the resend button all call exchangePolicy() rather than reading blind_mode themselves. A new page that forgets to check is a page that shows nothing, which fails in the safe direction.

One case that deserves an explicit refusal: blind mode plus link delivery is impossible. In link mode the organizer physically holds every assignment link, so calling the dashboard "blind" would be theatre. Better to reject the combination than to render a reassuring toggle that means nothing.

6. Never send the emails inside the request

A 50-person draw is 50 messages. Doing that inline means the organizer stares at a spinner, the route hits its timeout, and you have no idea which half went out.

Queue the sends and drain them from a cron route:

POST /api/manage/draw    →  compute pairs, persist, enqueue rows
GET  /api/cron/email-queue →  claim a batch, send, mark sent
Enter fullscreen mode Exit fullscreen mode

The queue is also where the boring-but-essential parts live: per-address rate limiting, so one mistyped list cannot get your sending domain flagged, and a resend path that is idempotent per participant rather than per click.

7. Don't let the join endpoint enumerate

If participants add themselves through a shareable link, that endpoint is unauthenticated by design. Return a count and nothing else — not the names, not the emails, not even "email already registered" as a distinct error. Otherwise the join link doubles as a membership oracle for anyone who receives it.

What I would tell past me

  • Model the draw as a matching, and let an unsolvable input be an error you can explain.
  • Math.random() is not random enough when there is money-shaped social pressure attached.
  • A signed token guarantees the payload was not edited; it does nothing to hide it. Keep ids in it and nothing else.
  • Bind assignment links to a draw generation, or "redraw" quietly creates two truths.
  • Put every visibility rule behind one function. The bug is never the flag you thought about; it is the export button you added in March.

The draw is the fun part and the part that is easiest to get subtly wrong. If you are building one, the matching algorithm and the generation counter are where I would spend the first hour.


I ended up shipping this as SantaWheel — free, no account for the organizer or the participants, two-way exclusion rules, up to 100 people. If you are building something similar, the matching function and the generation counter are the two places I would spend the first hour; everything else is CRUD around them.

Top comments (3)

Collapse
 
sunnatulla_dev profile image
Sunnatulla •

The matching approach is the right call for termination, but I got curious whether shuffling the giver order and candidate lists gives a uniform draw, so I rebuilt it from your description (shuffled givers, shuffled candidates, Kuhn's augmenting paths, crypto.randomInt) and counted 200k draws against rejection sampling, which is exactly uniform. Your findAugmentingPath isn't in the post, so yours may differ a bit.

It isn't uniform. With 4 people and no exclusions there are 9 valid draws, each should be 11.1%. The three "two swapped pairs" draws (A↔B, C↔D) came out at 8.7% and the 4-cycles at 12.4%. With 6 people and 2 couples excluded (116 valid draws, 0.86% each) the spread was 0.61% to 1.14%, so some pairings are almost twice as likely as others. It fades as the group grows: at 20 people with no exclusions I couldn't measure a difference anymore. Small family groups with couple exclusions are the usual Secret Santa though, and that's exactly where it shows.

Nothing breaks, but since section 2 already goes to the trouble of a CSPRNG, the cheap fix keeps your termination guarantee: run the matching first as the solvability proof, then try plain rejection sampling a bounded number of times and only fall back to the matching result if it never hits.

const proof = kuhnDraw(people, banned) // throws UnsolvableDrawError
for (let i = 0; i < 10_000; i++) {
  const p = shuffle([...people])
  if (people.every((g, k) => isAllowed(g, p[k]))) return p
}
return proof
Enter fullscreen mode Exit fullscreen mode

For tight lists where the valid rate is really low you'd land on the fallback, but for typical groups it returns a uniform draw within a handful of tries (about 1 in 3 permutations is a valid derangement, 1 in 6 for the 6-person couples case).

Collapse
 
mp3sss31 profile image
mp3sss •

Modeling the draw as bipartite matching rather than shuffle-retry is the right call — it turns an unbounded retry loop into an O(V·E) procedure that can report a provably unsolvable exclusion set instead of hanging on a spinner. The HMAC-signed lookup link matters just as much: keeping the recipient out of the URL means a forwarded link or a leak in server logs only exposes an opaque token, not the pairing. One thing to check on top: tie the signed token to a short expiry and a clear re-read policy so a shared link can't hand off the reveal repeatedly, and keep the organizer view on a separate permission path rather than the same session.

Collapse
 
komopdf profile image
KomoPDF •

One edge case in the matching sketch: an augmenting path can reassign a receiver already in pairs. Build the final pairs from the matching map after all givers are processed, rather than appending each intermediate result.