AI & ML

Defense in Depth: Designing the Security Layers Behind a Withdraw Button

· 5 min read
Community Article
Community articles are authored by SitePoint Premium contributors. Content is screened before publication, and SitePoint reserves the right to moderate or remove articles that violate our guidelines. Views expressed are those of the authors and do not necessarily reflect those of SitePoint.

Defense in Depth: Designing the Security Layers Behind a Withdraw Button

DJ
Div John
Published in
·Updated:

The AI briefing for Developers

Stay up to date with AI tools, model releases, and developer workflows that matter.

Weekly. Free. One click to leave.

Share this article

Defense in Depth: Designing the Security Layers Behind a Withdraw Button
SitePoint Premium
Stay Relevant and Grow Your Career in Tech
  • Premium Results
  • Publish articles on SitePoint
  • Daily curated jobs
  • Learning Paths
  • Discounts to dev tools
Start Free Trial

7 Day Free Trial. Cancel Anytime.

One button, many layers. A system-design walkthrough of how high-value platforms such as crypto exchanges protect their most dangerous endpoint, with a tested Node.js module you can adapt for any app that moves money or sensitive data.

Every application has one endpoint that keeps its engineers up at night. For a social network it might be "change email address". For a SaaS product it might be "export all data". For a crypto exchange it's the withdraw button, because a successful withdrawal is final. There's no chargeback and no bank to call. Once the transaction is signed and broadcast, the money is gone.

That makes exchanges a useful case study in a principle every developer has heard of and few apply rigorously: defense in depth. The idea is simple. Don't rely on any single control. Stack several independent layers, and design each one on the assumption that the layer before it has already failed.

This article walks through the layers a well-designed withdrawal flow uses, from the login screen down to the private keys. Along the way we'll build a small Node.js module, with tests, that implements the application-side layers. It uses only built-in modules, so there's nothing to install.

Key Takeaways

  • Re-authenticate for risky actions. A login session is not proof that the person at the keyboard is the account owner right now.
  • Make new destinations wait. An address allowlist with a cool-off period turns a fast account takeover into a slow one the owner can stop.
  • Cap the damage in advance. Velocity limits decide how much one compromised account can lose before anything goes wrong.
  • Score, then hold. Combine weak signals into a risk score, and send high scores to a person rather than rejecting them outright.
  • Fail closed and keep receipts. If a check errors, hold the request. Record every decision in an append-only log.
  • Keep the keys elsewhere. The web app should only queue withdrawals. A separate, locked-down service signs them.

Layer 1: Prove who you are, again

Logging in once isn't enough for a sensitive action. Sessions get hijacked, laptops get left unlocked, and cookies leak. The standard answer is step-up authentication: before a high-risk action, ask the user to prove their identity again, typically with a second factor, and accept that proof only for a short window. NIST's digital identity guidelines (SP 800-63B) set out reauthentication limits for each assurance level, and the OWASP Authentication Cheat Sheet covers re-authentication before sensitive features.

export async function requireRecentAuth({ user, session, now }) {
  if (now - (user.credentialsChangedAt ?? 0) < config.credentialLockMs) return deny('credentials_recently_changed');
  if (now - session.lastStrongAuthAt > config.stepUpWindowMs) return deny('step_up_required');
  return pass();
}

The first line adds a second rule that's worth copying even if you never build an exchange: after a password reset or a 2FA change, lock sensitive actions for a day. Account takeovers almost always start by changing credentials. A short lock turns a silent takeover into a delay the real owner has time to notice.

Notice the return value. Every check in this module returns one of three outcomes, built by tiny helpers: pass(), deny(reason) or hold(reason). Keeping every layer to the same small interface is what lets us compose them later.

Layer 2: Prove the destination is yours

Even a legitimately logged-in user can be tricked into sending funds to an attacker, or have their session used by malware. So the second layer moves from "who are you?" to "do you really mean this?"

The most effective pattern here is the address allowlist with a cool-off period. Users can only withdraw to addresses they've saved in advance, and a newly added address can't be used straight away.

