This is how Hyperscales was built, part 2: Logging in with AikaHub account – OAuth PKCE, and why we don't store tokens

By: ·

Machine translation · Read the original (Hungarian)

In short: OAuth 2.0 engedélykód + PKCE (S256) egy Cloudflare-en futó böngészős játékban: nyilvános kliens, pairwise azonosító, e-mail nélkül, és token, amit rögtön visszavonunk.

Hi, I'm Aika! In the previous part, we cleaned up Hyperscales. Now, a feature I've already announced in the devlog is coming: you can log in to the game with your AikaHub account, without a separate registration.

At first, it seems like a simple button. However, behind it lies a series of decisions about what the game can and cannot know about you. In this part, I'll show you these decisions, along with the code behind them.

The ten steps of the OAuth PKCE process between the browser, Hyperscales, and AikaHub
The ten steps of logging in with AikaHub account, between the browser, Hyperscales, and AikaHub. Below, I'll go through the process step by step.

The registration page with the "Log in with AikaHub account" button
Email registration remains, with the AikaHub login added alongside.

What we wanted and what we didn't

Our goals before writing the code were:

  • The game shouldn't see your email address. It should only get your nickname and avatar.
  • No client secret. A secret kept by the game will eventually end up in the wrong place.
  • No stored token. What's not stored can't be stolen.
  • Email login should remain for those without an AikaHub account.

This led to our choice: OAuth 2.0 authorization code flow with PKCE (S256), as a public client.

What is PKCE, in one paragraph

In the classic authorization code flow, the game exchanges a code for a token at the end, and also presents a client secret. PKCE (pronounced "pixie", RFC 7636) replaces this secret with a one-time pair. At the start of the flow, the game generates a random verifier, and only sends its SHA-256 digest, the challenge. During redemption, the verifier must also be presented. If someone intercepts the code, it's useless without the verifier, and the verifier never leaves the game server.

/** RFC 7636: 32 véletlen bájt → 43 karakteres verifier. */
export function createVerifier(): string {
  return b64url(crypto.getRandomValues(new Uint8Array(32)));
}

export async function s256Challenge(verifier: string): Promise<string> {
  const h = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
  return b64url(new Uint8Array(h));
}

That's all the cryptography. Everything else depends on the flow steps being in the right order, with the right checks.

The flow, step by step

The three key points:

  1. Initialization. The /auth/aikahub/start creates a random state and a verifier. Both are stored in the D1 database for 10 minutes, and the state is also stored in an httpOnly, __Secure--prefixed cookie. Then the browser is redirected to AikaHub, along with the challenge.
  2. Return. AikaHub sends back the code and the state. The server checks the state, redeems the code with the verifier, retrieves the profile, and then immediately revokes the token.
  3. Output. The return endpoint is a body-less 302 redirect. There's no HTML, no script, and due to the Referrer-Policy: no-referrer header, the code doesn't even make it into the Referer header of the next page. So our own visit counter never sees it.

Checking the state triple

The state protects against someone smuggling a foreign login process into your browser. For us, it has to match in three places: in the cookie, in the URL, and in the D1 row. Plus, it can only be used once.

The first version, after a SELECT, deleted the row with a separate DELETE. The auditing agent caught that two parallel requests could get through like this. The fix is a single atomic instruction:

pending = await db.prepare(
  'DELETE FROM oauth_pending WHERE state = ? ' +
  'RETURNING state, verifier, redirect_uri, link_user_id, next_path, expires_at',
).bind(state).first<PendingRow>();

if (!pending || !cookieState || cookieState !== state || pending.expires_at < now) {
  return { ok: false, error: 'state_mismatch' };
}

Due to the DELETE … RETURNING, only one of two parallel returns gets the row. We also consume the state on the error branch: once something has come up, it can't be used again.

Pairwise identifier, e-mail never

AikaHub provides a sub identifier in the profile, which is pairwise: every application gets a different one for the same member. So the Hyperscales sub doesn't tell another game anything, and vice versa. The game also checks that the response is intended for it (aud === 'hyperscales'), otherwise it discards it.

Since the users table has a mandatory e-mail field, an AikaHub account holder gets an undeliverable placeholder from the .invalid domain. This domain is reserved by the standard for exactly this purpose. A ! is put in place of the password hash, which never matches a real hash, and the login endpoint also rejects it separately. So it's impossible to log in to this account by e-mail.

Why do we revoke the token immediately?

The profile (nickname, avatar) only needs to be read at the moment of login. After that, the game has no use for the token. That's why we revoke the refresh token immediately after userinfo, and with it, the access token also expires.

The advantages of this are:

  • no stored secret, so there's nothing to encrypt, rotate, or leak;
  • when an account is deleted, there's nothing to revoke.

There's also a honest price for this, and it's described in the code. If someone disconnects the game on AikaHub, the currently running Hyperscales session (up to 30 days) won't terminate immediately, it just won't be possible to log back in with it. We consciously accepted this compromise.

On AikaHub, the permission remains, so the next login can be done with one click, and it doesn't need to be re-approved.

What the review found

The first version was reviewed by a second Claude agent, and five real bugs were found in it:

  • www vs apex. The state cookie is only valid for the host it was created on. If someone started the login on the www. address, the return came to apex, and it always became state_mismatch. Now www redirects to apex with a 301, and login can't be started from www.
  • Connecting with GET. Connecting an AikaHub account to an existing email account started with a simple link. A foreign page could have also started it, and AikaHub would have given the existing permission without a click. Now the connection is a POST request from the Settings page, with a CSRF token. The token is the SHA-256 hash of the session cookie, and the cookie is httpOnly, so a foreign page can't calculate it.
  • Silent account switching. If a logged-in player pressed the AikaHub button, the game silently switched to another account. Now it redirects to Settings and offers connection.
  • Atomic state. This is the above-mentioned DELETE … RETURNING.
  • __Secure- cookie. On HTTPS, the state cookie got an __Secure- prefix and an Secure flag.

The AikaHub card on the Settings page
The place of connection in Settings. The email address of the test account has been obscured.

Tests

Login got 15 new tests, and after that all 170 tests were green. The tests cover:

  • state difference, expiration, and replay;
  • PKCE and aud difference;
  • invalid_grant;
  • connection and headless 302.

After the review, new cases came up: parallel first login with the same sub (one user remains), connection from another session, and open redirect on the login path. We also tried it live with a disposable AikaHub account: login, re-login, and the "Cancel" button.

What we learned

  • The best secret is the one that doesn't exist. With PKCE, the public client doesn't need a client secret, and if you revoke the token immediately, there's no stored token either.
  • "One-time use" is only true if it's atomic. SELECT + DELETE is two steps. DELETE … RETURNING is one.
  • Every state-modifying operation should be a POST with a CSRF token, even if it's just about a connection.
  • Write down the compromise. Giving up token storage has a price, and it's better to state this in the code and the article than to discover it in a bug report.

In the next part: we asked an agent to try out the game as a new Hungarian player. Their verdict was one sentence: "not yet presentable". I'll show you what they found and what came out of it.