Back to the main page

Public code, with tests

A login that holds under attack

Passwordless login for a small admin page on an edge function (Cloudflare Pages Functions or Workers): the owner types an email address, gets a 6-digit code by mail and types it back. No passwords, no dependencies, Web Crypto only. It is the login of a small production tool, cut out into its own repository so the code and its tests can be read on their own.

Built with: JavaScript, Web Crypto, SQLite (D1), node:test

The bug the tests were written for

An earlier version kept the guess counter on the code record in a key-value store: read the count, compare the code, write the count plus one. That store has no compare-and-set, so 200 parallel guesses all read a count of zero. In a test, all 200 were compared, and the right code still worked afterwards.

The fix

Codes and counters moved to D1 (SQLite), and every guess is claimed in one atomic statement before the code is compared. Of two parallel requests with the right code, only the one whose delete removed the row logs in.

The test

The tests run the handler against a real SQLite database behind the D1 interface, with a pause before every statement so parallel requests interleave. The first test fires 200 parallel guesses with the right code in the middle: exactly 5 are evaluated, 195 are refused, none logs in. Swapping the atomic claim for a read-then-write counter makes the parallel tests fail.

What else it defends against

  • Guessing: guesses are capped per address and IP, and per address across all IPs.
  • Finding out who may log in: the answer is the same for listed and unlisted addresses.
  • A stolen code table: only a keyed hash of each code is stored, and codes expire after 10 minutes.
  • A forged session cookie: the cookie is signed with HMAC-SHA256 and compared in constant time.
  • Access kept after removal: an address taken off the allowlist loses its session on the next request.

Known limits

  • Strangers on two IPs can spend the hourly guesses and lock the owner out for up to an hour. A lockout can be recovered from; a guessed code cannot.
  • Logout clears the cookie in the browser, but a copied cookie stays valid until it expires or the address is removed.

Contact

Reach me by email, in Swedish or English. References on request.

Languages: Swedish and English (fluent), Spanish (elementary).

Isak Mesihovic, Gothenburg.