export async function requireAllowlistedAddress({ store, user, address, now }) {
  const entry = store.addresses.get(`${user.id}:${address}`);
  if (!entry) return deny('address_not_allowlisted');
  if (now - entry.addedAt < config.coolOffMs) return hold('address_in_cool_off');
  return pass();
}

The cool-off is the clever part. An attacker who gets into an account wants to move fast. A rule that says "new destinations only work tomorrow", combined with an email and push notification whenever one is added, gives the real owner a day to notice and freeze the account. It costs legitimate users very little, because most people withdraw to the same few addresses again and again.

The confirmation screen is part of this layer too. OWASP's Transaction Authorization Cheat Sheet calls it "What You See Is What You Sign": the user should see and approve the destination and the amount, not a generic "Are you sure?" dialog.

Layer 3: Limit the blast radius

Assume layers 1 and 2 have both failed. How much damage can one compromised account do? Velocity limits answer that question in advance.

export async function enforceDailyLimit({ store, user, amountCents, now }) {
  const spent = store.withdrawals
    .filter((w) => w.userId === user.id && w.at > now - DAY)
    .reduce((sum, w) => sum + w.amountCents, 0);
  if (spent + amountCents > user.dailyLimitCents) return hold('daily_limit');
  return pass();
}

Two implementation notes. Store amounts as integers in the smallest unit (cents, satoshis, wei), never as floats, or rounding errors will eventually let a request slip past a limit it should hit. And make the request idempotent: the client sends a unique key with each withdrawal, and the server refuses to process the same key twice. Without that, a flaky mobile connection and an impatient user tapping "retry" can turn one withdrawal into three. An IETF Internet-Draft, still a work in progress rather than a published standard, proposes this pattern as an Idempotency-Key HTTP header.

Layer 4: Let a risk engine (and a human) decide

The first three layers are rules. Rules are predictable, which is good for users and also good for attackers, who can learn them. The fourth layer adds judgment: a risk score built from signals such as a new device, an unusual country, or a withdrawal that empties the account straight after a deposit.

export function riskScore({ signals = {} }) {
  const weights = { newDevice: 40, newCountry: 30, drainsBalance: 30 };
  return Object.entries(weights).reduce((s, [k, w]) => s + (signals[k] ? w : 0), 0);
}

A single weak signal shouldn't stop anyone. People buy new phones and travel. A new device on its own scores 40 and passes; a new device in a new country scores 70 and is held for review. A high score doesn't reject the request, it holds it. That distinction matters: denying legitimate users is expensive in support tickets and trust, while a short hold for a person to look at the case is usually acceptable for a rare, high-value action.

Composing the layers

With every check sharing one interface, the withdrawal flow becomes a short pipeline. This is also where idempotency, failure handling and the audit log live, because they apply to every request rather than to one layer.

export async function requestWithdrawal(ctx) {
  const { store, user, address, amountCents, idempotencyKey, now } = ctx;
  const fingerprint = `${user.id}|${address}|${amountCents}`;
  const previous = store.requests.get(idempotencyKey);
  if (previous) {
    return previous.fingerprint === fingerprint ? previous.result : { status: 'rejected', reason: 'idempotency_key_reused' };
  }

  let result = { status: 'queued_for_signing' };
  for (const check of checks) {
    let outcome;
    try {
      outcome = await check(ctx);
    } catch {
      outcome = hold('check_failed'); // fail closed
    }
    if (outcome.action === 'deny') { result = { status: 'denied', reason: outcome.reason }; break; }
    if (outcome.action === 'hold') { result = { status: 'held_for_review', reason: outcome.reason }; break; }
  }

  if (result.status === 'queued_for_signing') store.withdrawals.push({ userId: user.id, amountCents, at: now });
  store.requests.set(idempotencyKey, { fingerprint, result });
  store.audit.push(Object.freeze({ at: now, userId: user.id, idempotencyKey, ...result }));
  return result;
}

