2 Commits

Author SHA1 Message Date
602edaae79 Start to build backend base 2025-10-31 18:29:31 +01:00
f7e1d1539f Reset repository content 2025-10-31 17:59:20 +01:00
62 changed files with 4313 additions and 15884 deletions

View File

@@ -1,12 +0,0 @@
---
kind: pipeline
type: docker
name: default
steps:
- name: cargo_check
image: rust
commands:
- rustup component add clippy
- cargo clippy -- -D warnings
- cargo test

View File

@@ -1,35 +0,0 @@
[package]
name = "matrix_gateway"
version = "0.1.0"
edition = "2021"
[dependencies]
log = "0.4.28"
env_logger = "0.11.8"
clap = { version = "4.5.51", features = ["derive", "env"] }
lazy_static = "1.5.0"
anyhow = "1.0.100"
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.143"
rust-s3 = { version = "0.37.0", features = ["tokio"] }
actix-web = "4.11.0"
actix-session = { version = "0.11.0", features = ["redis-session"] }
light-openid = "1.0.4"
thiserror = "2.0.17"
rand = "0.9.2"
rust-embed = "8.8.0"
mime_guess = "2.0.5"
askama = "0.14.0"
urlencoding = "2.1.3"
uuid = { version = "1.18.0", features = ["v4", "serde"] }
ipnet = { version = "2.11.0", features = ["serde"] }
chrono = "0.4.42"
futures-util = { version = "0.3.31", features = ["sink"] }
jwt-simple = { version = "0.12.13", default-features = false, features = ["pure-rust"] }
actix-remote-ip = "0.1.0"
bytes = "1.10.1"
sha2 = "0.11.0-rc.2"
base16ct = { version = "0.3.0", features = ["alloc"] }
ruma = { version = "0.13.0", features = ["client-api-c", "client-ext-client-api", "client-hyper-native-tls", "rand"] }
actix-ws = "0.3.0"
tokio = { version = "1.48.0", features = ["rt", "time", "macros", "rt-multi-thread"] }

View File

@@ -1,14 +0,0 @@
DOCKER_TEMP_DIR=temp
all: gateway
gateway:
cargo clippy -- -D warnings && cargo build --release
gateway_docker: gateway
rm -rf $(DOCKER_TEMP_DIR)
mkdir $(DOCKER_TEMP_DIR)
cp target/release/matrix_gateway $(DOCKER_TEMP_DIR)
docker build -t pierre42100/matrix_gateway -f ./Dockerfile "$(DOCKER_TEMP_DIR)"
rm -rf $(DOCKER_TEMP_DIR)

View File

@@ -6,10 +6,9 @@ Project that expose a simple API to make use of Matrix API. It acts as a Matrix
**Known limitations**:
- Supports only a limited subset of Matrix API
- Does not support E2E encryption
- Does not support spaces
Project written in Rust. Releases are published on Docker Hub.
Project written in Rust and TypeScript. Releases are published on Docker Hub.
## Docker image options
```bash
@@ -17,7 +16,10 @@ docker run --rm -it docker.io/pierre42100/matrix_gateway --help
```
## Setup dev environment
### Dependencies
```
cd matrixgw_backend
mkdir -p storage/maspostgres storage/synapse storage/minio
docker compose up
```
@@ -42,3 +44,15 @@ Auto-created Matrix accounts:
Minio administration credentials: `minioadmin` : `minioadmin`
### Backend
```bash
cd matrixgw_backend
cargo fmt && cargo clippy && cargo run --
```
### Frontend
```bash
cd matrixgw_frontend
npm install
npm run dev
```

12199
assets/bootstrap.css vendored

File diff suppressed because it is too large Load Diff

View File

@@ -1,30 +0,0 @@
/**
* Delete a client referenced by its ID
*
* @param clientID The ID of the client to delete
*/
async function deleteClient(clientID) {
if(!confirm("Do you really want to remove client " + clientID + "? The operation cannot be reverted!"))
return;
try {
const res = await fetch("/", {
method: "POST",
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
"delete_client_id": clientID
}),
});
if(res.status !== 200)
throw new Error(`Invalid status code: ${res.status}`);
alert("The client was successfully deleted!");
location.reload();
} catch (e) {
console.error(`Failed to delete client: ${e}`);
alert("Failed to delete client!");
}
}

View File

@@ -1,12 +0,0 @@
.body-content {
max-width: 900px;
margin: 50px auto;
}
.body-content .card-header {
font-weight: bold;
}
#user_id_container {
margin: 20px auto;
}

View File

@@ -1,68 +0,0 @@
let ws;
const JS_MESSAGE = "JS code";
const IN_MESSAGE = "Incoming";
/**
* Log message
*/
function log(src, txt) {
const target = document.getElementById("ws_log");
const msg = document.createElement("div");
msg.className = "message";
msg.innerHTML = `<div class='type'>${src}</div><div>${txt}</div>`
target.insertBefore(msg, target.firstChild);
}
/**
* Set the state of the WebSocket
*/
function setState(state) {
document.getElementById("state").innerText = state;
}
/**
* Initialize WebSocket connection
*/
function connect() {
disconnect();
log(JS_MESSAGE, "Initialize connection...");
ws = new WebSocket("/api/ws");
setState("Connecting...");
ws.onopen = function () {
log(JS_MESSAGE, "Connected to WebSocket !");
setState("Connected");
}
ws.onmessage = function (event) {
log(IN_MESSAGE, event.data);
}
ws.onclose = function () {
log(JS_MESSAGE, "Disconnected from WebSocket !");
setState("Disconnected");
}
ws.onerror = function (event) {
console.error("WS Error!", event);
log(JS_MESSAGE, `Error with websocket! ${event}`);
setState("Error");
}
}
/**
* Close WebSocket connection
*/
function disconnect() {
if (ws && ws.readyState === WebSocket.OPEN) {
log(JS_MESSAGE, "Close connection...");
ws.close();
}
setState("Disconnected");
ws = undefined;
}
/**
* Clear WS logs
*/
function clearLogs() {
document.getElementById("ws_log").innerHTML = "";
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,16 @@
[package]
name = "matrixgw_backend"
version = "0.1.0"
edition = "2024"
[dependencies]
env_logger = "0.11.8"
log = "0.4.28"
clap = { version = "4.5.51", features = ["derive", "env"] }
lazy_static = "1.5.0"
anyhow = "1.0.100"
serde = { version = "1.0.228", features = ["derive"] }
rust-s3 = { version = "0.37.0", features = ["tokio"] }
tokio = { version = "1.48.0", features = ["full"] }
actix-web = "4.11.0"
actix-session = { version = "0.11.0", features = ["redis-session"] }

View File

@@ -80,17 +80,17 @@ services:
element:
image: docker.io/vectorim/element-web
ports:
- 8080:80/tcp
- "8080:80/tcp"
volumes:
- ./docker/element/config.json:/app/config.json:ro
oidc:
image: dexidp/dex
ports:
- 9001:9001
- "9001:9001"
volumes:
- ./docker/dex:/conf:ro
command: ["dex", "serve", "/conf/dex.config.yaml"]
command: [ "dex", "serve", "/conf/dex.config.yaml" ]
minio:
image: quay.io/minio/minio
@@ -109,7 +109,7 @@ services:
image: redis:alpine
command: redis-server --requirepass ${REDIS_PASS:-secretredis}
ports:
- 6379:6379
- "6379:6379"
volumes:
- ./storage/redis-data:/data
- ./storage/redis-conf:/usr/local/etc/redis/redis.conf

View File

@@ -18,11 +18,11 @@ pub struct AppConfig {
#[clap(short, long, env)]
pub proxy_ip: Option<String>,
/// Secret key, used to sign some resources. Must be randomly generated
/// Secret key, used to secure some resources. Must be randomly generated
#[clap(short = 'S', long, env, default_value = "")]
secret: String,
/// Matrix API origin
/// Matrix homeserver origin
#[clap(short, long, env, default_value = "http://127.0.0.1:8448")]
pub matrix_homeserver: String,

View File

@@ -0,0 +1 @@
pub mod app_config;

View File

@@ -0,0 +1,27 @@
use actix_session::storage::RedisSessionStore;
use actix_web::cookie::Key;
use actix_web::{App, HttpServer};
use matrixgw_backend::app_config::AppConfig;
#[tokio::main]
async fn main() -> std::io::Result<()> {
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
let secret_key = Key::from(AppConfig::get().secret().as_bytes());
let redis_store = RedisSessionStore::new(AppConfig::get().redis_connection_string())
.await
.expect("Failed to connect to Redis!");
log::info!(
"Starting to listen on {} for {}",
AppConfig::get().listen_address,
AppConfig::get().website_origin
);
HttpServer::new(move || App::new())
.workers(4)
.bind(&AppConfig::get().listen_address)?
.run()
.await
}

24
matrixgw_frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

View File

@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs['recommended-latest'],
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

View File

Before

Width:  |  Height:  |  Size: 4.6 KiB

After

Width:  |  Height:  |  Size: 4.6 KiB

View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>matrixgw_frontend</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

3265
matrixgw_frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,33 @@
{
"name": "matrixgw_frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"react": "^19.1.1",
"react-dom": "^19.1.1"
},
"devDependencies": {
"@eslint/js": "^9.36.0",
"@types/node": "^24.6.0",
"@types/react": "^19.1.16",
"@types/react-dom": "^19.1.9",
"@vitejs/plugin-react": "^5.0.4",
"eslint": "^9.36.0",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.22",
"globals": "^16.4.0",
"typescript": "~5.9.3",
"typescript-eslint": "^8.45.0",
"vite": "npm:rolldown-vite@7.1.14"
},
"overrides": {
"vite": "npm:rolldown-vite@7.1.14"
}
}

View File

@@ -0,0 +1 @@
<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>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}

