Merge pull request #1 from recurse-chat/working-client

Working client
This commit is contained in:
2026-08-19 03:15:42 +02:00
committed by GitHub
36 changed files with 5804 additions and 299 deletions
+25
View File
@@ -0,0 +1,25 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "base-nova",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/main.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"rtl": false,
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"menuColor": "default",
"menuAccent": "subtle",
"registries": {}
}
+7 -1
View File
@@ -2,9 +2,15 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" /> <!--<link rel="icon" type="image/svg+xml" href="/vite.svg" />-->
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tauri + React + Typescript</title> <title>Tauri + React + Typescript</title>
<style>
html,
body {
background-color: #121212;
}
</style>
</head> </head>
<body> <body>
+4385 -107
View File
File diff suppressed because it is too large Load Diff
+22 -4
View File
@@ -10,17 +10,35 @@
"tauri": "tauri" "tauri": "tauri"
}, },
"dependencies": { "dependencies": {
"@base-ui/react": "^1.7.0",
"@fontsource-variable/geist": "^5.3.0",
"@noble/ed25519": "^3.1.0",
"@noble/hashes": "^2.3.0",
"@scure/base": "^2.3.0",
"@tailwindcss/vite": "^4.3.3",
"@tauri-apps/api": "^2",
"@tauri-apps/plugin-opener": "^2",
"@types/axios": "^0.9.36",
"axios": "^1.19.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^1.31.0",
"next-themes": "^0.4.6",
"react": "^19.1.0", "react": "^19.1.0",
"react-dom": "^19.1.0", "react-dom": "^19.1.0",
"@tauri-apps/api": "^2", "react-resizable-panels": "^4.12.3",
"@tauri-apps/plugin-opener": "^2" "shadcn": "^4.18.0",
"tailwind-merge": "^3.6.0",
"tailwindcss": "^4.3.3",
"tw-animate-css": "^1.4.0"
}, },
"devDependencies": { "devDependencies": {
"@tauri-apps/cli": "^2",
"@types/node": "^26.2.0",
"@types/react": "^19.1.8", "@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6", "@types/react-dom": "^19.1.6",
"@vitejs/plugin-react": "^4.6.0", "@vitejs/plugin-react": "^4.6.0",
"typescript": "~5.8.3", "typescript": "~5.8.3",
"vite": "^7.0.4", "vite": "^7.0.4"
"@tauri-apps/cli": "^2"
} }
} }
-6
View File
@@ -1,6 +0,0 @@
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
</svg>

Before

Width:  |  Height:  |  Size: 2.5 KiB

-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

