Home / Offline game server project

Offline game server project

1 year, 2 months

Ethereal.su

Current version of the site (Design Inspiration: BUM-16, credit @Benn Jordan)

Early Design

A rather sentimental story for me: my career began with a project like this.

After school I hadn’t decided what to do, attended law college for a couple of months — it turned out not to be my thing — and decided to “lose” a year trying to find a suitable career.

By chance I came across a semi-guide on YouTube about creating a project like this.
At that time it was a ready-made launcher with its own backend, to which an auth endpoint was attached via a config file, a PHP site on some paid CMS for a blog, and a ready-made PHP profile module.

During my school years, in my free time, I spent hundreds of hours on projects like these.
For most authors these were, of course, hobby projects — if they brought any profit, it was extremely dubious after subtracting the cost of hardware rental.
As a result, every project had a bunch of problems and a decent list of things I would have implemented differently.

I launched that project after a couple of months of work.
It lived for about six months due to a lack of funding for hosting (at that time I was unemployed, not even a student yet), but I liked the development process, and I decided on my career.

For the last couple of years, somewhere in my subconscious, an idea periodically circled:

My hands never really got to it — mostly because of a lack of time; I also didn’t want to use Electron because of the large executable size.
In parallel, the thought of finally touching Rust was circling; I had known about Tauri back in 2023.

Stack

Frontend:  Next.js, TypeScript, Zustand, Base UI, i18n, Fuse.js, React-hook-form
Desktop:   Rust, Tauri, Tokio, Reqwest, Rayon, sha1, zip
API:       Rust, Actix Web, PostgreSQL, Redis, sqlx, argon2, resend-rs, terra, image
Proxy:     Rust, Actix Web, Reqwest
Toolchain: Bun, GitHub, GitHub Actions, Docker

Project structure

Currently the project is in a pre-release state: core functionality is fully complete. The only server is now in offline/testing mode.
MVP functionality was written in 2 months. The site and launcher went through 3 full redesigns.

I’m still thinking about systematic monetization (structure and whether to have it at all) and a possible source-code release — first of all this is a hobby project for myself, more as experience working with all sides.

Website

Actively uses Next API routes as middleware.
According to the Yggdrasil spec, most auth routes expect the auth token as a field in the JSON/body of the request.
For auth routes, the website communicates only with Next API and uses the auth-token only as an http-only cookie.

Token authorization (Next API → 2 separate requests: validate + refresh) — ~70 ms in DevTools.

Functionality:

Launcher

binaries

Files are shared between different game client instances: part of the assets and libraries for most game client versions match.
If two clients have the same game version and modloader version, then for the second client you actually only need to download mods and configs — about 10% of a typical build.

Most launchers in the competing category download the entire game client as a single archive with all assets and libraries for each game client.

Functionality:

API

api.ethereal.su

Functionality:

Proxy

proxy.ethereal.su

A necessary component for successfully downloading the game client without user intervention in the current realities of blocking.

Functionality:

API /authserver/refresh

#[post("/refresh")]
pub async fn post(
    app_state: web::Data<AppState>,
    payload: web::Json<PostRequestPayload>,
) -> impl Responder {
    let stored_user_id = match app_state
        .redis_manager
        .refresh_access_token(&payload.access_token, &payload.client_token)
        .await
    {
        Ok(id) => id,
        Err(e) => return e.error_response(),
    };

    let user = match app_state
        .pg_pool
        .get_user(UserLookup::ById(&stored_user_id))
        .await
    {
        Ok(Some(usr)) => usr,
        Ok(None) => return AppError::internal("User not found").error_response(),
        Err(e) => return AppError::internal(format!("Database error: {}", e)).error_response(),
    };

    if let Some(char_profile) = &payload.selected_profile {
        if char_profile.id != user.character_id {
            return AppError::forbidden("Invalid token.").error_response();
        }
    };

    return HttpResponse::Ok().json(user::Payload::new(
        user,
        payload.access_token.clone(),
        payload.request_user,
        &app_state.encrypt,
        &app_state.public_api_url,
    ));
}