A few design decisions are worth pointing out:

  • Idempotency comes first. A retried request returns the original result without running the checks again. If the same key arrives with a different amount or address, the request is rejected, because that's a bug or an attack, not a retry.
  • Errors fail closed. If a check throws (say the risk service times out), the request is held, never waved through.
  • Every outcome is recorded with a machine-readable reason, and the log entries are frozen. In production that log would live in a separate store the web app can append to but not edit.
  • Nothing is signed here. A request that passes every check is only queued for signing. We'll come back to why.

A Withdrawal Pipeline You Can Run Today

Here's the complete module, including the pieces above. It keeps state in an in-memory store so you can run it without a database.

// withdrawals.mjs: a layered withdrawal pipeline with an in-memory store.
const MINUTE = 60_000;
const DAY = 24 * 60 * MINUTE;

export const config = {
  stepUpWindowMs: 5 * MINUTE,  // layer 1: how long a fresh 2FA check counts
  credentialLockMs: DAY,       // layer 1: no withdrawals right after a password or 2FA change
  coolOffMs: DAY,              // layer 2: new addresses wait this long
  riskHoldAt: 70,              // layer 4: hold for review at or above this score (0-100)
};

export function createStore() {
  return { addresses: new Map(), withdrawals: [], requests: new Map(), audit: [] };
}

const pass = () => ({ action: 'pass' });
const deny = (reason) => ({ action: 'deny', reason });
const hold = (reason) => ({ action: 'hold', reason });

// Layer 1: prove who you are, again
export async function requireRecentAuth({ user, session, now }) {
  if (now - (user.credentialsChangedAt ?? 0) < config.credentialLockMs) return deny('credentials_recently_changed');
  if (now - session.lastStrongAuthAt > config.stepUpWindowMs) return deny('step_up_required');
  return pass();
}

// Layer 2: prove the destination is yours
export async function addAddress(store, userId, address, now) {
  store.addresses.set(`${userId}:${address}`, { addedAt: now });
  return { notify: userId, message: `New withdrawal address added: ${address}` };
}

export async function requireAllowlistedAddress({ store, user, address, now }) {
  const entry = store.addresses.get(`${user.id}:${address}`);
  if (!entry) return deny('address_not_allowlisted');
  if (now - entry.addedAt < config.coolOffMs) return hold('address_in_cool_off');
  return pass();
}

// Layer 3: limit the blast radius
export async function enforceDailyLimit({ store, user, amountCents, now }) {
  const spent = store.withdrawals
    .filter((w) => w.userId === user.id && w.at > now - DAY)
    .reduce((sum, w) => sum + w.amountCents, 0);
  if (spent + amountCents > user.dailyLimitCents) return hold('daily_limit');
  return pass();
}

// Layer 4: score the request
export function riskScore({ signals = {} }) {
  const weights = { newDevice: 40, newCountry: 30, drainsBalance: 30 };
  return Object.entries(weights).reduce((s, [k, w]) => s + (signals[k] ? w : 0), 0);
}

export async function checkRisk(ctx) {
  return riskScore(ctx) >= config.riskHoldAt ? hold('risk_review') : pass();
}

export const checks = [requireRecentAuth, requireAllowlistedAddress, enforceDailyLimit, checkRisk];

// The pipeline: idempotent, fail-closed and audited
export async function requestWithdrawal(ctx) {
  const { store, user, address, amountCents, idempotencyKey, now } = ctx;
  const fingerprint = `${user.id}|${address}|${amountCents}`;
  const previous = store.requests.get(idempotencyKey);
  if (previous) {
    return previous.fingerprint === fingerprint ? previous.result : { status: 'rejected', reason: 'idempotency_key_reused' };
  }

  let result = { status: 'queued_for_signing' };
  for (const check of checks) {
    let outcome;
    try {
      outcome = await check(ctx);
    } catch {
      outcome = hold('check_failed'); // fail closed
    }
    if (outcome.action === 'deny') { result = { status: 'denied', reason: outcome.reason }; break; }
    if (outcome.action === 'hold') { result = { status: 'held_for_review', reason: outcome.reason }; break; }
  }

  if (result.status === 'queued_for_signing') store.withdrawals.push({ userId: user.id, amountCents, at: now });
  store.requests.set(idempotencyKey, { fingerprint, result });
  store.audit.push(Object.freeze({ at: now, userId: user.id, idempotencyKey, ...result }));
  return result;
}

The tests cover each layer and the cases that usually break in production: a stale 2FA check, an attacker's address, a brand-new address, a second withdrawal that crosses the daily limit, a single innocent risk signal, a retried request, a failing dependency and the audit trail.

import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createStore, addAddress, requestWithdrawal, checks } from './withdrawals.mjs';

const NOW = Date.parse('2026-11-30T12:00:00Z');
const DAY = 24 * 60 * 60_000;
let n = 0;

async function setup() {
  const store = createStore();
  await addAddress(store, 'u1', 'addr-home', NOW - 3 * DAY);
  const ctx = {
    store, now: NOW, address: 'addr-home', amountCents: 50_000,
    user: { id: 'u1', dailyLimitCents: 200_000 },
    session: { lastStrongAuthAt: NOW - 60_000 },
  };
  return { store, ctx, req: (over = {}) => requestWithdrawal({ ...ctx, idempotencyKey: `k${++n}`, ...over }) };
}

test('a normal withdrawal is queued for signing', async () => {
  const { req } = await setup();
  assert.deepEqual(await req(), { status: 'queued_for_signing' });
});

test('layer 1: stale 2FA and recent credential changes are denied', async () => {
  const { ctx, req } = await setup();
  assert.equal((await req({ session: { lastStrongAuthAt: NOW - DAY } })).reason, 'step_up_required');
  assert.equal((await req({ user: { ...ctx.user, credentialsChangedAt: NOW - 60_000 } })).reason, 'credentials_recently_changed');
});

test('layer 2: unknown addresses are denied, new ones are held', async () => {
  const { store, req } = await setup();
  assert.equal((await req({ address: 'addr-attacker' })).status, 'denied');
  const note = await addAddress(store, 'u1', 'addr-new', NOW - 60_000);
  assert.match(note.message, /addr-new/);
  assert.deepEqual(await req({ address: 'addr-new' }), { status: 'held_for_review', reason: 'address_in_cool_off' });
});

test('layer 3: the daily limit counts earlier withdrawals', async () => {
  const { req } = await setup();
  await req({ amountCents: 150_000 });
  assert.deepEqual(await req({ amountCents: 60_000 }), { status: 'held_for_review', reason: 'daily_limit' });
});

test('layer 4: several weak signals together trigger review, one does not', async () => {
  const { req } = await setup();
  assert.equal((await req({ signals: { newDevice: true } })).status, 'queued_for_signing');
  assert.equal((await req({ signals: { newDevice: true, newCountry: true } })).reason, 'risk_review');
});

test('a retry with the same key is processed once', async () => {
  const { store, req } = await setup();
  const first = await req({ idempotencyKey: 'retry-1' });
  const second = await req({ idempotencyKey: 'retry-1' });
  assert.deepEqual(second, first);
  assert.equal(store.withdrawals.length, 1);
  assert.equal((await req({ idempotencyKey: 'retry-1', amountCents: 1 })).reason, 'idempotency_key_reused');
});

test('a failing check holds the request instead of letting it through', async () => {
  const { req } = await setup();
  checks.push(async () => { throw new Error('risk service timeout'); });
  try {
    assert.deepEqual(await req(), { status: 'held_for_review', reason: 'check_failed' });
  } finally {
    checks.pop();
  }
});

test('every decision is written to the audit log', async () => {
  const { store, req } = await setup();
  await req();
  await req({ address: 'addr-attacker' });
  assert.deepEqual(store.audit.map((e) => e.status), ['queued_for_signing', 'denied']);
  assert.throws(() => { store.audit[0].status = 'edited'; });
});

Save the two files side by side as withdrawals.mjs and withdrawals.test.mjs, then run node --test in that folder. It needs Node.js 20 or later and nothing else, and all eight tests passed in our environment.

