~starkingdoms/starkingdoms

3419bb382f3605f71005a8643d3761cbbc47fdd9 — core 1 year, 8 months ago 5d171f7
fmt
M starkingdoms-api/src/main.rs => starkingdoms-api/src/main.rs +1 -1
@@ 51,7 51,7 @@ pub struct AppState {
    pub pool: bb8::Pool<AsyncDieselConnectionManager<AsyncPgConnection>>,
    pub idgen: Arc<Mutex<SnowflakeIdGenerator>>,
    pub key: Hmac<Sha256>,
    pub key_raw: Vec<u8>
    pub key_raw: Vec<u8>,
}

pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations");

M starkingdoms-api/src/models.rs => starkingdoms-api/src/models.rs +1 -1
@@ 22,5 22,5 @@ use diesel::{Identifiable, Insertable, Queryable, Selectable};
pub struct Save {
    pub id: i64,
    pub user_id: i64,
    pub pack: String
    pub pack: String,
}

M starkingdoms-api/src/routes/mod.rs => starkingdoms-api/src/routes/mod.rs +1 -1
@@ 13,4 13,4 @@
//
//     You should have received a copy of the GNU Affero General Public License
//     along with this program.  If not, see <https://www.gnu.org/licenses/>.
pub mod sign_save;
\ No newline at end of file
pub mod sign_save;

M starkingdoms-api/src/routes/sign_save.rs => starkingdoms-api/src/routes/sign_save.rs +26 -10
@@ 14,8 14,6 @@
//     You should have received a copy of the GNU Affero General Public License
//     along with this program.  If not, see <https://www.gnu.org/licenses/>.

use std::collections::HashMap;
use std::hash::Hash;
use crate::response::JsonAPIResponse;
use crate::AppState;
use actix_web::{


@@ 25,17 23,21 @@ use actix_web::{
};
use log::error;
use serde::{Deserialize, Serialize};
use starkingdoms_common::{__noverify__unpack_savefile, pack_savefile, PartType, SaveModule, unpack_savefile};
use starkingdoms_common::{
    __noverify__unpack_savefile, pack_savefile, unpack_savefile, PartType, SaveModule,
};
use std::collections::HashMap;
use std::hash::Hash;

#[derive(Deserialize)]
pub struct SignSaveRequest {
    pub old_save: String,
    pub new_partial: String
    pub new_partial: String,
}

#[derive(Serialize, Debug)]
pub struct SignSaveResponse {
    pub signed_save: String
    pub signed_save: String,
}

fn inc<T: Hash + PartialEq + Clone + Eq>(a: &mut HashMap<T, u64>, t: &T, by: u64) {


@@ 67,7 69,11 @@ pub async fn sign_save_req(
    let mut part_counts_old: HashMap<PartType, u64> = HashMap::new();

    for unused_modules in &old_save.unused_modules {
        inc(&mut part_counts_old, &unused_modules.0, unused_modules.1 as u64);
        inc(
            &mut part_counts_old,
            &unused_modules.0,
            unused_modules.1 as u64,
        );
    }
    for child in &old_save.children {
        recursive_inc(&mut part_counts_old, child);


@@ 76,24 82,34 @@ pub async fn sign_save_req(
    let mut part_counts_new: HashMap<PartType, u64> = HashMap::new();

    for unused_modules in &new_save.unused_modules {
        inc(&mut part_counts_new, &unused_modules.0, unused_modules.1 as u64);
        inc(
            &mut part_counts_new,
            &unused_modules.0,
            unused_modules.1 as u64,
        );
    }
    for child in &new_save.children {
        recursive_inc(&mut part_counts_new, child);
    }

    if part_counts_old != part_counts_new {
        error!("save validation failed: {:?} -> {:?}", part_counts_old, part_counts_new);
        error!(
            "save validation failed: {:?} -> {:?}",
            part_counts_old, part_counts_new
        );
        error!("old file: {:?}", old_save);
        error!("new file: {:?}", new_save);
        err!(
            StatusCode::BAD_REQUEST,
            make_err!("ERR_SAVE_VALIDATION_FAILED", "save validation failed: part counts do not match")
            make_err!(
                "ERR_SAVE_VALIDATION_FAILED",
                "save validation failed: part counts do not match"
            )
        )
    }

    // resign the savefile and return it to the user
    

    ok!(SignSaveResponse {
        signed_save: pack_savefile(&state.key_raw, new_save)
    })

M starkingdoms-client/src/pages/ShipEditor.svelte => starkingdoms-client/src/pages/ShipEditor.svelte +6 -6
@@ 5,7 5,7 @@
  import "../css/style.scss";
  import HeartIcon from "../icons/HeartIcon.svelte";
  import Popup from "../components/ui/Popup.svelte";
  import {__pack_save_for_api, unpack_save} from "../save.ts";
  import { __pack_save_for_api, unpack_save } from "../save.ts";
  import { PartType } from "../protocol.ts";
  import { onMount } from "svelte";
  import { part_texture_url } from "../textures.ts";


@@ 363,15 363,15 @@

      let packed_savefile = __pack_save_for_api(save_data);

      let r = await fetch(config.environments[3].apiBaseUrl + '/sign_save', {
        method: 'POST',
      let r = await fetch(config.environments[3].apiBaseUrl + "/sign_save", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          old_save: window.localStorage.getItem("save")!,
          new_partial: packed_savefile
        })
          new_partial: packed_savefile,
        }),
      });

      if (r.ok) {

M starkingdoms-client/src/save.ts => starkingdoms-client/src/save.ts +3 -13
@@ 12,22 12,12 @@ function bytesToBase64(bytes: any) {
}

export function unpack_save(data: string): any {
    console.log(decode(base64ToBytes(data)));
  console.log(decode(base64ToBytes(data)));
  // @ts-ignore
  return decode(decode(base64ToBytes(data))[0]);
}

export function __pack_save_for_api(data: any): string {
    console.log([
        encode(data),
        []
    ]);
  return bytesToBase64(
      encode(
          [
              Array.from(encode(data)),
              []
          ],
      )
  );
  console.log([encode(data), []]);
  return bytesToBase64(encode([Array.from(encode(data)), []]));
}

M starkingdoms-common/src/lib.rs => starkingdoms-common/src/lib.rs +0 -1
@@ 101,7 101,6 @@ pub fn __noverify__unpack_savefile(file: String) -> Result<SaveData, Box<dyn Err
    let save_file: Savefile = rmp_serde::from_slice(&savefile_bytes)
        .map_err(|e| format!("error decoding savefile wrapper: {e}"))?;


    let save_data = rmp_serde::from_slice(&save_file.data_msgpack)
        .map_err(|e| format!("error decoding inner signature: {e}"))?;