View File

@@ -0,0 +1,35 @@
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'
function App() {
const [count, setCount] = useState(0)
return (
<>
<div>
<a href="https://vite.dev" target="_blank">
<img src={viteLogo} className="logo" alt="Vite logo" />
</a>
<a href="https://react.dev" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
<h1>Vite + React</h1>
<div className="card">
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
<p>
Edit <code>src/App.tsx</code> and save to test HMR
</p>
</div>
<p className="read-the-docs">
Click on the Vite and React logos to learn more
</p>
</>
)
}
export default App

View File

@@ -0,0 +1 @@
<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>

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

@@ -0,0 +1,68 @@
:root {
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}

View File

@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

View File

@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
})

View File

@@ -1,46 +0,0 @@
use crate::sync_client::SyncClientID;
use crate::user::{APIClientID, UserID};
use ruma::api::client::sync::sync_events::v3::{GlobalAccountData, Presence, Rooms, ToDevice};
use ruma::api::client::sync::sync_events::DeviceLists;
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct SyncEvent {
/// Updates to rooms.
#[serde(default, skip_serializing_if = "Rooms::is_empty")]
pub rooms: Rooms,
/// Updates to the presence status of other users.
#[serde(default, skip_serializing_if = "Presence::is_empty")]
pub presence: Presence,
/// The global private data created by this user.
#[serde(default, skip_serializing_if = "GlobalAccountData::is_empty")]
pub account_data: GlobalAccountData,
/// Messages sent directly between devices.
#[serde(default, skip_serializing_if = "ToDevice::is_empty")]
pub to_device: ToDevice,
/// Information on E2E device updates.
///
/// Only present on an incremental sync.
#[serde(default, skip_serializing_if = "DeviceLists::is_empty")]
pub device_lists: DeviceLists,
}
/// Broadcast messages
#[derive(Debug, Clone)]
pub enum BroadcastMessage {
/// Request to close the session of a specific client
CloseClientSession(APIClientID),
/// Close all the sessions of a given user
CloseAllUserSessions(UserID),
/// Stop sync client for a given user
StopSyncTaskForUser(UserID),
/// Start sync client for a given user (if not already running)
StartSyncTaskForUser(UserID),
/// Stop a client with a given client ID
StopSyncClient(SyncClientID),
/// Propagate a new sync event
SyncEvent(UserID, Box<SyncEvent>),
}

View File

@@ -1,18 +0,0 @@
use std::time::Duration;
/// Session key for OpenID login state
pub const STATE_KEY: &str = "oidc-state";
/// Session key for user information
pub const USER_SESSION_KEY: &str = "user";
/// Token length
pub const TOKEN_LEN: usize = 20;
/// How often heartbeat pings are sent.
///
/// Should be half (or less) of the acceptable client timeout.
pub const WS_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
/// How long before lack of client response causes a timeout.
pub const WS_CLIENT_TIMEOUT: Duration = Duration::from_secs(10);

View File