Limits of This Example

  • The numbers are illustrative. A five-minute step-up window, a 24-hour cool-off and the risk weights (40, 30, 30, held at 70) are starting points. Set real values from your own data and measured false-positive rates.
  • It runs in one process. A production system would use a shared database, enforce idempotency with a unique constraint, and handle concurrent requests for the same account, which this in-memory version doesn't.
  • The risk signals are placeholders. Deciding what counts as a "new device" or an "unusual country" is a project of its own, and those signals are noisy.
  • Notifications are stubbed. addAddress returns the message it would send. Real alerts must still reach the owner if an attacker has just changed the account's email address, for example by also notifying the previous address.

Layer 5: Keep the keys somewhere else

The signing step is where the money actually moves, so it lives in a separate, much more locked-down system. Exchanges commonly split funds into tiers:

  • A hot wallet holds a small fraction of funds, online, for day-to-day withdrawals.
  • Warm and cold storage hold the rest, with keys kept offline or in hardware security modules.
  • Moving funds from cold to hot requires approval from several people, enforced cryptographically through multi-signature schemes or multi-party computation (MPC), so no single employee or server can do it alone.

The design goal is that even a full compromise of the web application can, at worst, drain the hot wallet, and the hot wallet is deliberately kept small. The signing service accepts requests only from the withdrawal queue, validates them again (never trust the caller) and has no other way in.

The general lesson applies well beyond crypto: put your most sensitive capability behind a separate service, with its own credentials and a deliberately narrow API.

Layer 6: Make it verifiable

The last layer isn't about stopping attackers. It's about being able to prove, to yourself and to your users, that the other layers worked.

Internally, that's the append-only audit log from our pipeline. Externally, exchanges have gone a step further with proof of reserves: publishing cryptographic evidence that customer balances are fully backed. As one example, the XT.COM proof-of-reserves page describes a Merkle tree method that lets each user verify that their own balance is included, and it says reserve reports are issued regularly. Its reserve-ratio table showed no data when we checked in December 2026, so treat any such page as a claim to verify. Done well, proof of reserves is defense in depth applied to trust itself: customers can check instead of taking the platform's word for it.

Designing Layers That Fail Independently

Stacking layers only helps if they fail independently. A few rules of thumb:

Avoid shared dependencies. If your 2FA check and your allowlist both trust the same session token, stealing that token defeats both. Each layer should rely on different evidence.

Watch the layers, not just the outcome. A sudden rise in address_in_cool_off holds is an early warning of an account-takeover campaign, long before any money moves.

Test each layer alone, and test it missing. Because every check shares one interface, you can unit-test each in isolation, then remove one from the checks array and see what the others still catch.

Roll out changes gradually. Run a new rule in "log only" mode first, recording what it would have done, before it starts holding real users' money.

Frequently Asked Questions

What is defense in depth?

It's a security design in which several independent controls protect the same asset, so that the failure of any one of them doesn't lead to a breach. Each layer is designed on the assumption that the others may already have failed.

Isn't two-factor authentication at login enough?

No. Login 2FA protects the start of a session, but sessions can be hijacked afterwards. Step-up authentication checks again at the moment of the risky action, and only accepts a recent check.

Why hold suspicious requests instead of blocking them?

Most suspicious-looking requests are legitimate: a new phone, a trip abroad, a large but planned withdrawal. Blocking them frustrates real users. A hold lets a person decide, and for rare high-value actions a short delay is usually acceptable.

Do I need idempotency keys if my client never retries?

Yes. Mobile networks, proxies and load balancers can all resend a request your code only sent once. An idempotency key makes a duplicate harmless.

Does this apply outside crypto?

Yes. Any endpoint that moves money, exports data or changes who controls an account benefits from the same layers: payouts, refunds, bulk exports and admin role changes are common examples.

Wrapping Up

The withdraw button looks like one action. Behind it, a well-designed system asks five separate questions: is this really you, is this really your destination, how much can go wrong, does this look normal, and who holds the keys. A sixth layer makes the answers verifiable.

You probably aren't building an exchange. But you almost certainly have an endpoint that deserves the same treatment, whether that's a payout, a data export or an admin role change. Pick it, list the layers that protect it today, and ask what happens when each one fails. If the answer is ever "everything", you've found your next layer.

proton_pass_2026_11_footer
Source: Div John · www.sitepoint.com