build: Add prettier to the project

This commit is contained in:
2024-02-22 15:36:45 +01:00
parent 17b92126de
commit 41024ddb79
95 changed files with 4237 additions and 2117 deletions

View File

@ -1,7 +1,7 @@
import * as core from './core.js';
import * as form from './form.js';
let gDatabase = new Database("auth");
let gDatabase = new Database('auth');
const kRefreshInterval = 1 * 7 * 24 * 60 * 60 * 1000;
@ -36,8 +36,20 @@ function makeJwt(payload) {
id = ssb.createIdentity(':auth');
}
let final_payload = b64url(base64Encode(JSON.stringify(Object.assign({}, payload, {exp: (new Date().valueOf()) + kRefreshInterval}))));
let jwt = [b64url(base64Encode(JSON.stringify({alg: 'HS256', typ: 'JWT'}))), final_payload, b64url(ssb.hmacsha256sign(final_payload, ':auth', id))].join('.');
let final_payload = b64url(
base64Encode(
JSON.stringify(
Object.assign({}, payload, {
exp: new Date().valueOf() + kRefreshInterval,
})
)
)
);
let jwt = [
b64url(base64Encode(JSON.stringify({alg: 'HS256', typ: 'JWT'}))),
final_payload,
b64url(ssb.hmacsha256sign(final_payload, ':auth', id)),
].join('.');
return jwt;
}
@ -51,7 +63,7 @@ function readSession(session) {
let id = ssb.getIdentities(':auth');
if (id?.length && ssb.hmacsha256verify(id[0], payload, signature)) {
let result = JSON.parse(utf8Decode(base64Decode(unb64url(payload))));
let now = new Date().valueOf()
let now = new Date().valueOf();
if (now < result.exp) {
print(`JWT valid for another ${(result.exp - now) / 1000} seconds.`);
return result;
@ -77,9 +89,15 @@ function hashPassword(password) {
}
function noAdministrator() {
return !core.globalSettings || !core.globalSettings.permissions || !Object.keys(core.globalSettings.permissions).some(function(name) {
return core.globalSettings.permissions[name].indexOf("administration") != -1;
});
return (
!core.globalSettings ||
!core.globalSettings.permissions ||
!Object.keys(core.globalSettings.permissions).some(function (name) {
return (
core.globalSettings.permissions[name].indexOf('administration') != -1
);
})
);
}
function makeAdministrator(name) {
@ -89,8 +107,8 @@ function makeAdministrator(name) {
if (!core.globalSettings.permissions[name]) {
core.globalSettings.permissions[name] = [];
}
if (core.globalSettings.permissions[name].indexOf("administration") == -1) {
core.globalSettings.permissions[name].push("administration");
if (core.globalSettings.permissions[name].indexOf('administration') == -1) {
core.globalSettings.permissions[name].push('administration');
}
core.setGlobalSettings(core.globalSettings);
}
@ -101,7 +119,7 @@ function getCookies(headers) {
if (headers.cookie) {
let parts = headers.cookie.split(/,|;/);
for (let i in parts) {
let equals = parts[i].indexOf("=");
let equals = parts[i].indexOf('=');
let name = parts[i].substring(0, equals).trim();
let value = parts[i].substring(equals + 1).trim();
cookies[name] = value;
@ -113,18 +131,34 @@ function getCookies(headers) {
function isNameValid(name) {
let c = name.charAt(0);
return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) && name.split().map(x => x >= ('a' && x <= 'z') || x >= ('A' && x <= 'Z') || x >= ('0' && x <= '9'));
return (
((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) &&
name
.split()
.map(
(x) =>
x >= ('a' && x <= 'z') ||
x >= ('A' && x <= 'Z') ||
x >= ('0' && x <= '9')
)
);
}
function handler(request, response) {
let session = getCookies(request.headers).session;
if (request.uri == "/login") {
if (request.uri == '/login') {
let formData = form.decodeForm(request.query);
if (query(request.headers)?.permissions?.authenticated) {
if (formData.return) {
response.writeHead(303, {"Location": formData.return});
response.writeHead(303, {Location: formData.return});
} else {
response.writeHead(303, {"Location": (request.client.tls ? 'https://' : 'http://') + request.headers.host + '/', "Content-Length": "0"});
response.writeHead(303, {
Location:
(request.client.tls ? 'https://' : 'http://') +
request.headers.host +
'/',
'Content-Length': '0',
});
}
response.end();
return;
@ -133,22 +167,23 @@ function handler(request, response) {
let sessionIsNew = false;
let loginError;
if (request.method == "POST" || formData.submit) {
if (request.method == 'POST' || formData.submit) {
sessionIsNew = true;
formData = form.decodeForm(utf8Decode(request.body), formData);
if (formData.submit == "Login") {
let account = gDatabase.get("user:" + formData.name);
if (formData.submit == 'Login') {
let account = gDatabase.get('user:' + formData.name);
account = account ? JSON.parse(account) : account;
if (formData.register == '1') {
if (!account &&
if (
!account &&
isNameValid(formData.name) &&
formData.password == formData.confirm) {
formData.password == formData.confirm
) {
let users = new Set();
let users_original = gDatabase.get('users');
try {
users = new Set(JSON.parse(users_original));
} catch {
}
} catch {}
if (!users.has(formData.name)) {
users.add(formData.name);
}
@ -166,10 +201,12 @@ function handler(request, response) {
loginError = 'Error registering account.';
}
} else if (formData.change == '1') {
if (account &&
if (
account &&
isNameValid(formData.name) &&
formData.new_password == formData.confirm &&
verifyPassword(formData.password, account.password)) {
verifyPassword(formData.password, account.password)
) {
session = makeJwt({name: formData.name});
account = {password: hashPassword(formData.new_password)};
gDatabase.set('user:' + formData.name, JSON.stringify(account));
@ -177,9 +214,11 @@ function handler(request, response) {
loginError = 'Error changing password.';
}
} else {
if (account &&
if (
account &&
account.password &&
verifyPassword(formData.password, account.password)) {
verifyPassword(formData.password, account.password)
) {
session = makeJwt({name: formData.name});
if (noAdministrator()) {
makeAdministrator(formData.name);
@ -197,32 +236,52 @@ function handler(request, response) {
let cookie = `session=${session}; path=/; Max-Age=${kRefreshInterval}; ${request.client.tls ? 'Secure; ' : ''}SameSite=Strict; HttpOnly`;
let entry = readSession(session);
if (entry && formData.return) {
response.writeHead(303, {"Location": formData.return, "Set-Cookie": cookie});
response.writeHead(303, {
Location: formData.return,
'Set-Cookie': cookie,
});
response.end();
} else {
File.readFile("core/auth.html").then(function(data) {
let html = utf8Decode(data);
let auth_data = {
session_is_new: sessionIsNew,
name: entry?.name,
error: loginError,
code_of_conduct: core.globalSettings.code_of_conduct,
have_administrator: !noAdministrator(),
};
html = utf8Encode(html.replace('$AUTH_DATA', JSON.stringify(auth_data)));
response.writeHead(200, {"Content-Type": "text/html; charset=utf-8", "Set-Cookie": cookie, "Content-Length": html.length});
response.end(html);
}).catch(function(error) {
response.writeHead(404, {"Content-Type": "text/plain; charset=utf-8", "Connection": "close"});
response.end("404 File not found");
});
File.readFile('core/auth.html')
.then(function (data) {
let html = utf8Decode(data);
let auth_data = {
session_is_new: sessionIsNew,
name: entry?.name,
error: loginError,
code_of_conduct: core.globalSettings.code_of_conduct,
have_administrator: !noAdministrator(),
};
html = utf8Encode(
html.replace('$AUTH_DATA', JSON.stringify(auth_data))
);
response.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'Set-Cookie': cookie,
'Content-Length': html.length,
});
response.end(html);
})
.catch(function (error) {
response.writeHead(404, {
'Content-Type': 'text/plain; charset=utf-8',
Connection: 'close',
});
response.end('404 File not found');
});
}
} else if (request.uri == "/login/logout") {
response.writeHead(303, {"Set-Cookie": `session=; path=/; ${request.client.tls ? 'Secure; ' : ''}SameSite=Strict; expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly`, "Location": "/login" + (request.query ? "?" + request.query : "")});
} else if (request.uri == '/login/logout') {
response.writeHead(303, {
'Set-Cookie': `session=; path=/; ${request.client.tls ? 'Secure; ' : ''}SameSite=Strict; expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly`,
Location: '/login' + (request.query ? '?' + request.query : ''),
});
response.end();
} else {
response.writeHead(200, {"Content-Type": "text/plain; charset=utf-8", "Connection": "close"});
response.end("Hello, " + request.client.peerName + ".");
response.writeHead(200, {
'Content-Type': 'text/plain; charset=utf-8',
Connection: 'close',
});
response.end('Hello, ' + request.client.peerName + '.');
}
}
@ -231,14 +290,18 @@ function getPermissions(session) {
let entry = readSession(session);
if (entry) {
permissions = getPermissionsForUser(entry.name);
permissions.authenticated = entry.name !== "guest";
permissions.authenticated = entry.name !== 'guest';
}
return permissions || {};
}
function getPermissionsForUser(userName) {
let permissions = {};
if (core.globalSettings && core.globalSettings.permissions && core.globalSettings.permissions[userName]) {
if (
core.globalSettings &&
core.globalSettings.permissions &&
core.globalSettings.permissions[userName]
) {
for (let i in core.globalSettings.permissions[userName]) {
permissions[core.globalSettings.permissions[userName][i]] = true;
}
@ -250,10 +313,12 @@ function query(headers) {
let session = getCookies(headers).session;
let entry;
let autologin = tildefriends.args.autologin;
if (entry = autologin ? {name: autologin} : readSession(session)) {
if ((entry = autologin ? {name: autologin} : readSession(session))) {
return {
session: entry,
permissions: autologin ? getPermissionsForUser(autologin) : getPermissions(session),
permissions: autologin
? getPermissionsForUser(autologin)
: getPermissions(session),
};
}
}
@ -267,4 +332,4 @@ function make_refresh(credentials) {
}
}
export { handler, query, make_refresh };
export {handler, query, make_refresh};