@@ -1,256 +0,0 @@
use crate::constants::USER_SESSION_KEY;
use crate::server::HttpFailure;
use crate::user::{APIClient, APIClientID, RumaClient, User, UserConfig, UserID};
use crate::utils::base_utils::curr_time;
use actix_remote_ip::RemoteIP;
use actix_session::Session;
use actix_web::dev::Payload;
use actix_web::{FromRequest, HttpRequest};
use bytes::Bytes;
use jwt_simple::common::VerificationOptions;
use jwt_simple::prelude::{Duration, HS256Key, MACLike};
use ruma::api::{IncomingResponse, OutgoingRequest};
use sha2::{Digest, Sha256};
use std::net::IpAddr;
use std::str::FromStr;
pub struct APIClientAuth {
pub user: UserConfig,
pub client: Option<APIClient>,
pub payload: Option<Vec<u8>>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenClaims {
#[serde(rename = "met")]
pub method: String,
pub uri: String,
#[serde(rename = "pay", skip_serializing_if = "Option::is_none")]
pub payload_sha256: Option<String>,
}
impl APIClientAuth {
async fn extract_auth(
req: &HttpRequest,
remote_ip: IpAddr,
payload_bytes: Option<Bytes>,
) -> Result<Self, actix_web::Error> {
// Check if user is authenticated using Web UI
let session = Session::from_request(req, &mut Payload::None).await?;
if let Some(user) = session.get::<User>(USER_SESSION_KEY)? {
match UserConfig::load(&user.id, false).await {
Ok(config) => {
return Ok(Self {
user: config,
client: None,
payload: payload_bytes.map(|bytes| bytes.to_vec()),
})
}
Err(e) => {
log::error!("Failed to fetch user information for authentication using cookie token! {e}");
}
};
}
let Some(token) = req.headers().get("x-client-auth") else {
return Err(actix_web::error::ErrorBadRequest(
"Missing authentication header!",
));
};
let Ok(jwt_token) = token.to_str() else {
return Err(actix_web::error::ErrorBadRequest(
"Failed to decode token as string!",
));
};
let metadata = match jwt_simple::token::Token::decode_metadata(jwt_token) {
Ok(m) => m,
Err(e) => {
log::error!("Failed to decode JWT header metadata! {e}");
return Err(actix_web::error::ErrorBadRequest(
"Failed to decode JWT header metadata!",
));
}
};
let Some(kid) = metadata.key_id() else {
return Err(actix_web::error::ErrorBadRequest(
"Missing key id in request!",
));
};
let Some((user_id, client_id)) = kid.split_once("#") else {
return Err(actix_web::error::ErrorBadRequest(
"Invalid key format (missing part)!",
));
};
let (Ok(user_id), Ok(client_id)) =
(urlencoding::decode(user_id), urlencoding::decode(client_id))
else {
return Err(actix_web::error::ErrorBadRequest(
"Invalid key format (decoding failed)!",
));
};
// Fetch user
const USER_NOT_FOUND_ERROR: &str = "User not found!";
let user = match UserConfig::load(&UserID(user_id.to_string()), false).await {
Ok(u) => u,
Err(e) => {
log::error!("Failed to get user information! {e}");
return Err(actix_web::error::ErrorForbidden(USER_NOT_FOUND_ERROR));
}
};
// Find client
let Ok(client_id) = APIClientID::from_str(&client_id) else {
return Err(actix_web::error::ErrorBadRequest("Invalid token format!"));
};
let Some(client) = user.find_client_by_id(&client_id) else {
log::error!("Client not found for user!");
return Err(actix_web::error::ErrorForbidden(USER_NOT_FOUND_ERROR));
};
// Decode JWT
let key = HS256Key::from_bytes(client.secret.as_bytes());
let verif = VerificationOptions {
max_validity: Some(Duration::from_mins(15)),
..Default::default()
};
let claims = match key.verify_token::<TokenClaims>(jwt_token, Some(verif)) {
Ok(t) => t,
Err(e) => {
log::error!("JWT validation failed! {e}");
return Err(actix_web::error::ErrorForbidden("JWT validation failed!"));
}
};
// Check for nonce
if claims.nonce.is_none() {
return Err(actix_web::error::ErrorBadRequest(
"A nonce is required in JWT!",
));
}
// Check IP restriction
if let Some(net) = client.network {
if !net.contains(&remote_ip) {
log::error!(
"Trying to use client {} from unauthorized IP address: {remote_ip}",
client.id.0
);
return Err(actix_web::error::ErrorForbidden(
"This client cannot be used from this IP address!",
));
}
}
// Check URI & verb
if claims.custom.uri != req.uri().to_string() {
return Err(actix_web::error::ErrorBadRequest("URI mismatch!"));
}
if claims.custom.method != req.method().to_string() {
return Err(actix_web::error::ErrorBadRequest("Method mismatch!"));
}
// Check for write access
if client.readonly_client && !req.method().is_safe() {
return Err(actix_web::error::ErrorBadRequest(
"Read only client cannot perform write operations!",
));
}
let payload = match (payload_bytes, claims.custom.payload_sha256) {
(None, _) => None,
(Some(_), None) => {
return Err(actix_web::error::ErrorBadRequest(
"A payload digest must be included in the JWT when the request has a payload!",
));
}
(Some(payload), Some(provided_digest)) => {
let computed_digest = base16ct::lower::encode_string(&Sha256::digest(&payload));
if computed_digest != provided_digest {
log::error!(
"Expected digest {provided_digest} but computed {computed_digest}!"
);
return Err(actix_web::error::ErrorBadRequest(
"Computed digest is different from the one provided in the JWT!",
));
}
Some(payload.to_vec())
}
};
// Update last use (if needed)
if client.need_update_last_used() {
let mut user_up = user.clone();
match user_up.find_client_by_id_mut(&client.id) {
None => log::error!("Client ID disappeared!!!"),
Some(u) => u.used = curr_time().unwrap(),
}
if let Err(e) = user_up.save().await {
log::error!("Failed to update last token usage! {e}");
}
}
Ok(Self {
client: Some(client.clone()),
payload,
user,
})
}
/// Get an instance of Matrix client
pub async fn client(&self) -> anyhow::Result<RumaClient> {
self.user.matrix_client().await
}
/// Send request to matrix server
pub async fn send_request<R: OutgoingRequest<IncomingResponse = E>, E: IncomingResponse>(
&self,
request: R,
) -> anyhow::Result<E, HttpFailure> {
match self.client().await?.send_request(request).await {
Ok(e) => Ok(e),
Err(e) => Err(HttpFailure::MatrixClientError(e.to_string())),
}
}
}
impl FromRequest for APIClientAuth {
type Error = actix_web::Error;
type Future = futures_util::future::LocalBoxFuture<'static, Result<Self, Self::Error>>;
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
let req = req.clone();
let remote_ip = match RemoteIP::from_request(&req, &mut Payload::None).into_inner() {
Ok(ip) => ip,
Err(e) => return Box::pin(async { Err(e) }),
};
let mut payload = payload.take();
Box::pin(async move {
let payload_bytes = match Bytes::from_request(&req, &mut payload).await {
Ok(b) => {
if b.is_empty() {
None
} else {
Some(b)
}
}
Err(e) => {
log::error!("Failed to extract request payload! {e}");
None
}
};
Self::extract_auth(&req, remote_ip.0, payload_bytes).await
})
}
}

View File

@@ -1 +0,0 @@
pub mod client_auth;

View File

@@ -1,8 +0,0 @@
pub mod app_config;
pub mod broadcast_messages;
pub mod constants;
pub mod extractors;
pub mod server;
pub mod sync_client;
pub mod user;
pub mod utils;

View File

@@ -1,80 +0,0 @@
use actix_remote_ip::RemoteIPConfig;
use actix_session::config::SessionLifecycle;
use actix_session::{storage::RedisSessionStore, SessionMiddleware};
use actix_web::cookie::Key;
use actix_web::{web, App, HttpServer};
use matrix_gateway::app_config::AppConfig;
use matrix_gateway::broadcast_messages::BroadcastMessage;
use matrix_gateway::server::{api, web_ui};
use matrix_gateway::sync_client;
use matrix_gateway::user::UserConfig;
#[tokio::main]
async fn main() -> std::io::Result<()> {
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
UserConfig::create_bucket_if_required()
.await
.expect("Failed to create bucket!");
let secret_key = Key::from(AppConfig::get().secret().as_bytes());
let redis_store = RedisSessionStore::new(AppConfig::get().redis_connection_string())
.await
.expect("Failed to connect to Redis!");
let (ws_tx, _) = tokio::sync::broadcast::channel::<BroadcastMessage>(16);
// Launch sync manager
tokio::spawn(sync_client::sync_client_manager(ws_tx.clone()));
log::info!(
"Starting to listen on {} for {}",
AppConfig::get().listen_address,
AppConfig::get().website_origin
);
HttpServer::new(move || {
App::new()
// Add session management to your application using Redis for session state storage
.wrap(
SessionMiddleware::builder(redis_store.clone(), secret_key.clone())
.cookie_name("matrixgw-session".to_string())
.session_lifecycle(SessionLifecycle::BrowserSession(Default::default()))
.build(),
)
.app_data(web::Data::new(RemoteIPConfig {
proxy: AppConfig::get().proxy_ip.clone(),
}))
.app_data(web::Data::new(ws_tx.clone()))
// Web configuration routes
.route("/assets/{tail:.*}", web::get().to(web_ui::static_file))
.route("/", web::get().to(web_ui::home))
.route("/", web::post().to(web_ui::home))
.route("/oidc_cb", web::get().to(web_ui::oidc_cb))
.route("/sign_out", web::get().to(web_ui::sign_out))
.route("/ws_debug", web::get().to(web_ui::ws_debug))
// API routes
.route("/api", web::get().to(api::api_home))
.route("/api", web::post().to(api::api_home))
.route("/api/account/whoami", web::get().to(api::account::who_am_i))
.route("/api/room/joined", web::get().to(api::room::joined_rooms))
.route("/api/room/{room_id}", web::get().to(api::room::info))
.route(
"/api/media/{server_name}/{media_id}/download",
web::get().to(api::media::download),
)
.route(
"/api/media/{server_name}/{media_id}/thumbnail",
web::get().to(api::media::thumbnail),
)
.route(
"/api/profile/{user_id}",
web::get().to(api::profile::get_profile),
)
.service(web::resource("/api/ws").route(web::get().to(api::ws::ws)))
})
.workers(4)
.bind(&AppConfig::get().listen_address)?
.run()
.await
}

