Compare commits

..

No commits in common. "b8b6dda131e5d85214938a8848a8210ce7503cb2" and "b068f4f91e1569e184a5349d85c67c78213be381" have entirely different histories.

24 changed files with 387 additions and 457 deletions

View file

@ -1,3 +1,6 @@
relay.example.com {
reverse_proxy / http://localhost:8080
relay.example.org {
gzip
proxy / 127.0.0.1:8080 {
transparent
}
}

View file

@ -8,12 +8,9 @@ import traceback
import typing
from aiohttp import web
from aiohttp.web import StaticResource
from aiohttp_swagger import setup_swagger
from aputils.signer import Signer
from datetime import datetime, timedelta
from mimetypes import guess_type
from pathlib import Path
from queue import Empty
from threading import Event, Thread
@ -71,6 +68,8 @@ class Application(web.Application):
for path, view in VIEWS:
self.router.add_view(path, view)
self.add_routes([web.static('/static', get_resource('frontend/static'))])
setup_swagger(
self,
ui_version = 3,
@ -131,7 +130,7 @@ class Application(web.Application):
data = [
"default-src 'none'",
f"script-src 'nonce-{request['hash']}'",
f"style-src 'self' 'nonce-{request['hash']}'",
f"style-src 'nonce-{request['hash']}'",
"form-action 'self'",
"connect-src 'self'",
"img-src 'self'",
@ -146,16 +145,6 @@ class Application(web.Application):
self['push_queue'].put((inbox, message, instance))
def register_static_routes(self) -> None:
if self['dev']:
static = StaticResource('/static', get_resource('frontend/static'))
else:
static = CachedStaticResource('/static', get_resource('frontend/static'))
self.router.register_resource(static)
def run(self) -> None:
if self["running"]:
return
@ -168,8 +157,6 @@ class Application(web.Application):
logging.error(f'A server is already running on {host}:{port}')
return
self.register_static_routes()
logging.info(f'Starting webserver at {domain} ({host}:{port})')
asyncio.run(self.handle_run())
@ -236,39 +223,6 @@ class Application(web.Application):
self['cache'].close()
class CachedStaticResource(StaticResource):
def __init__(self, prefix: str, path: Path):
StaticResource.__init__(self, prefix, path)
self.cache: dict[Path, bytes] = {}
for filename in path.rglob('*'):
if filename.is_dir():
continue
rel_path = str(filename.relative_to(path))
with filename.open('rb') as fd:
logging.debug('Loading static resource "%s"', rel_path)
self.cache[rel_path] = fd.read()
async def _handle(self, request: web.Request) -> web.StreamResponse:
rel_url = request.match_info['filename']
if Path(rel_url).anchor:
raise web.HTTPForbidden()
try:
return web.Response(
body = self.cache[rel_url],
content_type = guess_type(rel_url)[0]
)
except KeyError:
raise web.HTTPNotFound()
class CacheCleanupThread(Thread):
def __init__(self, app: Application):
Thread.__init__(self)
@ -333,8 +287,8 @@ async def handle_response_headers(request: web.Request, handler: Callable) -> Re
resp.headers['Server'] = 'ActivityRelay'
# Still have to figure out how csp headers work
if resp.content_type == 'text/html':
resp.headers['Content-Security-Policy'] = Application.DEFAULT.get_csp(request)
# if resp.content_type == 'text/html':
# resp.headers['Content-Security-Policy'] = Application.DEFAULT.get_csp(request)
if not request.app['dev'] and request.path.endswith(('.css', '.js')):
# cache for 2 weeks

View file

@ -9,7 +9,6 @@ from pathlib import Path
from tempfile import TemporaryDirectory
from . import __version__
from . import logger as logging
try:
from watchdog.observers import Observer
@ -87,11 +86,10 @@ def cli_build():
@cli.command('run')
@click.option('--dev', '-d', is_flag = True)
def cli_run(dev: bool):
def cli_run():
print('Starting process watcher')
handler = WatchHandler(dev)
handler = WatchHandler()
handler.run_proc()
watcher = Observer()
@ -114,13 +112,12 @@ def cli_run(dev: bool):
class WatchHandler(PatternMatchingEventHandler):
patterns = ['*.py']
cmd = [sys.executable, '-m', 'relay', 'run']
cmd = [sys.executable, '-m', 'relay', 'run', '-d']
def __init__(self, dev: bool):
def __init__(self):
PatternMatchingEventHandler.__init__(self)
self.dev: bool = dev
self.proc = None
self.last_restart = None
@ -129,7 +126,7 @@ class WatchHandler(PatternMatchingEventHandler):
if self.proc.poll() is not None:
return
logging.info(f'Terminating process {self.proc.pid}')
print(f'Terminating process {self.proc.pid}')
self.proc.terminate()
sec = 0.0
@ -138,11 +135,11 @@ class WatchHandler(PatternMatchingEventHandler):
sec += 0.1
if sec >= 5:
logging.error('Failed to terminate. Killing process...')
print('Failed to terminate. Killing process...')
self.proc.kill()
break
logging.info('Process terminated')
print('Process terminated')
def run_proc(self, restart=False):
@ -155,13 +152,10 @@ class WatchHandler(PatternMatchingEventHandler):
self.kill_proc()
cmd = [*self.cmd, '-d'] if self.dev else self.cmd
self.proc = subprocess.Popen(cmd, stdin = subprocess.PIPE)
self.proc = subprocess.Popen(self.cmd, stdin = subprocess.PIPE)
self.last_restart = timestamp
logging.info('Started process with PID %i', self.proc.pid)
logging.info('Command: %s', ' '.join(cmd))
print(f'Started process with PID {self.proc.pid}')
def on_any_event(self, event):

View file

@ -11,11 +11,9 @@
%title << {{config.name}}: {{page}}
%meta(charset="UTF-8")
%meta(name="viewport" content="width=device-width, initial-scale=1")
%link(rel="stylesheet" type="text/css" href="/theme/{{config.theme}}.css" nonce="{{view.request['hash']}}" class="theme")
%link(rel="stylesheet" type="text/css" href="/theme/{{config.theme}}.css" nonce="{{view.request['hash']}}")
%link(rel="stylesheet" type="text/css" href="/static/style.css" nonce="{{view.request['hash']}}")
%link(rel="stylesheet" type="text/css" href="/static/toast.css" nonce="{{view.request['hash']}}")
%script(type="application/javascript" src="/static/menu.js" nonce="{{view.request['hash']}}", defer)
%script(type="application/javascript" src="/static/toast.js" nonce="{{view.request['hash']}}", defer)
%script(type="application/javascript" src="/static/api.js" nonce="{{view.request['hash']}}", defer)
-block head
@ -39,8 +37,6 @@
-else
{{menu_item("Login", "/login")}}
%ul#notifications
#container
#header.section
%span#menu-open << &#8286;

View file

@ -1,13 +1,13 @@
-macro new_checkbox(name, checked)
-if checked
%input(id="{{name}}" type="checkbox" checked)
%input(id="{{name}}" name="{{name}}" type="checkbox" checked)
-else
%input(id="{{name}}" type="checkbox")
%input(id="{{name}}" name="{{name}}" type="checkbox")
-macro new_select(name, selected, items)
%select(id="{{name}}")
%select(id="{{name}}" name="{{name}}")
-for item in items
-if item == selected
%option(value="{{item}}" selected) -> =item.title()

View file

@ -11,10 +11,10 @@
.grid-2col
%label(for="name") << Name
%input(id = "name" placeholder="Relay Name" value="{{config.name or ''}}")
%input(id = "name" name="name" placeholder="Relay Name" value="{{config.name or ''}}")
%label(for="note") << Description
%textarea(id="note" value="{{config.note or ''}}") << {{config.note}}
%label(for="description") << Description
%textarea(id="description" name="note" value="{{config.note or ''}}") << {{config.note}}
%label(for="theme") << Color Theme
=func.new_select("theme", config.theme, themes)

View file

@ -2,7 +2,7 @@
-set page="Domain Bans"
-block head
%script(type="application/javascript" src="/static/domain_ban.js" nonce="{{view.request['hash']}}" defer)
%script(type="application/javascript" src="/static/domain_ban.js" nonce="{{view.request['hash']}}")
-block content
%details.section
@ -17,7 +17,7 @@
%label(for="new-note") << Admin Note
%textarea(id="new-note") << {{""}}
%input#new-ban(type="button" value="Ban Domain")
%input(type="button" value="Ban Domain" onclick="ban();")
%fieldset.section
%legend << Domain Bans
@ -44,10 +44,10 @@
%label.note(for="{{ban.domain}}-note") << Note
%textarea.note(id="{{ban.domain}}-note") << {{ban.note or ""}}
%input.update-ban(type="button" value="Update")
%input(type="button" value="Update" onclick="update_ban('{{ban.domain}}')")
%td.date
=ban.created.strftime("%Y-%m-%d")
%td.remove
%a(href="#" title="Unban domain") << &#10006;
%a(href="#" onclick="unban('{{ban.domain}}')" title="Unban domain") << &#10006;

View file

@ -2,7 +2,7 @@
-set page="Instances"
-block head
%script(type="application/javascript" src="/static/instance.js" nonce="{{view.request['hash']}}" defer)
%script(type="application/javascript" src="/static/instance.js" nonce="{{view.request['hash']}}")
-block content
%details.section
@ -20,7 +20,7 @@
%label(for="new-software") << Software
%input(id="new-software" placeholder="software")
%input#add-instance(type="button" value="Add Instance")
%input(type="button" value="Add Instance", onclick="add_instance()")
-if requests
%fieldset.section.requests
@ -48,10 +48,10 @@
=request.created.strftime("%Y-%m-%d")
%td.approve
%a(href="#" title="Approve Request") << &check;
%a(href="#" onclick="req_response('{{request.domain}}', true)" title="Approve Request") << &check;
%td.deny
%a(href="#" title="Deny Request") << &#10006;
%a(href="#" onclick="req_response('{{request.domain}}', false)" title="Deny Request") << &#10006;
%fieldset.section.instances
%legend << Instances
@ -78,4 +78,4 @@
=instance.created.strftime("%Y-%m-%d")
%td.remove
%a(href="#" title="Remove Instance") << &#10006;
%a(href="#" onclick="del_instance('{{instance.domain}}')" title="Remove Instance") << &#10006;

View file

@ -2,7 +2,7 @@
-set page="Software Bans"
-block head
%script(type="application/javascript" src="/static/software_ban.js" nonce="{{view.request['hash']}}" defer)
%script(type="application/javascript" src="/static/software_ban.js" nonce="{{view.request['hash']}}")
-block content
%details.section
@ -17,13 +17,13 @@
%label(for="new-note") << Admin Note
%textarea(id="new-note") << {{""}}
%input#new-ban(type="button" value="Ban Software")
%input(type="submit" value="Ban Software" onclick="ban()")
%fieldset.section
%legend << Software Bans
.data-table
%table#bans
%table
%thead
%tr
%td.name << Name
@ -44,10 +44,10 @@
%label.note(for="{{ban.name}}-note") << Note
%textarea.note(id="{{ban.name}}-note") << {{ban.note or ""}}
%input.update-ban(type="button" value="Update")
%input(type="button" value="Update" onclick="update_ban('{{ban.name}}')")
%td.date
=ban.created.strftime("%Y-%m-%d")
%td.remove
%a(href="#" title="Unban name") << &#10006;
%a(href="#" onclick="unban('{{ban.name}}')" title="Unban name") << &#10006;

View file

@ -2,25 +2,25 @@
-set page="Users"
-block head
%script(type="application/javascript" src="/static/user.js" nonce="{{view.request['hash']}}" defer)
%script(type="application/javascript" src="/static/user.js" nonce="{{view.request['hash']}}")
-block content
%details.section
%summary << Add User
#add-item
%label(for="new-username") << Username
%input(id="new-username" name="username" placeholder="Username" autocomplete="off")
%input(id="new-username" name="username" placeholder="Username")
%label(for="new-password") << Password
%input(id="new-password" type="password" placeholder="Password" autocomplete="off")
%input(id="new-password" type="password" placeholder="Password")
%label(for="new-password2") << Password Again
%input(id="new-password2" type="password" placeholder="Password Again" autocomplete="off")
%input(id="new-password2" type="password" placeholder="Password Again")
%label(for="new-handle") << Handle
%input(id="new-handle" type="email" placeholder="handle" autocomplete="off")
%input(id="new-handle" type="email" placeholder="handle")
%input#new-user(type="button" value="Add User")
%input(type="button" value="Add User" onclick="add_user()")
%fieldset.section
%legend << Users
@ -47,4 +47,4 @@
=user.created.strftime("%Y-%m-%d")
%td.remove
%a(href="#" title="Remove User") << &#10006;
%a(href="#" onclick="del_user('{{user.username}}')" title="Remove User") << &#10006;

View file

@ -2,7 +2,7 @@
-set page="Whitelist"
-block head
%script(type="application/javascript" src="/static/whitelist.js" nonce="{{view.request['hash']}}" defer)
%script(type="application/javascript" src="/static/whitelist.js" nonce="{{view.request['hash']}}")
-block content
%details.section
@ -11,7 +11,7 @@
%label(for="new-domain") << Domain
%input(type="domain" id="new-domain" placeholder="Domain")
%input#new-item(type="button" value="Add Domain")
%input(type="button" value="Add Domain", onclick="add_whitelist()")
%fieldset.data-table.section
%legend << Whitelist
@ -33,4 +33,4 @@
=item.created.strftime("%Y-%m-%d")
%td.remove
%a(href="#" title="Remove whitlisted domain") << &#10006;
%a(href="#" onclick="del_whitelist('{{item.domain}}')" title="Remove whitlisted domain") << &#10006;

View file

@ -1,13 +1,10 @@
-extends "base.haml"
-set page="Login"
-block head
%script(type="application/javascript" src="/static/login.js" nonce="{{view.request['hash']}}" defer)
-block content
%fieldset.section
%legend << Login
%form(action="/login" method="POST")
.grid-2col
%label(for="username") << Username
%input(id="username" name="username" placeholder="Username" value="{{username or ''}}")
@ -15,4 +12,4 @@
%label(for="password") << Password
%input(id="password" name="password" placeholder="Password" type="password")
%input.submit(type="button" value="Login")
%input(type="submit" value="Login")

View file

@ -30,8 +30,6 @@ function append_table_row(table, row_name, row) {
index += 1;
}
}
return table_row;
}

View file

@ -1,6 +1,6 @@
const elems = [
document.querySelector("#name"),
document.querySelector("#note"),
document.querySelector("#description"),
document.querySelector("#theme"),
document.querySelector("#log-level"),
document.querySelector("#whitelist-enabled"),
@ -18,7 +18,7 @@ async function handle_config_change(event) {
await request("POST", "v1/config", params);
} catch (error) {
toast(error);
alert(error);
return;
}
@ -26,12 +26,6 @@ async function handle_config_change(event) {
document.querySelector("#header .title").innerHTML = params.value;
document.querySelector("title").innerHTML = params.value;
}
if (params.key === "theme") {
document.querySelector("link.theme").href = `/theme/${params.value}.css`;
}
toast("Updated config", "message");
}

View file

@ -6,25 +6,13 @@ function create_ban_object(domain, reason, note) {
text += `<textarea id="${domain}-reason" class="reason">${reason}</textarea>\n`;
text += `<label for="${domain}-note" class="note">Note</label>\n`;
text += `<textarea id="${domain}-note" class="note">${note}</textarea>\n`;
text += `<input class="update-ban" type="button" value="Update">`;
text += `<input type="button" value="Update" onclick="update_ban(\"${domain}\"")">`;
text += '</details>';
return text;
}
function add_row_listeners(row) {
row.querySelector(".update-ban").addEventListener("click", async (event) => {
await update_ban(row.id);
});
row.querySelector(".remove a").addEventListener("click", async (event) => {
event.preventDefault();
await unban(row.id);
});
}
async function ban() {
var table = document.querySelector("table");
var elems = {
@ -35,12 +23,12 @@ async function ban() {
var values = {
domain: elems.domain.value.trim(),
reason: elems.reason.value.trim(),
note: elems.note.value.trim()
reason: elems.reason.value,
note: elems.note.value
}
if (values.domain === "") {
toast("Domain is required");
alert("Domain is required");
return;
}
@ -48,24 +36,21 @@ async function ban() {
var ban = await request("POST", "v1/domain_ban", values);
} catch (err) {
toast(err);
alert(err);
return
}
var row = append_table_row(document.querySelector("table"), ban.domain, {
append_table_row(document.getElementById("instances"), ban.domain, {
domain: create_ban_object(ban.domain, ban.reason, ban.note),
date: get_date_string(ban.created),
remove: `<a href="#" title="Unban domain">&#10006;</a>`
remove: `<a href="#" onclick="unban('${ban.domain}')" title="Unban domain">&#10006;</a>`
});
add_row_listeners(row);
elems.domain.value = null;
elems.reason.value = null;
elems.note.value = null;
document.querySelector("details.section").open = false;
toast("Banned domain", "message");
}
@ -87,12 +72,11 @@ async function update_ban(domain) {
await request("PATCH", "v1/domain_ban", values)
} catch (error) {
toast(error);
alert(error);
return;
}
row.querySelector("details").open = false;
toast("Updated baned domain", "message");
}
@ -101,23 +85,9 @@ async function unban(domain) {
await request("DELETE", "v1/domain_ban", {"domain": domain});
} catch (error) {
toast(error);
alert(error);
return;
}
document.getElementById(domain).remove();
toast("Unbanned domain", "message");
}
document.querySelector("#new-ban").addEventListener("click", async (event) => {
await ban();
});
for (var row of document.querySelector("fieldset.section table").rows) {
if (!row.querySelector(".update-ban")) {
continue;
}
add_row_listeners(row);
}

View file

@ -1,24 +1,3 @@
function add_instance_listeners(row) {
row.querySelector(".remove a").addEventListener("click", async (event) => {
event.preventDefault();
await del_instance(row.id);
});
}
function add_request_listeners(row) {
row.querySelector(".approve a").addEventListener("click", async (event) => {
event.preventDefault();
await req_response(row.id, true);
});
row.querySelector(".deny a").addEventListener("click", async (event) => {
event.preventDefault();
await req_response(row.id, false);
});
}
async function add_instance() {
var elems = {
actor: document.getElementById("new-actor"),
@ -35,7 +14,7 @@ async function add_instance() {
}
if (values.actor === "") {
toast("Actor is required");
alert("Actor is required");
return;
}
@ -43,26 +22,23 @@ async function add_instance() {
var instance = await request("POST", "v1/instance", values);
} catch (err) {
toast(err);
alert(err);
return
}
row = append_table_row(document.getElementById("instances"), instance.domain, {
append_table_row(document.getElementById("instances"), instance.domain, {
domain: `<a href="https://${instance.domain}/" target="_new">${instance.domain}</a>`,
software: instance.software,
date: get_date_string(instance.created),
remove: `<a href="#" title="Remove Instance">&#10006;</a>`
remove: `<a href="#" onclick="del_instance('${instance.domain}')" title="Remove Instance">&#10006;</a>`
});
add_instance_listeners(row);
elems.actor.value = null;
elems.inbox.value = null;
elems.followid.value = null;
elems.software.value = null;
document.querySelector("details.section").open = false;
toast("Added instance", "message");
}
@ -71,7 +47,7 @@ async function del_instance(domain) {
await request("DELETE", "v1/instance", {"domain": domain});
} catch (error) {
toast(error);
alert(error);
return;
}
@ -89,7 +65,7 @@ async function req_response(domain, accept) {
await request("POST", "v1/request", params);
} catch (error) {
toast(error);
alert(error);
return;
}
@ -106,39 +82,12 @@ async function req_response(domain, accept) {
instances = await request("GET", `v1/instance`, null);
instances.forEach((instance) => {
if (instance.domain === domain) {
row = append_table_row(document.getElementById("instances"), instance.domain, {
append_table_row(document.getElementById("instances"), instance.domain, {
domain: `<a href="https://${instance.domain}/" target="_new">${instance.domain}</a>`,
software: instance.software,
date: get_date_string(instance.created),
remove: `<a href="#" title="Remove Instance">&#10006;</a>`
remove: `<a href="#" onclick="del_instance('${instance.domain}')" title="Remove Instance">&#10006;</a>`
});
add_instance_listeners(row);
}
});
toast("Removed instance", "message");
}
document.querySelector("#add-instance").addEventListener("click", async (event) => {
await add_instance();
})
for (var row of document.querySelector("#instances").rows) {
if (!row.querySelector(".remove a")) {
continue;
}
add_instance_listeners(row);
}
if (document.querySelector("#requests")) {
for (var row of document.querySelector("#requests").rows) {
if (!row.querySelector(".approve a")) {
continue;
}
add_request_listeners(row);
}
}

View file

@ -1,29 +0,0 @@
async function login(event) {
fields = {
username: document.querySelector("#username"),
password: document.querySelector("#password")
}
values = {
username: fields.username.value.trim(),
password: fields.password.value.trim()
}
if (values.username === "" | values.password === "") {
toast("Username and/or password field is blank");
return;
}
try {
await request("POST", "v1/token", values);
} catch (error) {
toast(error);
return;
}
document.location = "/";
}
document.querySelector(".submit").addEventListener("click", login);

View file

@ -6,26 +6,17 @@ function create_ban_object(name, reason, note) {
text += `<textarea id="${name}-reason" class="reason">${reason}</textarea>\n`;
text += `<label for="${name}-note" class="note">Note</label>\n`;
text += `<textarea id="${name}-note" class="note">${note}</textarea>\n`;
text += `<input class="update-ban" type="button" value="Update">`;
text += `<input type="button" value="Update" onclick="update_ban(\"${name}\"")">`;
text += '</details>';
return text;
}
function add_row_listeners(row) {
row.querySelector(".update-ban").addEventListener("click", async (event) => {
await update_ban(row.id);
});
row.querySelector(".remove a").addEventListener("click", async (event) => {
event.preventDefault();
await unban(row.id);
});
}
async function ban() {
var table = document.querySelector("table");
var row = table.insertRow(-1);
var elems = {
name: document.getElementById("new-name"),
reason: document.getElementById("new-reason"),
@ -39,7 +30,7 @@ async function ban() {
}
if (values.name === "") {
toast("Domain is required");
alert("Domain is required");
return;
}
@ -47,24 +38,21 @@ async function ban() {
var ban = await request("POST", "v1/software_ban", values);
} catch (err) {
toast(err);
alert(err);
return
}
var row = append_table_row(document.getElementById("bans"), ban.name, {
append_table_row(document.getElementById("instances"), ban.name, {
name: create_ban_object(ban.name, ban.reason, ban.note),
date: get_date_string(ban.created),
remove: `<a href="#" title="Unban software">&#10006;</a>`
remove: `<a href="#" onclick="unban('${ban.domain}')" title="Unban software">&#10006;</a>`
});
add_row_listeners(row);
elems.name.value = null;
elems.reason.value = null;
elems.note.value = null;
document.querySelector("details.section").open = false;
toast("Banned software", "message");
}
@ -86,12 +74,11 @@ async function update_ban(name) {
await request("PATCH", "v1/software_ban", values)
} catch (error) {
toast(error);
alert(error);
return;
}
row.querySelector("details").open = false;
toast("Updated software ban", "message");
}
@ -100,23 +87,9 @@ async function unban(name) {
await request("DELETE", "v1/software_ban", {"name": name});
} catch (error) {
toast(error);
alert(error);
return;
}
document.getElementById(name).remove();
toast("Unbanned software", "message");
}
document.querySelector("#new-ban").addEventListener("click", async (event) => {
await ban();
});
for (var row of document.querySelector("#bans").rows) {
if (!row.querySelector(".update-ban")) {
continue;
}
add_row_listeners(row);
}

View file

@ -1,68 +0,0 @@
#notifications {
position: fixed;
top: 40px;
left: 50%;
transform: translateX(-50%);
}
#notifications li {
position: relative;
overflow: hidden;
list-style: none;
border-radius: 5px;
padding: 5px;;
margin-bottom: var(--spacing);
animation: show_toast 0.3s ease forwards;
display: grid;
grid-template-columns: auto max-content;
grid-gap: 5px;
align-items: center;
}
#notifications a {
font-size: 1.5em;
line-height: 1em;
text-decoration: none;
}
#notifications li.hide {
animation: hide_toast 0.3s ease forwards;
}
@keyframes show_toast {
0% {
transform: translateX(100%);
}
40% {
transform: translateX(-5%);
}
80% {
transform: translateX(0%);
}
100% {
transform: translateX(-10px);
}
}
@keyframes hide_toast {
0% {
transform: translateX(-10px);
}
40% {
transform: translateX(0%);
}
80% {
transform: translateX(-5%);
}
100% {
transform: translateX(calc(100% + 20px));
}
}

View file

@ -1,26 +0,0 @@
const notifications = document.querySelector("#notifications")
function remove_toast(toast) {
toast.classList.add("hide");
if (toast.timeoutId) {
clearTimeout(toast.timeoutId);
}
setTimeout(() => toast.remove(), 300);
}
function toast(text, type="error", timeout=5) {
const toast = document.createElement("li");
toast.className = `section ${type}`
toast.innerHTML = `<span class=".text">${text}</span><a href="#">&#10006;</span>`
toast.querySelector("a").addEventListener("click", async (event) => {
event.preventDefault();
await remove_toast(toast);
});
notifications.appendChild(toast);
toast.timeoutId = setTimeout(() => remove_toast(toast), timeout * 1000);
}

View file

@ -1,11 +1,3 @@
function add_row_listeners(row) {
row.querySelector(".remove a").addEventListener("click", async (event) => {
event.preventDefault();
await del_user(row.id);
});
}
async function add_user() {
var elems = {
username: document.getElementById("new-username"),
@ -22,12 +14,12 @@ async function add_user() {
}
if (values.username === "" | values.password === "" | values.password2 === "") {
toast("Username, password, and password2 are required");
alert("Username, password, and password2 are required");
return;
}
if (values.password !== values.password2) {
toast("Passwords do not match");
alert("Passwords do not match");
return;
}
@ -35,26 +27,23 @@ async function add_user() {
var user = await request("POST", "v1/user", values);
} catch (err) {
toast(err);
alert(err);
return
}
var row = append_table_row(document.querySelector("fieldset.section table"), user.username, {
append_table_row(document.getElementById("users"), user.username, {
domain: user.username,
handle: user.handle ? self.handle : "n/a",
handle: user.handle,
date: get_date_string(user.created),
remove: `<a href="#" title="Delete User">&#10006;</a>`
remove: `<a href="#" onclick="del_user('${user.username}')" title="Delete User">&#10006;</a>`
});
add_row_listeners(row);
elems.username.value = null;
elems.password.value = null;
elems.password2.value = null;
elems.handle.value = null;
document.querySelector("details.section").open = false;
toast("Created user", "message");
}
@ -63,23 +52,9 @@ async function del_user(username) {
await request("DELETE", "v1/user", {"username": username});
} catch (error) {
toast(error);
alert(error);
return;
}
document.getElementById(username).remove();
toast("Deleted user", "message");
}
document.querySelector("#new-user").addEventListener("click", async (event) => {
await add_user();
});
for (var row of document.querySelector("#users").rows) {
if (!row.querySelector(".remove a")) {
continue;
}
add_row_listeners(row);
}

View file

@ -1,17 +1,9 @@
function add_row_listeners(row) {
row.querySelector(".remove a").addEventListener("click", async (event) => {
event.preventDefault();
await del_whitelist(row.id);
});
}
async function add_whitelist() {
var domain_elem = document.getElementById("new-domain");
var domain = domain_elem.value.trim();
if (domain === "") {
toast("Domain is required");
alert("Domain is required");
return;
}
@ -19,21 +11,18 @@ async function add_whitelist() {
var item = await request("POST", "v1/whitelist", {"domain": domain});
} catch (err) {
toast(err);
return;
alert(err);
return
}
var row = append_table_row(document.getElementById("whitelist"), item.domain, {
append_table_row(document.getElementById("whitelist"), item.domain, {
domain: item.domain,
date: get_date_string(item.created),
remove: `<a href="#" title="Remove whitelisted domain">&#10006;</a>`
remove: `<a href="#" onclick="del_whitelist('${item.domain}')" title="Remove whitelisted domain">&#10006;</a>`
});
add_row_listeners(row);
domain_elem.value = null;
document.querySelector("details.section").open = false;
toast("Added domain", "message");
}
@ -42,23 +31,9 @@ async function del_whitelist(domain) {
await request("DELETE", "v1/whitelist", {"domain": domain});
} catch (error) {
toast(error);
alert(error);
return;
}
document.getElementById(domain).remove();
toast("Removed domain", "message");
}
document.querySelector("#new-item").addEventListener("click", async (event) => {
await add_whitelist();
});
for (var row of document.querySelector("fieldset.section table").rows) {
if (!row.querySelector(".remove a")) {
continue;
}
add_row_listeners(row);
}

View file

@ -81,19 +81,7 @@ class Login(View):
token = conn.put_token(data['username'])
resp = Response.new({'token': token['code']}, ctype = 'json')
resp.set_cookie(
'user-token',
token['code'],
max_age = 60 * 60 * 24 * 365,
domain = self.config.domain,
path = '/',
secure = True,
httponly = False,
samesite = 'lax'
)
return resp
return Response.new({'token': token['code']}, ctype = 'json')
async def delete(self, request: Request) -> Response:

View file

@ -72,6 +72,47 @@ class Login(View):
return Response.new(data, ctype = 'html')
async def post(self, request: Request) -> Response:
form = await request.post()
params = {}
with self.database.session(True) as conn:
if not (user := conn.get_user(form['username'])):
params = {
'username': form['username'],
'error': 'User not found'
}
else:
try:
conn.hasher.verify(user['hash'], form['password'])
except VerifyMismatchError:
params = {
'username': form['username'],
'error': 'Invalid password'
}
if params:
data = self.template.render('page/login.haml', self, **params)
return Response.new(data, ctype = 'html')
token = conn.put_token(user['username'])
resp = Response.new_redir(request.query.getone('redir', '/'))
resp.set_cookie(
'user-token',
token['code'],
max_age = 60 * 60 * 24 * 365,
domain = self.config.domain,
path = '/',
secure = True,
httponly = False,
samesite = 'lax'
)
return resp
@register_route('/logout')
class Logout(View):
async def get(self, request: Request) -> Response:
@ -112,6 +153,104 @@ class AdminInstances(View):
return Response.new(data, ctype = 'html')
async def post(self, request: Request) -> Response:
post = await request.post()
data: dict[str, str] = {key: value for key, value in post.items()} # type: ignore
if not data.get('actor') and not data.get('domain'):
return await self.get(request, error = 'Missing actor and/or domain')
if not data.get('domain'):
data['domain'] = urlparse(data['actor']).netloc
if not data.get('software'):
nodeinfo = await self.client.fetch_nodeinfo(data['domain'])
if nodeinfo is None:
return await self.get(request, error = 'Failed to fetch nodeinfo')
data['software'] = nodeinfo.sw_name
if not data.get('actor') and data['software'] in ACTOR_FORMATS:
data['actor'] = ACTOR_FORMATS[data['software']].format(domain = data['domain'])
if not data.get('inbox') and data['actor']:
actor: Message | None = await self.client.get(data['actor'], True, Message)
if actor is None:
return await self.get(request, error = 'Failed to fetch actor')
data['inbox'] = actor.shared_inbox
with self.database.session(True) as conn:
conn.put_inbox(**data)
return await self.get(request, message = "Added new inbox")
@register_route('/admin/instances/delete/{domain}')
class AdminInstancesDelete(View):
async def get(self, request: Request, domain: str) -> Response:
with self.database.session(True) as conn:
if not conn.get_inbox(domain):
return await AdminInstances(request).get(request, error = 'Instance not found')
conn.del_inbox(domain)
return await AdminInstances(request).get(request, message = 'Removed instance')
@register_route('/admin/instances/approve/{domain}')
class AdminInstancesApprove(View):
async def get(self, request: Request, domain: str) -> Response:
try:
with self.database.session(True) as conn:
instance = conn.put_request_response(domain, True)
except KeyError:
return await AdminInstances(request).get(request, error = 'Instance not found')
message = Message.new_response(
host = self.config.domain,
actor = instance['actor'],
followid = instance['followid'],
accept = True
)
self.app.push_message(instance['inbox'], message, instance)
if instance['software'] != 'mastodon':
message = Message.new_follow(
host = self.config.domain,
actor = instance['actor']
)
self.app.push_message(instance['inbox'], message, instance)
return await AdminInstances(request).get(request, message = 'Request accepted')
@register_route('/admin/instances/deny/{domain}')
class AdminInstancesDeny(View):
async def get(self, request: Request, domain: str) -> Response:
try:
with self.database.session(True) as conn:
instance = conn.put_request_response(domain, False)
except KeyError:
return await AdminInstances(request).get(request, error = 'Instance not found')
message = Message.new_response(
host = self.config.domain,
actor = instance['actor'],
followid = instance['followid'],
accept = False
)
self.app.push_message(instance['inbox'], message, instance)
return await AdminInstances(request).get(request, message = 'Request denied')
@register_route('/admin/whitelist')
class AdminWhitelist(View):
async def get(self,
@ -134,6 +273,34 @@ class AdminWhitelist(View):
return Response.new(data, ctype = 'html')
async def post(self, request: Request) -> Response:
data = await request.post()
if not data['domain']:
return await self.get(request, error = 'Missing domain')
with self.database.session(True) as conn:
if conn.get_domain_whitelist(data['domain']):
return await self.get(request, error = "Domain already in whitelist")
conn.put_domain_whitelist(data['domain'])
return await self.get(request, message = "Added/updated domain ban")
@register_route('/admin/whitelist/delete/{domain}')
class AdminWhitlistDelete(View):
async def get(self, request: Request, domain: str) -> Response:
with self.database.session() as conn:
if not conn.get_domain_whitelist(domain):
msg = 'Whitelisted domain not found'
return await AdminWhitelist.run("GET", request, error = msg)
conn.del_domain_whitelist(domain)
return await AdminWhitelist.run("GET", request, message = 'Removed domain from whitelist')
@register_route('/admin/domain_bans')
class AdminDomainBans(View):
async def get(self,
@ -156,6 +323,42 @@ class AdminDomainBans(View):
return Response.new(data, ctype = 'html')
async def post(self, request: Request) -> Response:
data = await request.post()
if not data['domain']:
return await self.get(request, error = 'Missing domain')
with self.database.session(True) as conn:
if conn.get_domain_ban(data['domain']):
conn.update_domain_ban(
data['domain'],
data.get('reason'),
data.get('note')
)
else:
conn.put_domain_ban(
data['domain'],
data.get('reason'),
data.get('note')
)
return await self.get(request, message = "Added/updated domain ban")
@register_route('/admin/domain_bans/delete/{domain}')
class AdminDomainBansDelete(View):
async def get(self, request: Request, domain: str) -> Response:
with self.database.session() as conn:
if not conn.get_domain_ban(domain):
return await AdminDomainBans.run("GET", request, error = 'Domain ban not found')
conn.del_domain_ban(domain)
return await AdminDomainBans.run("GET", request, message = 'Unbanned domain')
@register_route('/admin/software_bans')
class AdminSoftwareBans(View):
async def get(self,
@ -178,6 +381,42 @@ class AdminSoftwareBans(View):
return Response.new(data, ctype = 'html')
async def post(self, request: Request) -> Response:
data = await request.post()
if not data['name']:
return await self.get(request, error = 'Missing name')
with self.database.session(True) as conn:
if conn.get_software_ban(data['name']):
conn.update_software_ban(
data['name'],
data.get('reason'),
data.get('note')
)
else:
conn.put_software_ban(
data['name'],
data.get('reason'),
data.get('note')
)
return await self.get(request, message = "Added/updated software ban")
@register_route('/admin/software_bans/delete/{name}')
class AdminSoftwareBansDelete(View):
async def get(self, request: Request, name: str) -> Response:
with self.database.session() as conn:
if not conn.get_software_ban(name):
return await AdminSoftwareBans.run("GET", request, error = 'Software ban not found')
conn.del_software_ban(name)
return await AdminSoftwareBans.run("GET", request, message = 'Unbanned software')
@register_route('/admin/users')
class AdminUsers(View):
async def get(self,
@ -200,6 +439,37 @@ class AdminUsers(View):
return Response.new(data, ctype = 'html')
async def post(self, request: Request) -> Response:
data = await request.post()
required_fields = {'username', 'password', 'password2'}
if not all(data.get(field) for field in required_fields):
return await self.get(request, error = 'Missing username and/or password')
if data['password'] != data['password2']:
return await self.get(request, error = 'Passwords do not match')
with self.database.session(True) as conn:
if conn.get_user(data['username']):
return await self.get(request, error = "User already exists")
conn.put_user(data['username'], data['password'], data['handle'])
return await self.get(request, message = "Added user")
@register_route('/admin/users/delete/{name}')
class AdminUsersDelete(View):
async def get(self, request: Request, name: str) -> Response:
with self.database.session() as conn:
if not conn.get_user(name):
return await AdminUsers.run("GET", request, error = 'User not found')
conn.del_user(name)
return await AdminUsers.run("GET", request, message = 'User deleted')
@register_route('/admin/config')
class AdminConfig(View):
async def get(self, request: Request, message: str | None = None) -> Response:
@ -213,6 +483,23 @@ class AdminConfig(View):
return Response.new(data, ctype = 'html')
async def post(self, request: Request) -> Response:
form = dict(await request.post())
data = ConfigData()
for key in ConfigData.USER_KEYS():
data.set(key, form.get(key.replace('_', '-')))
with self.database.session(True) as conn:
for key, value in data.to_dict().items():
if key in ConfigData.SYSTEM_KEYS():
continue
conn.put_config(key, value)
return await self.get(request, message = 'Updated config')
@register_route('/style.css')
class StyleCss(View):
async def get(self, request: Request) -> Response: