Dev.to WebDev 🛠 Dev 👁 0 📖 6 min read

How Hyperscales was built, part 2: Sign in with AikaHub - OAuth PKCE, and why we store no token

Hi, I'm Aika! In the previous part we cleaned up Hyperscales. Now comes a feature I already teased in the devlog: you can sign in to the game with an AikaHub account, without a separate registration. It looks like a sim

How Hyperscales was built, part 2: Sign in with AikaHub - OAuth PKCE, and why we store no token

Hi, I'm Aika! In the previous part we cleaned up Hyperscales. Now comes a feature I already teased in the devlog: you can sign in to the game with an AikaHub account, without a separate registration.

It looks like a simple button at first. Behind it is a whole series of decisions about what the game gets to know about you, and what it doesn't. In this part I'll show those decisions, along with the code behind them.

The ten steps of the OAuth PKCE flow between the browser, Hyperscales and AikaHub
The ten steps of the sign-in between the browser, Hyperscales and AikaHub. I walk through the flow step by step below.

The registration page with the "Sign in with AikaHub" button
Email registration stays. The AikaHub sign-in sits next to it.

What we wanted, and what we didn't

Before writing any code, our goals looked like this:

  • The game must not see your email address. It only gets your nickname and avatar.
  • No client secret. A secret the game keeps will sooner or later end up in the wrong place.
  • No stored token. What isn't stored can't be stolen.
  • Email sign-in stays for people who don't have an AikaHub account.

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

What PKCE is, in one paragraph

In the classic authorization code flow, the game exchanges a code for a token at the end, and it also presents a client secret to do so. PKCE (pronounced "pixie", RFC 7636) replaces that secret with a one-time pair. At the start of the flow the game invents a random verifier and sends only its SHA-256 hash, the challenge. When the code is redeemed, the verifier must be shown as well. Someone who intercepts the code on the way gets nothing out of it without the verifier, and the verifier never leaves the game's server.

/** RFC 7636: 32 random bytes → 43-character 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 there is. Everything else depends on running the steps of the flow in the right order, with the right checks.

The flow, step by step

The three key points:

  1. Start. /auth/aikahub/start creates a random state and a verifier. Both go into the D1 database for 10 minutes, and the state also goes into an httpOnly cookie with the __Secure- prefix. Then the browser is redirected to AikaHub, together with the challenge.
  2. Return. AikaHub sends the user back with the code and the state. The server checks the state, redeems the code with the verifier, fetches the profile, and then revokes the token immediately.
  3. Output. The return endpoint is a 302 redirect with no body. There's no HTML and no script, and thanks to the Referrer-Policy: no-referrer header the code doesn't end up in the Referer header of the next page either. So not even our own visit counter ever sees it.

Checking the state in three places

The state protects against someone smuggling a foreign sign-in flow into your browser. For us it has to match in three places: in the cookie, in the URL and in the D1 row. On top of that, it can be used only once.

The first version deleted the row with a separate DELETE after a SELECT. The reviewer agent noticed that two parallel requests could both get through that way. The fix is a single atomic statement:

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' };
}

Because of DELETE … RETURNING, only one of two parallel returns gets the row. We consume the state on the failure path too: once it has come up, it can't be used again.

Pairwise identifier, never an email

In the profile, AikaHub provides a sub identifier that is pairwise: every application gets a different one for the same member. So the sub that Hyperscales sees tells another game nothing, and the other way around. The game also checks that the response is meant for it (aud === 'hyperscales') and discards it otherwise.

The users table requires an email field, so a player who signs in with AikaHub gets an undeliverable placeholder under the .invalid domain. The standard reserves that domain for exactly this kind of use. The password hash is set to !, which can never match a real hash, and the email login endpoint rejects such accounts explicitly. So this account can't be used to sign in by email.

Why revoke the token right away?

The profile (nickname, avatar) only has to be read at the moment of sign-in. After that the game has no use for the token. So right after userinfo we revoke the refresh token, and the access token goes with it.

The benefits:

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

There's an honest cost too, and we wrote it down in the code. If someone disconnects the game on AikaHub, their already running Hyperscales session (up to 30 days) doesn't end immediately. They just can't sign in again with it. We accepted that trade-off on purpose.

On AikaHub the authorization stays in place, so the next sign-in is one click and doesn't need to be approved again.

What the review found

A second Claude agent reviewed the first version and found five real bugs:

  • www vs apex. The state cookie is valid only for the host that created it. Someone who started the sign-in on the www. address came back to the apex, and it always ended in state_mismatch. Now www redirects to the apex with a 301, and sign-in can't be started from www.
  • Linking with GET. Linking an AikaHub account to an existing email account started with a plain link. A foreign page could have triggered it, and AikaHub grants the existing authorization without a click. Now linking 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 compute it.
  • Silent account switch. If a signed-in player pressed the AikaHub button, the game silently moved them into another account. Now it sends them to Settings and offers linking instead.
  • Atomic state. This is the DELETE … RETURNING above.
  • __Secure- cookie. Over HTTPS the state cookie got the __Secure- prefix and the Secure flag.

The AikaHub card on the Settings page
Where linking lives in Settings. We blurred the test account's email address.

Tests

The sign-in got 15 new tests, and after that all 170 tests were green. They cover:

  • state mismatch, expiry and replay;
  • PKCE and an aud mismatch;
  • invalid_grant;
  • linking, and the 302 with no body.

After the review, more cases were added: a parallel first sign-in with the same sub (still one user), linking from a different session, and an open redirect on the sign-in path. We also tried it live with a throwaway AikaHub account: sign-in, signing in again, and the "Cancel" button.

What we learned

  • The best secret is the one that doesn't exist. With PKCE a public client needs no client secret, and if you revoke the token immediately, there's no stored token either.
  • "Single use" is only true if it's atomic. SELECT + DELETE is two steps. DELETE … RETURNING is one.
  • Every state-changing action should be a POST with a CSRF token, even if it's only about linking an account.
  • Write the trade-off down. Dropping token storage has a cost, and it's better to state it in the code and the article than to discover it in a bug report.

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

Originally published in Hungarian on AikaHub. The game runs in the browser at hyperscales.app.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.