View File

@@ -1,23 +0,0 @@
use crate::extractors::client_auth::APIClientAuth;
use crate::server::HttpResult;
use actix_web::HttpResponse;
use ruma::api::client::account;
use ruma::DeviceId;
#[derive(serde::Serialize)]
struct WhoAmIResponse {
user_id: String,
device_id: Option<String>,
}
/// Get current user identity
pub async fn who_am_i(auth: APIClientAuth) -> HttpResult {
let res = auth
.send_request(account::whoami::v3::Request::default())
.await?;
Ok(HttpResponse::Ok().json(WhoAmIResponse {
user_id: res.user_id.to_string(),
device_id: res.device_id.as_deref().map(DeviceId::to_string),
}))
}

View File

@@ -1,59 +0,0 @@
use crate::extractors::client_auth::APIClientAuth;
use crate::server::HttpResult;
use actix_web::{web, HttpResponse};
use ruma::api::client::media;
use ruma::{OwnedServerName, UInt};
#[derive(serde::Deserialize)]
pub struct MediaInfoInPath {
server_name: OwnedServerName,
media_id: String,
}
/// Download a media
#[allow(deprecated)]
pub async fn download(auth: APIClientAuth, path: web::Path<MediaInfoInPath>) -> HttpResult {
let res = auth
.send_request(media::get_content::v3::Request::new(
path.media_id.clone(),
path.server_name.clone(),
))
.await?;
let mut http_res = HttpResponse::Ok();
if let Some(content_type) = res.content_type {
http_res.content_type(content_type);
}
Ok(http_res.body(res.file))
}
#[derive(serde::Deserialize)]
pub struct MediaThumbnailQuery {
width: Option<UInt>,
height: Option<UInt>,
}
/// Get a media thumbnail
#[allow(deprecated)]
pub async fn thumbnail(
auth: APIClientAuth,
path: web::Path<MediaInfoInPath>,
query: web::Query<MediaThumbnailQuery>,
) -> HttpResult {
let res = auth
.send_request(media::get_content_thumbnail::v3::Request::new(
path.media_id.clone(),
path.server_name.clone(),
query.width.unwrap_or(UInt::new(500).unwrap()),
query.height.unwrap_or(UInt::new(500).unwrap()),
))
.await?;
let mut http_res = HttpResponse::Ok();
if let Some(content_type) = res.content_type {
http_res.content_type(content_type);
}
Ok(http_res.body(res.file))
}

View File

@@ -1,14 +0,0 @@
use crate::extractors::client_auth::APIClientAuth;
use crate::server::HttpResult;
use actix_web::HttpResponse;
pub mod account;
pub mod media;
pub mod profile;
pub mod room;
pub mod ws;
/// API Home route
pub async fn api_home(auth: APIClientAuth) -> HttpResult {
Ok(HttpResponse::Ok().body(format!("Welcome user {}!", auth.user.user_id.0)))
}

View File

@@ -1,29 +0,0 @@
use crate::extractors::client_auth::APIClientAuth;
use crate::server::HttpResult;
use crate::utils::matrix_utils::ApiMxcURI;
use actix_web::{web, HttpResponse};
use ruma::api::client::profile;
use ruma::OwnedUserId;
#[derive(serde::Deserialize)]
pub struct UserIDInPath {
user_id: OwnedUserId,
}
#[derive(serde::Serialize)]
struct ProfileResponse {
display_name: Option<String>,
avatar: Option<ApiMxcURI>,
}
/// Get user profile
pub async fn get_profile(auth: APIClientAuth, path: web::Path<UserIDInPath>) -> HttpResult {
let res = auth
.send_request(profile::get_profile::v3::Request::new(path.user_id.clone()))
.await?;
Ok(HttpResponse::Ok().json(ProfileResponse {
display_name: res.displayname,
avatar: res.avatar_url.map(ApiMxcURI),
}))
}

View File

@@ -1,81 +0,0 @@
use crate::extractors::client_auth::APIClientAuth;
use crate::server::{HttpFailure, HttpResult};
use crate::utils::matrix_utils::ApiMxcURI;
use actix_web::{web, HttpResponse};
use ruma::api::client::{membership, state};
use ruma::events::StateEventType;
use ruma::{OwnedMxcUri, OwnedRoomId};
use serde::de::DeserializeOwned;
#[derive(serde::Serialize)]
struct GetRoomsMembershipsResponse {
rooms: Vec<OwnedRoomId>,
}
/// Get the list of rooms the user has joined
pub async fn joined_rooms(auth: APIClientAuth) -> HttpResult {
let res = auth
.send_request(membership::joined_rooms::v3::Request::default())
.await?;
Ok(HttpResponse::Ok().json(GetRoomsMembershipsResponse {
rooms: res.joined_rooms,
}))
}
#[derive(serde::Deserialize)]
pub struct RoomIDInPath {
room_id: OwnedRoomId,
}
#[derive(serde::Serialize)]
struct GetRoomInfoResponse {
name: Option<String>,
avatar: Option<ApiMxcURI>,
}
/// Get a room information
async fn get_room_info<E: DeserializeOwned>(
auth: &APIClientAuth,
room_id: OwnedRoomId,
event_type: StateEventType,
field: &str,
) -> anyhow::Result<Option<E>, HttpFailure> {
let res = auth
.send_request(state::get_state_events_for_key::v3::Request::new(
room_id,
event_type,
String::default(),
))
.await?;
Ok(res.content.get_field(field)?)
}
/// Get room information
pub async fn info(auth: APIClientAuth, path: web::Path<RoomIDInPath>) -> HttpResult {
let room_name: Option<String> = get_room_info(
&auth,
path.room_id.clone(),
StateEventType::RoomName,
"name",
)
.await
.ok()
.flatten();
let room_avatar: Option<OwnedMxcUri> = get_room_info(
&auth,
path.room_id.clone(),
StateEventType::RoomAvatar,
"url",
)
.await
.ok()
.flatten();
Ok(HttpResponse::Ok().json(GetRoomInfoResponse {
name: room_name,
avatar: room_avatar.map(ApiMxcURI),
}))
}

View File