pub async fn refresh_access_token(
    &self,
    access_token: &str,
    user_id: &Option<String>,
) -> Result<String, AppError> {
    let mut conn = self.manager.lock().await;
    let token_key = format!("auth:token:{}", access_token);

    let stored_id = match conn.get(&token_key).await {
        Ok(Some(id)) => id,
        Ok(None) => return Err(AppError::forbidden("Invalid token.")),
        Err(e) => return Err(AppError::internal(format!("Redis error: {}", e))),
    };

    if let Some(request_id) = user_id {
        if !stored_id.contains(request_id) {
            return Err(AppError::forbidden("Invalid token."));
        }
    }

    let user_id = match stored_id.split(':').next() {
        Some(id) => id.to_string(),
        None => return Err(AppError::forbidden("Invalid token.")),
    };

    if let Err(e) = conn.expire(token_key, 60 * 60 * 24 * 7).await {
        return Err(AppError::internal(format!("Redis error: {}", e)));
    }

    return Ok(user_id);
}

Website /api/refresh

export const GET = async (_: NextRequest) => {
  const cookieStore = await cookies();

  const accessToken = cookieStore.get("accessToken");
  const clientToken = cookieStore.get("clientToken");

  if (!accessToken?.value) {
    return new Response(null, { status: 401 });
  }

  try {
    await axiosServer.post(`${apiUrl}/authserver/validate`, {
      accessToken: accessToken.value,
      clientToken: clientToken?.value,
    });

    const res = await axiosServer.post<ApiResponse>(
      `${apiUrl}/authserver/refresh`,
      {
        accessToken: accessToken.value,
        clientToken: clientToken?.value,
        requestUser: true,
      },
    );

    cookieStore.set("accessToken", res.data.accessToken, options);
    cookieStore.set("clientToken", res.data.clientToken, options);

    return Response.json(profileData(res.data), { status: 200 });
  } catch (e) {
    cookieStore.delete("accessToken");
    cookieStore.delete("clientToken");

    return catchGenericApi(e);
  }
};

Launcher event-system

const handlers = {
    //...
    [EmitEvent.LauncherAuthSuccess]: (data: AuthData) => {
        useUserStore.getState().setUser(data);

        useTerminalStore.getState().addLog({
          key: "init.user.success",
          type: LogType.Success,
          props: { username: data.username },
        });
    },
    [EmitEvent.LauncherAuthFailure]: (_error: string) => {
        useUserStore.getState().setUser({ hydrated: true });

        useTerminalStore.getState().addLog({
          key: "init.user.error",
          type: LogType.Text,
        });
    },
};

export const setupEventListeners = async () => {
  const unsubs = Object.keys(handlers).map((event) =>
    listen(event, (e) => handlers[event as keyof typeof handlers](e.payload)),
  );

  return await Promise.all(unsubs);
};

export const clearEventListeners = (unsubs: Array<() => void>) => {
  for (const unsub of unsubs) {
    unsub();
  }
};

Launcher http-client request

pub async fn send_request_once(
    url: &str,
    use_stream_client: bool,
    should_proxy: bool,
) -> Result<reqwest::Response, AppError> {
    let req_client = match use_stream_client {
        true => stream_client(),
        false => http_client(),
    };

    let token = cancel::global_token();

    if token.is_cancelled() {
        return Err(AppError::http_cancel());
    }

    pause::wait_if_paused().await;

    let req_url = if should_proxy {
        url.to_string()
    } else {
        crate::setup::mirror::apply_mirror_to_url(url)
    };

    let req_fut = if should_proxy {
        let token = match commands::auth::get_auth_tokens().await {
            Ok(ts) => ts.access_token,
            Err(_) => return Err(AppError::http_request("missing auth token")),
        };

        let cookie = match token {
            Some(t) => format!("accessToken={}", t),
            None => return Err(AppError::http_request("missing auth token")),
        };

        req_client.get(req_url).header(COOKIE, cookie).send()
    } else {
        req_client.get(req_url).send()
    };

    tokio::select! {
        _ = token.cancelled() => Err(AppError::http_cancel()),
        resp = req_fut => resp.map_err(|e| AppError::http_response(e.to_string(), e.status().map_or(0, |s| s.as_u16()))),
    }
}