+48
View File
@@ -0,0 +1,48 @@
use serde::{Deserialize, Serialize};
use std::fs;
use tauri::{AppHandle, Manager};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Account {
pub display_name: String,
pub private_key: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountsFile {
pub active_account: usize,
pub accounts: Vec<Account>,
}
fn accounts_file_path(app: &AppHandle) -> Result<std::path::PathBuf, String> {
let dir = app
.path()
.app_data_dir()
.map_err(|e| format!("Failed to resolve app data dir: {e}"))?;
fs::create_dir_all(&dir).map_err(|e| format!("Failed to create app data dir: {e}"))?;
Ok(dir.join("accounts.json"))
}
#[tauri::command]
pub fn save_accounts(app: AppHandle, data: AccountsFile) -> Result<(), String> {
let path = accounts_file_path(&app)?;
let json = serde_json::to_string_pretty(&data)
.map_err(|e| format!("Failed to serialize accounts: {e}"))?;
fs::write(&path, json).map_err(|e| format!("Failed to write accounts: {e}"))?;
Ok(())
}
#[tauri::command]
pub fn get_accounts(app: AppHandle) -> Result<AccountsFile, String> {
let path = accounts_file_path(&app)?;
if !path.exists() {
return Ok(AccountsFile {
active_account: 0,
accounts: Vec::new(),
});
}
let json = fs::read_to_string(&path).map_err(|e| format!("Failed to read accounts: {e}"))?;
serde_json::from_str(&json).map_err(|e| format!("Failed to parse accounts: {e}"))
}
+2
View File
@@ -0,0 +1,2 @@
pub mod accounts;
pub mod server_list;
+54
View File
@@ -0,0 +1,54 @@
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, fs};
use tauri::{AppHandle, Manager};
use crate::protocol::ServerMeta;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct KnownServer {
pub meta: ServerMeta,
pub public_key: String,
pub is_secure: bool,
}
type ServerList = HashMap<String, KnownServer>;
fn servers_file_path(app: &AppHandle) -> Result<std::path::PathBuf, String> {
let dir = app
.path()
.app_data_dir()
.map_err(|e| format!("Failed to resolve app data dir: {e}"))?;
// ensure the directory exists before we ever try to read/write into it
fs::create_dir_all(&dir).map_err(|e| format!("Failed to create app data dir: {e}"))?;
Ok(dir.join("servers.json"))
}
#[tauri::command]
pub fn save_server_list(app: AppHandle, servers: ServerList) -> Result<(), String> {
let path = servers_file_path(&app)?;
let json = serde_json::to_string_pretty(&servers)
.map_err(|e| format!("Failed to serialize server list: {e}"))?;
fs::write(&path, json).map_err(|e| format!("Failed to write server list: {e}"))?;
Ok(())
}
#[tauri::command]
pub fn get_server_list(app: AppHandle) -> Result<ServerList, String> {
let path = servers_file_path(&app)?;
if !path.exists() {
fs::write(&path, "[]").map_err(|e| format!("Failed to write first server list: {e}"))?;
return Ok(ServerList::new());
}
let json = fs::read_to_string(&path).map_err(|e| format!("Failed to read server list: {e}"))?;
serde_json::from_str(&json).map_err(|e| format!("Failed to parse server list: {e}"))
}
+8 -6
View File
@@ -1,14 +1,16 @@
// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/ pub mod commands;
#[tauri::command] pub mod protocol;
fn greet(name: &str) -> String {
format!("Hello, {}! You've been greeted from Rust!", name)
}
#[cfg_attr(mobile, tauri::mobile_entry_point)] #[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() { pub fn run() {
tauri::Builder::default() tauri::Builder::default()
.plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_opener::init())
.invoke_handler(tauri::generate_handler![greet]) .invoke_handler(tauri::generate_handler![
commands::server_list::save_server_list,
commands::server_list::get_server_list,
commands::accounts::save_accounts,
commands::accounts::get_accounts,
])
.run(tauri::generate_context!()) .run(tauri::generate_context!())
.expect("error while running tauri application"); .expect("error while running tauri application");
} }
+46
View File
@@ -0,0 +1,46 @@
use std::borrow::Cow;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClientMeta {}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerMeta {
pub name: String,
pub description: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "method")]
pub enum ClientMethod {
Initialized {
public_key: String,
signature: String,
timestamp: u64,
hostname: String,
},
Error {
error: Cow<'static, str>,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "method")]
pub enum ServerMethod {
Initialize {
public_key: String,
signature: String,
timestamp: u64,
hostname: String,
},
Meta(ClientMeta),
Error {
error: String,
},
}
-116
View File
@@ -1,116 +0,0 @@
.logo.vite:hover {
filter: drop-shadow(0 0 2em #747bff);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafb);
}
:root {
font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 24px;
font-weight: 400;
color: #0f0f0f;
background-color: #f6f6f6;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
.container {
margin: 0;
padding-top: 10vh;
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: 0.75s;
}
.logo.tauri:hover {
filter: drop-shadow(0 0 2em #24c8db);
}
.row {
display: flex;
justify-content: center;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
h1 {
text-align: center;
}
input,
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
color: #0f0f0f;
background-color: #ffffff;
transition: border-color 0.25s;
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2);
}
button {
cursor: pointer;
}
button:hover {
border-color: #396cd8;
}
button:active {
border-color: #396cd8;
background-color: #e8e8e8;
}
input,
button {
outline: none;
}
#greet-input {
margin-right: 5px;
}
@media (prefers-color-scheme: dark) {
:root {
color: #f6f6f6;
background-color: #2f2f2f;
}
a:hover {
color: #24c8db;
}
input,
button {
color: #ffffff;
background-color: #0f0f0f98;
}
button:active {
background-color: #0f0f0f69;
}
}
+45 -43
View File
@@ -1,51 +1,53 @@
import { useState } from "react"; import { useReducer, useRef } from "react";
import reactLogo from "./assets/react.svg"; import Enclave from "@/app/app";
import { invoke } from "@tauri-apps/api/core"; import ServerList from "./components/view/ServerList";
import "./App.css"; import { NewProfilePage } from "./components/view/NewProfileView";
import {
ResizableHandle,
ResizablePanel,
ResizablePanelGroup,
} from "./components/ui/resizable";
import Sidebar from "./components/view/Sidebar";
import { ThemeProvider } from "next-themes";
function App() { export default function App() {
const [greetMsg, setGreetMsg] = useState(""); const appRef = useRef<Enclave | null>(null);
const [name, setName] = useState(""); const [, forceRender] = useReducer((x) => x + 1, 0);
if (!appRef.current) {
appRef.current = new Enclave();
async function greet() { appRef.current.forceRender = forceRender;
// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
setGreetMsg(await invoke("greet", { name })); appRef.current
.init()
.then(() => {
console.log("Encalve initialized");
forceRender();
})
.catch(console.error);
} }
return ( return (
<main className="container"> <ThemeProvider attribute="class" defaultTheme="system">
<h1>Welcome to Tauri + React</h1> <main className="size-screen flex">
{appRef.current?.accounts &&
<div className="row"> appRef.current.accounts.accounts.length === 0 ? (
<a href="https://vite.dev" target="_blank"> <NewProfilePage appRef={appRef} />
<img src="/vite.svg" className="logo vite" alt="Vite logo" /> ) : (
</a> <>
<a href="https://tauri.app" target="_blank"> <ServerList appRef={appRef} />
<img src="/tauri.svg" className="logo tauri" alt="Tauri logo" /> <ResizablePanelGroup orientation="horizontal" className="h-screen">
</a> <ResizablePanel defaultSize="420px">
<a href="https://react.dev" target="_blank"> <Sidebar appRef={appRef} />
<img src={reactLogo} className="logo react" alt="React logo" /> </ResizablePanel>
</a> <ResizableHandle withHandle />
</div> <ResizablePanel defaultSize="100%">
<p>Click on the Tauri, Vite, and React logos to learn more.</p> <div className="h-screen"></div>
</ResizablePanel>
<form </ResizablePanelGroup>
className="row" </>
onSubmit={(e) => { )}
e.preventDefault();
greet();
}}
>
<input
id="greet-input"
onChange={(e) => setName(e.currentTarget.value)}
placeholder="Enter a name..."
/>
<button type="submit">Greet</button>
</form>
<p>{greetMsg}</p>
</main> </main>
</ThemeProvider>
); );
} }
export default App;
+94
View File
@@ -0,0 +1,94 @@
import { getHTTPUrl, getServerList, ServerList } from "@/lib/serverList";
import EnclaveServer from "./server";
import * as ed from "@noble/ed25519";
import { sha512 } from "@noble/hashes/sha2.js";
import { base58 } from "@scure/base";
import axios from "axios";
import { AccountsFile, getAccounts } from "@/lib/accounts";
ed.hashes.sha512 = sha512;
/**
* Top-level application state and client-side logic.
*
* Owns all active connections — currently `EnclaveServer` instances, one
* per connected server, keyed by server id — and will later also own
* `DMServer` connections once direct messages are implemented.
*
* This is where UI-facing logic lives: handling user actions (button
* clicks, switching the active server, sending a message from an input
* box), and exposing state for the UI layer to render. The UI itself
* should stay a pure display of what `Enclave` exposes — it should not
* reach into `EnclaveServer` or `EnclaveWebSocket` directly.
*/
export default class Enclave {
public accounts?: AccountsFile;
public server?: EnclaveServer;
public serverList: ServerList;
public forceRender: () => void;
public constructor() {
this.serverList = {};
this.forceRender = () => {};
}
public async init() {
this.serverList = await getServerList();
this.accounts = await getAccounts();
}
public async connectToServer(hostname: string, isSecure: boolean) {
if (this.server) {
this.server.disconnect();
}
this.server = new EnclaveServer(hostname, isSecure);
const clientSecretKey = this.getClientSecretKey();
if (!clientSecretKey) {
console.error("Failed to get client key");
return;
}
const clientPublicKey = ed.getPublicKey(clientSecretKey);
await this.server.connect(clientPublicKey, clientSecretKey);
if (!this.server.serverPublicKey) {
console.error("Failed to get public key");
return;
}
if (
this.serverList[hostname]?.publicKey !==
base58.encode(this.server.serverPublicKey)
) {
console.error("Server's new public key doesn't match old one");
return;
}
const metaResponse = await axios.get(
getHTTPUrl(hostname, isSecure, "/meta"),
);
this.server.meta = metaResponse.data as any;
this.serverList[hostname] = {
meta: metaResponse.data as any,
isSecure,
publicKey: base58.encode(this.server.serverPublicKey),
};
this.forceRender();
}
public getClientSecretKey() {
if (!this.accounts) return null;
const account = this.accounts?.accounts[this.accounts.activeAccount];
return account ? base58.decode(account.privateKey) : null;
}
}
+41
View File
@@ -0,0 +1,41 @@
export interface ClientMeta {}
export interface ServerMeta {
name: string;
description: string;
channels: Channel[];
}
export type ClientMethod =
| {
method: "Initialized";
public_key: string;
signature: string;
timestamp: number;
hostname: string;
}
| {
method: "Error";
error: string;
};
export type ServerMethod =
| {
method: "Initialize";
public_key: string;
signature: string;
timestamp: number;
hostname: string;
}
| {
method: "Meta";
}
| {
method: "Error";
error: string;
};
export type Channel = { id: string; name: string } & ChannelKind;
export type ChannelKind =
{ kind: "text" } | { kind: "category"; channels: Channel[] };
+95
View File
@@ -0,0 +1,95 @@
import { base58 } from "@scure/base";
import * as ed from "@noble/ed25519";
import EnclaveWebSocket from "./ws";
import { sha512 } from "@noble/hashes/sha2.js";
import { getWSUrl } from "@/lib/serverList";
import { ServerMeta } from "./protocol";
ed.hashes.sha512 = sha512;
/**
* Represents a known Enclave server, whether connected or not.
*
* Most `EnclaveServer` instances exist purely as metadata — name,
* description, icon, and the server's public key — fetched from the
* server's HTTP endpoints, with no live connection. A server only
* connects when the user opens it (e.g. clicking its icon in the UI).
*
* On connect, `EnclaveServer` performs the key exchange and identity
* handshake itself, storing the resulting `serverPublicKey`, and creates
* the underlying `EnclaveWebSocket` for the live protocol connection.
* Once connected, it also manages channels and messages for that server.
*
* `Enclave` owns and manages multiple `EnclaveServer` instances — one
* per known server, connected or not.
*/
export default class EnclaveServer {
public serverPublicKey?: Uint8Array;
public hostname: string;
public isSecure: boolean;
public websocket?: EnclaveWebSocket;
public meta?: ServerMeta;
public constructor(hostname: string, isSecure: boolean) {
this.hostname = hostname;
this.isSecure = isSecure;
}
public disconnect() {
this.websocket?.websocket.close();
this.websocket = undefined;
}
public async connect(
clientPublicKey: Uint8Array,
clientSecretKey: Uint8Array,
) {
this.websocket = new EnclaveWebSocket(
getWSUrl(this.hostname, this.isSecure),
);
const publicKeyString = base58.encode(clientPublicKey);
const timestamp = Date.now();
const msg = new TextEncoder().encode(`${timestamp}@${this.hostname}`);
this.websocket.send({
method: "Initialize",
public_key: publicKeyString,
signature: base58.encode(ed.sign(msg, clientSecretKey)),
timestamp,
hostname: this.hostname,
});
const initialized = await this.websocket.read();
if (initialized.method !== "Initialized") {
this.disconnect();
throw Error("Invalid method from server, closing. ");
}
if (initialized.hostname !== this.hostname) {
this.disconnect();
throw Error("Server is trying to be a middle man");
}
if (Math.abs(initialized.timestamp - timestamp) > 2000) {
this.disconnect();
throw Error("Server timestamp is desynced");
}
const sigMsg = new TextEncoder().encode(
`${initialized.timestamp}@${this.hostname}@${publicKeyString}`,
);
this.serverPublicKey = base58.decode(initialized.public_key);
const signature = base58.decode(initialized.signature);
if (!ed.verify(signature, sigMsg, this.serverPublicKey)) {
this.websocket.websocket.close();
throw Error("Invalid signature");
}
}
}
+45
View File
@@ -0,0 +1,45 @@
import { ClientMethod, ServerMethod } from "./protocol";
/**
* A protocol-aware wrapper around the browser `WebSocket`.
*
* Exposes typed protocol methods (`ServerMethod` / `ClientMethod`) rather
* than raw WebSocket messages. Has no concept of channels, messages, or
* app state — `EnclaveServer` builds on top of this to add those.
*/
export default class EnclaveWebSocket {
public websocket: WebSocket;
onOpenQueue: Array<() => void>;
public constructor(hostname: string) {
this.onOpenQueue = new Array();
this.websocket = new WebSocket(hostname);
this.websocket.onopen = () => {
this.onOpenQueue.forEach((fun) => fun());
};
}
public async send(method: ServerMethod) {
if (this.websocket.readyState !== WebSocket.OPEN) {
return new Promise<void>((ok) => {
this.onOpenQueue.push(() => {
this.websocket.send(JSON.stringify(method));
ok();
});
});
}
this.websocket.send(JSON.stringify(method));
}
public async read(): Promise<ClientMethod> {
return new Promise((ok) => {
this.websocket.onmessage = (msg) => {
const data = JSON.parse(msg.data);
ok(data);
this.websocket.onmessage = null;
};
});
}
}
-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

Before

Width:  |  Height:  |  Size: 4.0 KiB

+131
View File
@@ -0,0 +1,131 @@
import { useState } from "react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { PlusIcon } from "lucide-react";
// hostname[:port][/path] — explicitly no protocol/scheme allowed
const HOSTNAME_PATTERN =
/^(?!.*:\/\/)[a-zA-Z0-9.-]+(:\d{1,5})?(\/[a-zA-Z0-9\-._~%!$&'()*+,;=:@/]*)?$/;
function validateHostname(value: string): string | null {
if (!value.trim()) {
return "Hostname is required";
}
if (value.includes("://")) {
return "Don't include a protocol (e.g. https://)";
}
if (!HOSTNAME_PATTERN.test(value)) {
return "Invalid hostname format";
}
return null;
}
type AddServerDialogProps = {
onAdd: (hostname: string, isSecure: boolean) => Promise<void> | void;
};
export function AddServerDialog({ onAdd }: AddServerDialogProps) {
const [open, setOpen] = useState(false);
const [hostname, setHostname] = useState("");
const [isSecure, setIsSecure] = useState(true);
const [error, setError] = useState<string | null>(null);
const [submitting, setSubmitting] = useState(false);
function handleHostnameChange(value: string) {
setHostname(value);
if (error) {
setError(validateHostname(value));
}
}
async function handleSubmit() {
const validationError = validateHostname(hostname);
if (validationError) {
setError(validationError);
return;
}
setSubmitting(true);
try {
await onAdd(hostname.trim(), isSecure);
setHostname("");
setIsSecure(true);
setError(null);
setOpen(false);
} catch (e) {
setError(e instanceof Error ? e.message : "Failed to add server");
} finally {
setSubmitting(false);
}
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger
render={() => (
<Button
variant="secondary"
className="aspect-square w-full h-auto rounded-full"
onClick={() => setOpen(true)}
>
<PlusIcon />
</Button>
)}
/>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Add a Server</DialogTitle>
<DialogDescription>
Enter the server's address to connect.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="hostname">Hostname</Label>
<Input
id="hostname"
placeholder="myserver.example.com:8080"
value={hostname}
onChange={(e) => handleHostnameChange(e.target.value)}
aria-invalid={!!error}
/>
{error && <p className="text-sm text-destructive">{error}</p>}
</div>
<div className="flex items-center justify-between">
<Label htmlFor="secure-toggle" className="flex flex-col gap-1">
Secure connection
</Label>
<Switch
id="secure-toggle"
checked={isSecure}
onCheckedChange={setIsSecure}
/>
</div>
</div>
<DialogFooter>
<Button variant="ghost" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button onClick={handleSubmit} disabled={submitting}>
{submitting ? "Adding..." : "Add"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+58
View File
@@ -0,0 +1,58 @@
import { Button as ButtonPrimitive } from "@base-ui/react/button";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/80",
outline:
"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
ghost:
"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
destructive:
"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default:
"h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
icon: "size-8",
"icon-xs":
"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",
"icon-sm":
"size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",
"icon-lg": "size-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
function Button({
className,
variant = "default",
size = "default",
...props
}: ButtonPrimitive.Props & VariantProps<typeof buttonVariants>) {
return (
<ButtonPrimitive
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
);
}
export { Button, buttonVariants };
+158
View File
@@ -0,0 +1,158 @@
import * as React from "react"
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { XIcon } from "lucide-react"
function Dialog({ ...props }: DialogPrimitive.Root.Props) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({ ...props }: DialogPrimitive.Portal.Props) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({ ...props }: DialogPrimitive.Close.Props) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: DialogPrimitive.Backdrop.Props) {
return (
<DialogPrimitive.Backdrop
data-slot="dialog-overlay"
className={cn(
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
className
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: DialogPrimitive.Popup.Props & {
showCloseButton?: boolean
}) {
return (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Popup
data-slot="dialog-content"
className={cn(
"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
render={
<Button
variant="ghost"
className="absolute top-2 right-2"
size="icon-sm"
/>
}
>
<XIcon
/>
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Popup>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2", className)}
{...props}
/>
)
}
function DialogFooter({
className,
showCloseButton = false,
children,
...props
}: React.ComponentProps<"div"> & {
showCloseButton?: boolean
}) {
return (
<div
data-slot="dialog-footer"
className={cn(
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close render={<Button variant="outline" />}>
Close
</DialogPrimitive.Close>
)}
</div>
)
}
function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn(
"font-heading text-base leading-none font-medium",
className
)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: DialogPrimitive.Description.Props) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn(
"text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
className
)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}
+20
View File
@@ -0,0 +1,20 @@
import * as React from "react"
import { Input as InputPrimitive } from "@base-ui/react/input"
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<InputPrimitive
type={type}
data-slot="input"
className={cn(
"h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
className
)}
{...props}
/>
)
}
export { Input }
+18
View File
@@ -0,0 +1,18 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Label({ className, ...props }: React.ComponentProps<"label">) {
return (
<label
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }
+48
View File
@@ -0,0 +1,48 @@
import * as ResizablePrimitive from "react-resizable-panels"
import { cn } from "@/lib/utils"
function ResizablePanelGroup({
className,
...props
}: ResizablePrimitive.GroupProps) {
return (
<ResizablePrimitive.Group
data-slot="resizable-panel-group"
className={cn(
"flex h-full w-full aria-[orientation=vertical]:flex-col",
className
)}
{...props}
/>
)
}
function ResizablePanel({ ...props }: ResizablePrimitive.PanelProps) {
return <ResizablePrimitive.Panel data-slot="resizable-panel" {...props} />
}
function ResizableHandle({
withHandle,
className,
...props
}: ResizablePrimitive.SeparatorProps & {
withHandle?: boolean
}) {
return (
<ResizablePrimitive.Separator
data-slot="resizable-handle"
className={cn(
"relative flex w-px items-center justify-center bg-border ring-offset-background after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-hidden aria-[orientation=horizontal]:h-px aria-[orientation=horizontal]:w-full aria-[orientation=horizontal]:after:left-0 aria-[orientation=horizontal]:after:h-1 aria-[orientation=horizontal]:after:w-full aria-[orientation=horizontal]:after:translate-x-0 aria-[orientation=horizontal]:after:-translate-y-1/2 [&[aria-orientation=horizontal]>div]:rotate-90",
className
)}
{...props}
>
{withHandle && (
<div className="z-10 flex h-6 w-1 shrink-0 rounded-lg bg-border" />
)}
</ResizablePrimitive.Separator>
)
}
export { ResizableHandle, ResizablePanel, ResizablePanelGroup }
+32
View File
@@ -0,0 +1,32 @@
"use client"
import { Switch as SwitchPrimitive } from "@base-ui/react/switch"
import { cn } from "@/lib/utils"
function Switch({
className,
size = "default",
...props
}: SwitchPrimitive.Root.Props & {
size?: "sm" | "default"
}) {
return (
<SwitchPrimitive.Root
data-slot="switch"
data-size={size}
className={cn(
"peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none group-has-[:focus-visible]/field-label:border-transparent group-has-[:focus-visible]/field-label:ring-0 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",
className
)}
{...props}
>
<SwitchPrimitive.Thumb
data-slot="switch-thumb"
className="pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"
/>
</SwitchPrimitive.Root>
)
}
export { Switch }
+89
View File
@@ -0,0 +1,89 @@
import * as ed from "@noble/ed25519";
import { base58 } from "@scure/base";
import { useState } from "react";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { saveAccounts } from "@/lib/accounts";
import Enclave from "@/app/app";
export function NewProfilePage({
appRef,
}: {
appRef: React.RefObject<Enclave | null>;
}) {
const [displayName, setDisplayName] = useState("");
const [error, setError] = useState<string | null>(null);
const [submitting, setSubmitting] = useState(false);
async function handleCreate() {
const name = displayName.trim();
if (!name) {
setError("Display name is required");
return;
}
setSubmitting(true);
setError(null);
try {
if (!appRef.current) {
console.error("AppRef is not initialized yet");
return;
}
if (!appRef.current.accounts) {
appRef.current.accounts = { activeAccount: 0, accounts: [] };
}
const { secretKey } = ed.keygen();
const newAccount = {
displayName: name,
privateKey: base58.encode(secretKey),
};
appRef.current.accounts.activeAccount =
appRef.current.accounts.accounts.length;
appRef.current.accounts.accounts.push(newAccount);
saveAccounts(appRef.current.accounts);
} catch (e) {
setError(e instanceof Error ? e.message : "Failed to create profile");
} finally {
setSubmitting(false);
}
}
return (
<div className="flex h-screen items-center justify-center">
<div className="w-full max-w-sm space-y-6">
<div className="space-y-2 text-center">
<h1 className="text-2xl font-semibold">Create your profile</h1>
<p className="text-sm text-muted-foreground">
Enclave generates a keypair for your identity — no email or password
required.
</p>
</div>
<div className="space-y-2">
<Label htmlFor="display-name">Display name</Label>
<Input
id="display-name"
placeholder="e.g. John Doe"
value={displayName}
onChange={(e) => setDisplayName(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleCreate()}
/>
{error && <p className="text-sm text-destructive">{error}</p>}
</div>
<Button className="w-full" onClick={handleCreate} disabled={submitting}>
{submitting ? "Creating..." : "Create Profile"}
</Button>
</div>
</div>
);
}
+16
View File
@@ -0,0 +1,16 @@
export type ViewProps<C> = C extends React.ComponentType<infer P> ? P : never;
export default function SelectView<
T extends Record<string, React.ComponentType<any>>,
K extends keyof T,
>({
config,
views,
}: {
config: { currentView: K; viewProps: ViewProps<T[K]> };
views: T;
}) {
const ActiveView = views[config.currentView];
return <ActiveView {...config.viewProps} />;
}
+52
View File
@@ -0,0 +1,52 @@
import Enclave from "@/app/app";
import { Channel, ChannelKind } from "@/app/protocol";
import { HashIcon } from "lucide-react";
export function ChannelIcon({ kind }: { kind: ChannelKind["kind"] }) {
switch (kind) {
case "text":
return <HashIcon className="p-0.5" />;
default:
return null;
}
}
export function RenderChannels({ channels }: { channels: Channel[] }) {
return channels.map((channel) =>
channel.kind === "category" ? (
<div>
<div className="w-full px-0.5 py-1 rounded-md select-none cursor-default text-sm text-foreground/70">
{channel.name}
</div>
<div className="pl-2 pr-1.5 pt-0.5 w-full flex flex-col gap-1">
<RenderChannels channels={channel.channels} />
</div>
</div>
) : (
<div className="w-full hover:bg-accent px-2.5 py-1.5 rounded-md flex gap-2.5 items-center select-none cursor-default text-sm text-foreground/70">
<ChannelIcon kind={channel.kind} />
{channel.name}
</div>
),
);
}
export default function Sidebar({
appRef,
}: {
appRef: React.RefObject<Enclave | null>;
}) {
return (
appRef.current?.server?.meta && (
<div className="h-screen">
<header className="px-3 pt-2.5 pb-2.5 text-lg font-semibold border-b border-b-border">
<h1>{appRef.current.server.meta.name}</h1>
</header>
<section className="px-1.5 pt-3.5 w-full flex flex-col gap-1">
<RenderChannels channels={appRef.current.server.meta.channels} />
</section>
</div>
)
);
}
+53
View File
@@ -0,0 +1,53 @@
import Enclave from "@/app/app";
import { getHTTPUrl, saveServerList } from "@/lib/serverList";
import { AddServerDialog } from "../dialog/AddServerDialog";
export default function ServerList({
appRef,
}: {
appRef: React.RefObject<Enclave | null>;
}) {
if (!appRef.current) return null;
return (
<aside className="bg-card w-16 h-screen p-2 flex flex-col gap-2.5 border-r border-r-border">
{Object.entries(appRef.current.serverList).map(([hostname, server]) => {
return (
<img
src={getHTTPUrl(hostname, server.isSecure, "/icon")}
key={hostname}
className={
hostname === appRef.current?.server?.hostname
? "rounded-lg"
: "rounded-full"
}
onClick={async () => {
if (!appRef.current) {
console.error("AppRef is not initialized yet");
return;
}
appRef.current.connectToServer(hostname, server.isSecure);
}}
/>
);
})}
<AddServerDialog
onAdd={(hostname, isSecure) => {
if (!appRef.current) {
console.error("AppRef is not initialized yet");
return;
}
appRef.current.connectToServer(hostname, isSecure).then(() => {
if (!appRef.current) return;
saveServerList(appRef.current.serverList);
});
}}
/>
</aside>
);
}
+19
View File
@@ -0,0 +1,19 @@
import { invoke } from "@tauri-apps/api/core";
export interface Account {
displayName: string;
privateKey: string;
}
export interface AccountsFile {
activeAccount: number;
accounts: Account[];
}
export async function getAccounts(): Promise<AccountsFile> {
return await invoke("get_accounts");
}
export async function saveAccounts(data: AccountsFile): Promise<void> {
await invoke("save_accounts", { data });
}
+26
View File
@@ -0,0 +1,26 @@
import { ServerMeta } from "@/app/protocol";
import { invoke } from "@tauri-apps/api/core";
export interface KnownServer {
meta: ServerMeta;
publicKey: string;
isSecure: boolean;
}
export type ServerList = Record<string, KnownServer>;
export async function saveServerList(servers: ServerList): Promise<void> {
await invoke("save_server_list", { servers });
}
export async function getServerList(): Promise<ServerList> {
return await invoke("get_server_list");
}
export function getHTTPUrl(hostname: string, isSecure: boolean, path: string) {
return (isSecure ? "https://" : "http://") + hostname + path;
}
export function getWSUrl(hostname: string, isSecure: boolean) {
return (isSecure ? "wss://" : "ws://") + hostname;
}
+6
View File
@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
+134
View File
@@ -0,0 +1,134 @@
@import "tailwindcss";
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@import "@fontsource-variable/geist";
@custom-variant dark (&:is(.dark *));
@theme inline {
--font-heading: var(--font-sans);
--font-sans: "Geist Variable", sans-serif;
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--color-foreground: var(--foreground);
--color-background: var(--background);
--radius-sm: calc(var(--radius) * 0.6);
--radius-md: calc(var(--radius) * 0.8);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) * 1.4);
--radius-2xl: calc(var(--radius) * 1.8);
--radius-3xl: calc(var(--radius) * 2.2);
--radius-4xl: calc(var(--radius) * 2.6);
}
:root {
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
--radius: 0.625rem;
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
html {
@apply bg-background font-sans;
}
}
body {
overflow: hidden;
}
+1
View File
@@ -1,6 +1,7 @@
import React from "react"; import React from "react";
import ReactDOM from "react-dom/client"; import ReactDOM from "react-dom/client";
import App from "./App"; import App from "./App";
import "./main.css";
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode> <React.StrictMode>
+7 -2
View File
@@ -18,8 +18,13 @@
"strict": true, "strict": true,
"noUnusedLocals": true, "noUnusedLocals": true,
"noUnusedParameters": true, "noUnusedParameters": true,
"noFallthroughCasesInSwitch": true "noFallthroughCasesInSwitch": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],
},
}, },
"include": ["src"], "include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }] "references": [{ "path": "./tsconfig.node.json" }],
} }
+9 -2
View File
@@ -1,12 +1,19 @@
import { defineConfig } from "vite"; import { defineConfig } from "vite";
import react from "@vitejs/plugin-react"; import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";
import path from "path";
// @ts-expect-error process is a nodejs global
const host = process.env.TAURI_DEV_HOST; const host = process.env.TAURI_DEV_HOST;
// https://vite.dev/config/ // https://vite.dev/config/
export default defineConfig(async () => ({ export default defineConfig(async () => ({
plugins: [react()], plugins: [react(), tailwindcss()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
// Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build` // Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
// //