@@ -1,176 +0,0 @@
use crate::broadcast_messages::{BroadcastMessage, SyncEvent};
use crate::constants::{WS_CLIENT_TIMEOUT, WS_HEARTBEAT_INTERVAL};
use crate::extractors::client_auth::APIClientAuth;
use crate::server::HttpResult;
use actix_web::dev::Payload;
use actix_web::{web, FromRequest, HttpRequest};
use actix_ws::Message;
use futures_util::StreamExt;
use std::time::Instant;
use tokio::select;
use tokio::sync::broadcast;
use tokio::sync::broadcast::Receiver;
use tokio::time::interval;
/// Messages send to the client
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(tag = "type")]
pub enum WsMessage {
Sync(SyncEvent),
}
/// Main WS route
pub async fn ws(
req: HttpRequest,
stream: web::Payload,
tx: web::Data<broadcast::Sender<BroadcastMessage>>,
) -> HttpResult {
// Forcefully ignore request payload by manually extracting authentication information
let auth = APIClientAuth::from_request(&req, &mut Payload::None).await?;
let (res, session, msg_stream) = actix_ws::handle(&req, stream)?;
// Ask for sync client to be started
if let Err(e) = tx.send(BroadcastMessage::StartSyncTaskForUser(
auth.user.user_id.clone(),
)) {
log::error!("Failed to send StartSyncTaskForUser: {e}");
}
let rx = tx.subscribe();
// spawn websocket handler (and don't await it) so that the response is returned immediately
actix_web::rt::spawn(ws_handler(session, msg_stream, auth, rx));
Ok(res)
}
pub async fn ws_handler(
mut session: actix_ws::Session,
mut msg_stream: actix_ws::MessageStream,
auth: APIClientAuth,
mut rx: Receiver<BroadcastMessage>,
) {
log::info!("WS connected");
let mut last_heartbeat = Instant::now();
let mut interval = interval(WS_HEARTBEAT_INTERVAL);
let reason = loop {
// waits for either `msg_stream` to receive a message from the client, the broadcast channel
// to send a message, or the heartbeat interval timer to tick, yielding the value of
// whichever one is ready first
select! {
ws_msg = rx.recv() => {
let msg = match ws_msg {
Ok(msg) => msg,
Err(broadcast::error::RecvError::Closed) => break None,
Err(broadcast::error::RecvError::Lagged(_)) => continue,
};
match msg {
BroadcastMessage::CloseClientSession(id) => {
if let Some(client) = &auth.client {
if client.id == id {
log::info!(
"closing client session {id:?} of user {:?} as requested", auth.user.user_id
);
break None;
}
}
},
BroadcastMessage::CloseAllUserSessions(userid) => {
if userid == auth.user.user_id {
log::info!(
"closing WS session of user {userid:?} as requested"
);
break None;
}
}
BroadcastMessage::SyncEvent(userid, event) => {
if userid != auth.user.user_id {
continue;
}
// Send the message to the websocket
if let Ok(msg) = serde_json::to_string(&WsMessage::Sync(*event)) {
if let Err(e) = session.text(msg).await {
log::error!("Failed to send SyncEvent: {e}");
}
}
}
_ => {}};
}
// heartbeat interval ticked
_tick = interval.tick() => {
// if no heartbeat ping/pong received recently, close the connection
if Instant::now().duration_since(last_heartbeat) > WS_CLIENT_TIMEOUT {
log::info!(
"client has not sent heartbeat in over {WS_CLIENT_TIMEOUT:?}; disconnecting"
);
break None;
}
// send heartbeat ping
let _ = session.ping(b"").await;
},
msg = msg_stream.next() => {
let msg = match msg {
// received message from WebSocket client
Some(Ok(msg)) => msg,
// client WebSocket stream error
Some(Err(err)) => {
log::error!("{err}");
break None;
}
// client WebSocket stream ended
None => break None
};
log::debug!("msg: {msg:?}");
match msg {
Message::Text(s) => {
log::info!("Text message: {s}");
}
Message::Binary(_) => {
// drop client's binary messages
}
Message::Close(reason) => {
break reason;
}
Message::Ping(bytes) => {
last_heartbeat = Instant::now();
let _ = session.pong(&bytes).await;
}
Message::Pong(_) => {
last_heartbeat = Instant::now();
}
Message::Continuation(_) => {
log::warn!("no support for continuation frames");
}
// no-op; ignore
Message::Nop => {}
};
}
}
};
// attempt to close connection gracefully
let _ = session.close(reason).await;
log::info!("WS disconnected");
}

View File

