Skip to content

Commit

Permalink
save a bunch of shit
Browse files Browse the repository at this point in the history
  • Loading branch information
jaybutera committed Aug 21, 2023
1 parent 17bc022 commit ae3da28
Show file tree
Hide file tree
Showing 11 changed files with 287 additions and 11 deletions.
35 changes: 31 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,5 @@ rexiv2 = "0.10.0"
rand = "0.8.5"
rand_core = "0.6.3"
ed25519-dalek = { version = "2.0.0", features = ["rand_core"] }
base64 = "0.21.2"
sha3 = "0.10.8"
15 changes: 13 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ use smol::io::{AsyncRead, AsyncReadExt, BufReader};
use smol::stream::StreamExt;
use sha3::Digest;
use rand_core;
//use async_channel::{TryRecvError};

use crate::migrations::generate_thumbnails;
use crate::utils::{
Expand Down Expand Up @@ -85,6 +84,7 @@ async fn main_async() -> tide::Result<()> {
};

let mut app = tide::with_state(state);
use tide::http::cookies::SameSite;
let cors = CorsMiddleware::new()
.allow_methods("GET, POST, OPTIONS".parse::<HeaderValue>().unwrap())
//.allow_origin(Origin::from("*"))
Expand All @@ -94,7 +94,8 @@ async fn main_async() -> tide::Result<()> {
tide::sessions::MemoryStore::new(),
&"sessionasdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdf".to_string().into_bytes(),
//args.session_key.as_bytes(),
);
)
.with_same_site_policy(SameSite::Lax);
app.with(sessions);
app.with(cors);

Expand Down Expand Up @@ -134,6 +135,11 @@ async fn generate_challenge(mut req: Request<ServerState>) -> tide::Result {

// Store the challenge in the session
req.session_mut().insert("challenge", challenge.to_vec())?;

// Get the sid from the session
let sid = req.session().id();
log::info!("Session ID: {}", sid);

let challenge = base64::encode(challenge);

let res = Response::builder(200)
Expand All @@ -149,6 +155,9 @@ async fn authenticate(mut req: Request<ServerState>) -> tide::Result {
let pubkey: [u8; 32] = payload.public_key[..].try_into()?;
let public_key = VerifyingKey::from_bytes(&pubkey)?;

let sid = req.session().id();
log::info!("Session ID: {}", sid);

// Check if the challenge in the session matches the provided challenge
let stored_challenge = req.session().get::<Vec<u8>>("challenge")
.ok_or(to_badreq(anyhow!("No challenge found in session!")))?;
Expand Down Expand Up @@ -223,6 +232,8 @@ async fn get_image_full(req: Request<ServerState>) -> tide::Result {
}

async fn get_image_thumbnail(req: Request<ServerState>) -> tide::Result {
let sid = req.session().id();
log::info!("Session ID: {}", sid);
let name = req.param("name")?;
let mut path = req.state().args.root_dir.clone();
// Use the thumbnail
Expand Down
103 changes: 102 additions & 1 deletion ui/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@
},
"type": "module",
"dependencies": {
"bootstrap": "^5.3.0"
"@noble/ed25519": "^2.0.0",
"bootstrap": "^5.3.0",
"buffer": "^6.0.3",
"noble-ed25519": "^1.2.6",
"tweetnacl": "^1.0.3",
"tweetnacl-ts": "^1.0.3"
}
}
22 changes: 22 additions & 0 deletions ui/src/components/ErrorMessage.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<script>
import { onMount } from 'svelte';
let messages = [];
onMount(() => {
const handler = (e) => {
messages.push(e.detail);
};
document.addEventListener('app-error', handler);
return () => {
document.removeEventListener('app-error', handler);
};
});
</script>

{#each messages as message (message.id)}
<div class="error">
{message.text}
</div>
{/each}
51 changes: 49 additions & 2 deletions ui/src/lib/img.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,59 @@
import { sign } from 'tweetnacl';
import { Buffer } from 'buffer';
import * as ed from '@noble/ed25519';
//import * as nacl from 'tweetnacl';
// Img server address
//export const img_server: string = "http://127.0.0.1:2342";
export const img_server: string = "https://img.smdhi.xyz:8080";
export const img_server: string = "http://127.0.0.1:2342";
//export const img_server: string = "https://img.smdhi.xyz:8080";

interface Index {
name: string;
topics: string[];
}

export async function authenticate(challenge: Uint8Array): Promise<void> {
let private_key = localStorage.getItem('private_key');
const decoded = Buffer.from(private_key, 'base64');
// Convert private key to Uint8Array
//let keypair = sign.keyPair.fromSecretKey(decoded);
const pubKey = await ed.getPublicKeyAsync(decoded);
const sig = await ed.signAsync(challenge, decoded);
/*
let sig = sign(challenge, keypair.secretKey);
console.log(JSON.stringify({
signature: [...sig],
public_key: [...keypair.publicKey],
}));
*/

const response = await fetch(`${img_server}/authenticate`, {
method: 'POST',
credentials: 'include',
body: JSON.stringify({
signature: [...sig],
public_key: [...pubKey],
}),
});

if (!response.ok) {
throw new Error(`Error authenticating: ${response.status}`);
}
}

export async function get_challenge(): Promise<Uint8Array> {
const response = await fetch(`${img_server}/generate-challenge`, {
credentials: 'include',
});

if (!response.ok) {
throw new Error(`Error getting challenge: ${response.status}`);
}
let encoded = await response.json();
console.log(encoded);
const decoded = Buffer.from(encoded, 'base64');
return decoded;
}

export async function generate_key(): Promise<Uint8Array> {
let response = await fetch(`${img_server}/generate-key`);
return response;
Expand Down
Loading

0 comments on commit ae3da28

Please sign in to comment.