@@ -1,49 +0,0 @@
use actix_web::http::StatusCode;
use actix_web::{HttpResponse, ResponseError};
use std::error::Error;
use std::fmt::Debug;
pub mod api;
pub mod web_ui;
#[derive(thiserror::Error, Debug)]
pub enum HttpFailure {
#[error("this resource requires higher privileges")]
Forbidden,
#[error("this resource was not found")]
NotFound,
#[error("Actix web error")]
ActixError(#[from] actix_web::Error),
#[error("an unhandled session insert error occurred")]
SessionInsertError(#[from] actix_session::SessionInsertError),
#[error("an unhandled session error occurred")]
SessionError(#[from] actix_session::SessionGetError),
#[error("an unspecified open id error occurred: {0}")]
OpenID(Box<dyn Error>),
#[error("an error occurred while fetching user configuration: {0}")]
FetchUserConfig(anyhow::Error),
#[error("an unspecified internal error occurred: {0}")]
InternalError(#[from] anyhow::Error),
#[error("a matrix api client error occurred: {0}")]
MatrixApiClientError(#[from] ruma::api::client::Error),
#[error("a matrix client error occurred: {0}")]
MatrixClientError(String),
#[error("a serde_json error occurred: {0}")]
SerdeJsonError(#[from] serde_json::error::Error),
}
impl ResponseError for HttpFailure {
fn status_code(&self) -> StatusCode {
match &self {
Self::Forbidden => StatusCode::FORBIDDEN,
Self::NotFound => StatusCode::NOT_FOUND,
_ => StatusCode::INTERNAL_SERVER_ERROR,
}
}
fn error_response(&self) -> HttpResponse {
HttpResponse::build(self.status_code()).body(self.to_string())
}
}
pub type HttpResult = Result<HttpResponse, HttpFailure>;

View File

@@ -1,252 +0,0 @@
use crate::app_config::AppConfig;
use crate::broadcast_messages::BroadcastMessage;
use crate::constants::{STATE_KEY, USER_SESSION_KEY};
use crate::server::{HttpFailure, HttpResult};
use crate::user::{APIClient, APIClientID, User, UserConfig, UserID};
use crate::utils::base_utils;
use actix_session::Session;
use actix_web::{web, HttpResponse};
use askama::Template;
use ipnet::IpNet;
use light_openid::primitives::OpenIDConfig;
use std::str::FromStr;
use tokio::sync::broadcast;
/// Static assets
#[derive(rust_embed::Embed)]
#[folder = "assets/"]
struct Assets;
/// Serve static file
pub async fn static_file(path: web::Path<String>) -> HttpResult {
match Assets::get(path.as_ref()) {
Some(content) => Ok(HttpResponse::Ok()
.content_type(
mime_guess::from_path(path.as_str())
.first_or_octet_stream()
.as_ref(),
)
.body(content.data.into_owned())),
None => Ok(HttpResponse::NotFound().body("404 Not Found")),
}
}
#[derive(askama::Template)]
#[template(path = "index.html")]
struct HomeTemplate {
name: String,
user_id: UserID,
matrix_token: String,
clients: Vec<APIClient>,
success_message: Option<String>,
error_message: Option<String>,
}
/// HTTP form request
#[derive(serde::Deserialize)]
pub struct FormRequest {
/// Update matrix token
new_matrix_token: Option<String>,
/// Create a new client
new_client_desc: Option<String>,
/// Restrict new client to a given network
ip_network: Option<String>,
/// Grant read only access to client
readonly_client: Option<String>,
/// Delete a specified client id
delete_client_id: Option<APIClientID>,
}
/// Main route
pub async fn home(
session: Session,
form_req: Option<web::Form<FormRequest>>,
tx: web::Data<broadcast::Sender<BroadcastMessage>>,
) -> HttpResult {
// Get user information, requesting authentication if information is missing
let Some(user): Option<User> = session.get(USER_SESSION_KEY)? else {
// Generate auth state
let state = base_utils::rand_str(50);
session.insert(STATE_KEY, &state)?;
let oidc = AppConfig::get().openid_provider();
let config = OpenIDConfig::load_from_url(oidc.configuration_url)
.await
.map_err(HttpFailure::OpenID)?;
let auth_url = config.gen_authorization_url(oidc.client_id, &state, &oidc.redirect_url);
return Ok(HttpResponse::Found()
.append_header(("location", auth_url))
.finish());
};
let mut success_message = None;
let mut error_message = None;
// Retrieve user configuration
let mut config = UserConfig::load(&user.id, true)
.await
.map_err(HttpFailure::FetchUserConfig)?;
if let Some(form_req) = form_req {
// Update matrix token, if requested
if let Some(t) = form_req.0.new_matrix_token {
if t.len() < 3 {
error_message = Some("Specified Matrix token is too short!".to_string());
} else {
config.matrix_token = t;
config.save().await?;
success_message = Some("Matrix token was successfully updated!".to_string());
// Close sync task
if let Err(e) = tx.send(BroadcastMessage::StopSyncTaskForUser(user.id.clone())) {
log::error!("Failed to send StopSyncClientForUser: {e}");
}
// Invalidate all Ws connections
if let Err(e) = tx.send(BroadcastMessage::CloseAllUserSessions(user.id.clone())) {
log::error!("Failed to send CloseAllUserSessions: {e}");
}
}
}
// Create a new client, if requested
if let Some(new_token_desc) = form_req.0.new_client_desc {
let ip_net = match form_req.0.ip_network.as_deref() {
None | Some("") => None,
Some(e) => match IpNet::from_str(e) {
Ok(n) => Some(n),
Err(e) => {
log::error!("Failed to parse IP network provided by user: {e}");
error_message = Some(format!("Failed to parse restricted IP network: {e}"));
None
}
},
};
if error_message.is_none() {
let mut token = APIClient::generate(new_token_desc, ip_net);
token.readonly_client = form_req.0.readonly_client.is_some();
success_message = Some(format!("The secret of your new token is '{}'. Be sure to write it somewhere as you will not be able to recover it later!", token.secret));
config.clients.push(token);
config.save().await?;
}
}
// Delete a client
if let Some(delete_client_id) = form_req.0.delete_client_id {
config.clients.retain(|c| c.id != delete_client_id);
config.save().await?;
success_message = Some("The client was successfully deleted!".to_string());
if let Err(e) = tx.send(BroadcastMessage::CloseClientSession(delete_client_id)) {
log::error!("Failed to send CloseClientSession: {e}");
}
}
}
// Render page
Ok(HttpResponse::Ok()
.insert_header(("content-type", "text/html"))
.body(
HomeTemplate {
name: user.name,
user_id: user.id,
matrix_token: config.obfuscated_matrix_token(),
clients: config.clients,
success_message,
error_message,
}
.render()
.unwrap(),
))
}
#[derive(serde::Deserialize)]
pub struct AuthCallbackQuery {
code: String,
state: String,
}
/// Authenticate user callback
pub async fn oidc_cb(session: Session, query: web::Query<AuthCallbackQuery>) -> HttpResult {
if session.get(STATE_KEY)? != Some(query.state.to_string()) {
return Ok(HttpResponse::BadRequest()
.append_header(("content-type", "text/html"))
.body("State mismatch! <a href='/'>Try again</a>"));
}
let oidc = AppConfig::get().openid_provider();
let config = OpenIDConfig::load_from_url(oidc.configuration_url)
.await
.map_err(HttpFailure::OpenID)?;
let (token, _) = match config
.request_token(
oidc.client_id,
oidc.client_secret,
&query.code,
&oidc.redirect_url,
)
.await
{
Ok(t) => t,
Err(e) => {
log::error!("Failed to request user token! {e}");
return Ok(HttpResponse::BadRequest()
.append_header(("content-type", "text/html"))
.body("Authentication failed! <a href='/'>Try again</a>"));
}
};
let (user, _) = config
.request_user_info(&token)
.await
.map_err(HttpFailure::OpenID)?;
let user = User {
id: UserID(user.sub),
name: user.name.unwrap_or("no_name".to_string()),
email: user.email.unwrap_or("no@mail.com".to_string()),
};
log::info!("Successful authentication as {user:?}");
session.insert(USER_SESSION_KEY, user)?;
Ok(HttpResponse::Found()
.insert_header(("location", "/"))
.finish())
}
/// De-authenticate user
pub async fn sign_out(session: Session) -> HttpResult {
session.remove(USER_SESSION_KEY);
Ok(HttpResponse::Found()
.insert_header(("location", "/"))
.finish())
}
#[derive(askama::Template)]
#[template(path = "ws_debug.html")]
struct WsDebugTemplate {
name: String,
}
/// WebSocket debug
pub async fn ws_debug(session: Session) -> HttpResult {
let Some(user): Option<User> = session.get(USER_SESSION_KEY)? else {
return Ok(HttpResponse::Found()
.insert_header(("location", "/"))
.finish());
};
Ok(HttpResponse::Ok()
.content_type("text/html")
.body(WsDebugTemplate { name: user.name }.render().unwrap()))
}

View File

@@ -1,145 +0,0 @@
use crate::broadcast_messages::{BroadcastMessage, SyncEvent};
use crate::user::{UserConfig, UserID};
use futures_util::TryStreamExt;
use ruma::api::client::sync::sync_events;
use ruma::assign;
use ruma::presence::PresenceState;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::broadcast;
/// ID of sync client
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct SyncClientID(uuid::Uuid);
/// Sync client launcher loop
pub async fn sync_client_manager(tx: broadcast::Sender<BroadcastMessage>) -> ! {
let mut rx = tx.subscribe();
let tx = Arc::new(tx.clone());
let mut running_tasks = HashMap::new();
while let Ok(msg) = rx.recv().await {
match msg {
BroadcastMessage::StartSyncTaskForUser(user_id) => {
if running_tasks.contains_key(&user_id) {
log::info!("Won't start sync task for user {user_id:?} because a task is already running for this user!");
continue;
}
log::info!("Start sync task for user {user_id:?}");
let task_id = SyncClientID(uuid::Uuid::new_v4());
running_tasks.insert(user_id.clone(), task_id.clone());
let tx = tx.clone();
tokio::task::spawn(async move {
sync_task(task_id, user_id, tx).await;
});
}
BroadcastMessage::StopSyncTaskForUser(user_id) => {
// Check if a task is running for this user
if let Some(task_id) = running_tasks.remove(&user_id) {
log::info!("Stop sync task for user {user_id:?}");
tx.send(BroadcastMessage::StopSyncClient(task_id)).unwrap();
} else {
log::info!("Not stopping sync task for user {user_id:?}: not running");
}
}
_ => {}
}
}
panic!("Sync client manager stopped unexpectedly!");
}
/// Sync task for a single user
async fn sync_task(
id: SyncClientID,
user_id: UserID,
tx: Arc<broadcast::Sender<BroadcastMessage>>,
) {
let mut rx = tx.subscribe();
let Ok(user_config) = UserConfig::load(&user_id, false).await else {
log::error!("Failed to load user config in sync thread!");
return;
};
let client = match user_config.matrix_client().await {
Err(e) => {
log::error!("Failed to load matrix client for user {user_id:?}: {e}");
return;
}
Ok(client) => client,
};
let initial_sync_response = match client
.send_request(assign!(sync_events::v3::Request::new(), {
filter: None,
}))
.await
{
Ok(res) => res,
Err(e) => {
log::error!("Failed to perform initial sync request for user {user_id:?}! {e}");
return;
}
};
let mut sync_stream = Box::pin(client.sync(
None,
initial_sync_response.next_batch,
PresenceState::Offline,
Some(Duration::from_secs(30)),
));
loop {
tokio::select! {
// Message from tokio broadcast
msg = rx.recv() => {
match msg {
Ok(BroadcastMessage::StopSyncClient(client_id)) => {
if client_id == id {
log::info!("A request was received to stop this client! {id:?} for user {user_id:?}");
break;
}
}
Err(e) => {
log::error!("Failed to receive a message from broadcast! {e}");
return;
}
Ok(_) => {}
}
}
// Message from Matrix
msg_stream = sync_stream.try_next() => {
match msg_stream {
Ok(Some(msg)) => {
log::debug!("Received new message from Matrix: {msg:#?}");
if let Err(e) = tx.send(BroadcastMessage::SyncEvent(user_id.clone(), Box::new(SyncEvent {
rooms: msg.rooms,presence: msg.presence,
account_data: msg.account_data,
to_device: msg.to_device,
device_lists: msg.device_lists,
}))) {
log::error!("Failed to propagate event! {e}");
}
}
Ok(None) => {
log::debug!("Received no message from Matrix");
}
Err(e) => {
log::error!("Failed to receive a message from Matrix! {e}");
return;
}
}
}
}
}
}

View File

@@ -1,241 +0,0 @@
use s3::error::S3Error;
use s3::request::ResponseData;
use s3::{Bucket, BucketConfiguration};
use std::str::FromStr;
use thiserror::Error;
use crate::app_config::AppConfig;
use crate::constants::TOKEN_LEN;
use crate::utils::base_utils::{curr_time, format_time, rand_str};
type HttpClient = ruma::client::http_client::HyperNativeTls;
pub type RumaClient = ruma::Client<HttpClient>;
#[derive(Error, Debug)]
pub enum UserError {
#[error("failed to fetch user configuration: {0}")]
FetchUserConfig(S3Error),
#[error("missing matrix token")]
MissingMatrixToken,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, Hash)]
pub struct UserID(pub String);
impl UserID {
fn conf_path_in_bucket(&self) -> String {
format!("confs/{}.json", urlencoding::encode(&self.0))
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct User {
pub id: UserID,
pub name: String,
pub email: String,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct APIClientID(pub uuid::Uuid);
impl APIClientID {
pub fn generate() -> Self {
Self(uuid::Uuid::new_v4())
}
}
impl FromStr for APIClientID {
type Err = uuid::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(uuid::Uuid::from_str(s)?))
}
}
/// Single API client information
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct APIClient {
/// Client unique ID
pub id: APIClientID,
/// Client description
pub description: String,
/// Restricted API network for token
pub network: Option<ipnet::IpNet>,
/// Client secret
pub secret: String,
/// Client creation time
pub created: u64,
/// Client last usage time
pub used: u64,
/// Read only access
pub readonly_client: bool,
}
impl APIClient {
pub fn fmt_created(&self) -> String {
format_time(self.created).unwrap_or_default()
}
pub fn fmt_used(&self) -> String {
format_time(self.used).unwrap_or_default()
}
pub fn need_update_last_used(&self) -> bool {
self.used + 60 * 15 < curr_time().unwrap()
}
}
impl APIClient {
/// Generate a new API client
pub fn generate(description: String, network: Option<ipnet::IpNet>) -> Self {
Self {
id: APIClientID::generate(),
description,
network,
secret: rand_str(TOKEN_LEN),
created: curr_time().unwrap(),
used: curr_time().unwrap(),
readonly_client: true,
}
}
}
#[derive(serde::Serialize, serde::Deserialize, Clone)]
pub struct UserConfig {
/// Target user ID
pub user_id: UserID,
/// Configuration creation time
pub created: u64,
/// Configuration last update time
pub updated: u64,
/// Current user matrix token
pub matrix_token: String,
/// API clients
pub clients: Vec<APIClient>,
}
impl UserConfig {
/// Create S3 bucket if required
pub async fn create_bucket_if_required() -> anyhow::Result<()> {
if AppConfig::get().s3_skip_auto_create_bucket {
log::debug!("Skipping bucket existence check");
return Ok(());
}
let bucket = AppConfig::get().s3_bucket()?;
match bucket.location().await {
Ok(_) => {
log::debug!("The bucket already exists.");
return Ok(());
}
Err(S3Error::HttpFailWithBody(404, s)) if s.contains("<Code>NoSuchKey</Code>") => {
log::warn!("Failed to fetch bucket location, but it seems that bucket exists.");
return Ok(());
}
Err(S3Error::HttpFailWithBody(404, s)) if s.contains("<Code>NoSuchBucket</Code>") => {
log::warn!("The bucket does not seem to exists, trying to create it!")
}
Err(e) => {
log::error!("Got unexpected error when querying bucket info: {e}");
return Err(e.into());
}
}
Bucket::create_with_path_style(
&bucket.name,
bucket.region,
AppConfig::get().s3_credentials()?,
BucketConfiguration::private(),
)
.await?;
Ok(())
}
/// Get current user configuration
pub async fn load(user_id: &UserID, allow_non_existing: bool) -> anyhow::Result<Self> {
let res: Result<ResponseData, S3Error> = AppConfig::get()
.s3_bucket()?
.get_object(user_id.conf_path_in_bucket())
.await;
match (res, allow_non_existing) {
(Ok(res), _) => Ok(serde_json::from_slice(res.as_slice())?),
(Err(S3Error::HttpFailWithBody(404, _)), true) => {
log::warn!("User configuration does not exists, generating a new one...");
Ok(Self {
user_id: user_id.clone(),
created: curr_time()?,
updated: curr_time()?,
matrix_token: "".to_string(),
clients: vec![],
})
}
(Err(e), _) => Err(UserError::FetchUserConfig(e).into()),
}
}
/// Set user configuration
pub async fn save(&mut self) -> anyhow::Result<()> {
log::info!("Saving new configuration for user {:?}", self.user_id);
self.updated = curr_time()?;
// Save updated configuration
AppConfig::get()
.s3_bucket()?
.put_object(
self.user_id.conf_path_in_bucket(),
&serde_json::to_vec(self)?,
)
.await?;
Ok(())
}
/// Get current user matrix token, in an obfuscated form
pub fn obfuscated_matrix_token(&self) -> String {
self.matrix_token
.chars()
.enumerate()
.map(|(num, c)| match num {
0 | 1 => c,
_ => 'X',
})
.collect()
}
/// Find a client by its id
pub fn find_client_by_id(&self, id: &APIClientID) -> Option<&APIClient> {
self.clients.iter().find(|c| &c.id == id)
}
/// Find a client by its id and get a mutable reference
pub fn find_client_by_id_mut(&mut self, id: &APIClientID) -> Option<&mut APIClient> {
self.clients.iter_mut().find(|c| &c.id == id)
}
/// Get a matrix client instance for the current user
pub async fn matrix_client(&self) -> anyhow::Result<RumaClient> {
if self.matrix_token.is_empty() {
return Err(UserError::MissingMatrixToken.into());
}
Ok(ruma::Client::builder()
.homeserver_url(AppConfig::get().matrix_homeserver.to_string())
.access_token(Some(self.matrix_token.clone()))
.build()
.await?)
}
}

View File

@@ -1,20 +0,0 @@
use rand::distr::{Alphanumeric, SampleString};
use std::time::{SystemTime, UNIX_EPOCH};
/// Generate a random string of a given size
pub fn rand_str(len: usize) -> String {
Alphanumeric.sample_string(&mut rand::rng(), len)
}
/// Get current time
pub fn curr_time() -> anyhow::Result<u64> {
Ok(SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|t| t.as_secs())?)
}
/// Format time
pub fn format_time(time: u64) -> Option<String> {
let time = chrono::DateTime::from_timestamp(time as i64, 0)?;
Some(time.naive_local().to_string())
}

View File

@@ -1,18 +0,0 @@
use ruma::OwnedMxcUri;
use serde::ser::SerializeMap;
use serde::{Serialize, Serializer};
pub struct ApiMxcURI(pub OwnedMxcUri);
impl Serialize for ApiMxcURI {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut map = serializer.serialize_map(Some(3))?;
map.serialize_entry("uri", &self.0)?;
map.serialize_entry("server_name", &self.0.server_name().ok())?;
map.serialize_entry("media_id", &self.0.media_id().ok())?;
map.end()
}
}

View File

@@ -1,2 +0,0 @@
pub mod base_utils;
pub mod matrix_utils;

View File

@@ -1,46 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Matrix GW</title>
<link rel="icon" type="image/png" href="/assets/favicon.png"/>
<link rel="stylesheet" href="/assets/bootstrap.css"/>
<link rel="stylesheet" href="/assets/style.css"/>
</head>
<body>
<!-- Header -->
<header data-bs-theme="dark">
<div class="navbar navbar-dark bg-dark shadow-sm">
<div class="container">
<a href="/" class="navbar-brand d-flex align-items-center">
<svg xxmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="none" stroke="currentColor"
stroke-linecap="round" stroke-linejoin="round" stroke-width="1" aria-hidden="true" class="me-2"
viewBox="0 0 24 24">
<path d="M10 11.5H17V13H10V11.5M10 8.5H19V10H10V8.5M20 5H9C7.9 5 7 5.9 7 7V21L11 17H20C21.1 17 22 16.1 22 15V7C22 5.9 21.1 5 20 5M20 15H10.2L9 16.2V7H20V15M3 7C2.4 7 2 7.4 2 8S2.4 9 3 9H5V7H3M2 11C1.4 11 1 11.4 1 12S1.4 13 2 13H5V11H2M1 15C.4 15 0 15.4 0 16C0 16.6 .4 17 1 17H5V15H1Z"/>
</svg>
<strong>Matrix GW</strong>
</a>
<ul class="navbar-nav mr-auto" style="flex: 1">
<li class="nav-item"><a href="/ws_debug" class="nav-link">WS Debug</a></li>
</ul>
<div class="navbar" >
<span>Hi <span style="font-style: italic;">{{ name }}</span>&nbsp;&nbsp;</span>
<a href="/sign_out">Sign out</a>
</div>
</div>
</div>
</header>
<div class="body-content">
{% block content %}
TO_REPLACE
{% endblock content %}
</div>
</body>
</html>

View File

@@ -1,146 +0,0 @@
{% extends "base_page.html" %}
{% block content %}
<!-- Success message -->
{% if let Some(msg) = success_message %}
<div class="alert alert-success">
{{ msg }}
</div>
{% endif %}
<!-- Error message -->
{% if let Some(msg) = error_message %}
<div class="alert alert-danger">
{{ msg }}
</div>
{% endif %}
<!-- User ID -->
<div id="user_id_container"><strong>Current user ID</strong>: {{ user_id.0 }}</div>
<!-- Display clients list -->
<div class="card border-light mb-3">
<div class="card-header">Registered clients</div>
<div class="card-body">
{% if clients.len() > 0 %}
<table class="table table-hover">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Description</th>
<th scope="col">Read only</th>
<th scope="col">Network</th>
<th scope="col">Created</th>
<th scope="col">Used</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
{% for client in clients %}
<tr>
<th scope="row">{{ client.id.0 }}</th>
<td>{{ client.description }}</td>
<td>
{% if client.readonly_client %}
<strong>YES</strong>
{% else %}
<i>NO</i>
{% endif %}
</td>
<td>
{% if let Some(net) = client.network %}
{{ net }}
{% else %}
<i>Unrestricted</i>
{% endif %}
</td>
<td>{{ client.fmt_created() }}</td>
<td>{{ client.fmt_used() }}</td>
<td>
<button type="button" class="btn btn-danger btn-sm" onclick="deleteClient('{{ client.id.0 }}');">
Delete
</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
{% if clients.len() == 0 %}
<p>No client registered yet!</p>
{% endif %}
</div>
</div>
<!-- New client -->
<div class="card border-light mb-3">
<div class="card-header">New client</div>
<div class="card-body">
<form action="/" method="post">
<div>
<label for="new_client_desc" class="form-label">Description</label>
<input type="text" class="form-control" id="new_client_desc" required minlength="3"
aria-describedby="new_client_desc" placeholder="New client description..."
name="new_client_desc"/>
<small class="form-text text-muted">Client description helps with identification.</small>
</div>
<div>
<label for="ip_network" class="form-label">Allowed IP network</label>
<input type="text" class="form-control" id="ip_network" aria-describedby="ip_network"
placeholder="Client network (x.x.x.x/x or x:x:x:x:x:x/x" name="ip_network"/>
<small class="form-text text-muted">Restrict the networks this IP address can be used from.</small>
</div>
<br/>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" checked id="readonly_client"
name="readonly_client"/>
<label class="form-check-label" for="readonly_client">
Readonly client
</label>
</div>
<br/>
<input type="submit" class="btn btn-primary" value="Create client"/>
</form>
</div>
</div>
<!-- Matrix authentication token -->
<div class="card border-light mb-3">
<div class="card-header">Matrix authentication token</div>
<div class="card-body">
<p>To obtain a new Matrix authentication token:</p>
<ol>
<li>Sign in to Element <strong>from a private browser window</strong></li>
<li>Open <em>All settings</em> and access the <em>Help &amp; About</em> tag</li>
<li>Expand <em>Access Token</em> and copy the value</li>
<li>Paste the copied value below</li>
<li>Close the private browser window <strong>without signing out</strong>!</li>
</ol>
<p>You should not need to replace this value unless you explicitly signed out the associated browser
session.</p>
<p>Tip: you can rename the session to easily identify it among all your other sessions!</p>
<form action="/" method="post">
<div>
<label for="accessTokenInput" class="form-label mt-4">New Matrix access token</label>
<input type="text" class="form-control" id="accessTokenInput" aria-describedby="tokenHelp"
placeholder="{{ matrix_token }}" required minlength="2" name="new_matrix_token"/>
<small id="tokenHelp" class="form-text text-muted">Changing this value will reset all active
connections
to Matrix GW.</small>
</div>
<input type="submit" class="btn btn-primary" value="Update"/>
</form>
</div>
</div>
<script src="/assets/script.js"></script>
{% endblock content %}

View File

@@ -1,46 +0,0 @@
{% extends "base_page.html" %}
{% block content %}
<style>
#ws_actions {
margin: 30px;
border: 1px white solid;
padding: 10px;
}
#ws_log {
margin: 30px;
border: 1px white solid;
padding: 10px;
}
#ws_log .message {
display: flex;
margin-bottom: 10px;
}
#ws_log .message .type {
font-style: italic;
margin-right: 10px;
}
</style>
<h2>WS Debug</h2>
<div id="ws_actions">
<button onclick="connect()">Reconnect</button>
<button onclick="disconnect()">Disconnect</button>
<button onclick="clearLogs()">Clear logs</button>
<span>State: <span id="state">DISCONNECTED</span></span>
</div>
<div id="ws_log">
<div class="message">
<div class="type">INFO</div>
<div>Welcome!</div>
</div>
</div>
<script src="/assets/ws_debug.js"></script>
{% endblock content %}