Borrow ESLint inspiration from AirBNB.

This commit is contained in:
Andrew Pietila 2023-10-08 23:14:04 -05:00
parent de41020b61
commit 4bb28d1c00
34 changed files with 1438 additions and 322 deletions

View file

@ -7,7 +7,13 @@
"parserOptions": {
"ecmaVersion": "latest"
},
// "extends": ["eslint:recommended"],
"extends": [
// "eslint:recommended",
// "airbnb-base"
],
"plugins": [
"import"
],
"rules": {
"indent": [
"error",
@ -38,6 +44,51 @@
{
"allowKeywords": false
}
],
"eol-last": "error",
"comma-dangle": [
"error",
"always-multiline"
],
"no-multi-spaces": "error",
"space-in-parens": [
"error",
"never"
],
"import/order": "error",
"no-return-await": "error",
"no-trailing-spaces": "error",
"padded-blocks": [
"error",
"never",
{
"allowSingleLineBlocks": false
}
],
"space-infix-ops": "error",
"radix": [
"error",
"always"
],
"object-curly-spacing": [
"error",
"never"
],
"space-before-function-paren": [
"error",
"always"
],
"one-var": [
"error",
"never"
],
"one-var-declaration-per-line": [
"error",
"always"
],
"template-curly-spacing": [
"error",
"never"
]
}
}

22
app.js
View file

@ -5,27 +5,28 @@ const { glob } = require("glob");
const {match: createPathMatch} = require("path-to-regexp");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const databaseHandler = require("./lib/database-handler");
const qs = require("qs");
const databaseHandler = require("./lib/database-handler");
(async () => {
const app = express();
app.set("query parser", "extended");
app.use(bodyParser.json({ type: "application/*+json",
verify: function (req, _res, buf) {
app.use(bodyParser.json({
type: "application/*+json",
verify (req, _res, buf) {
req.rawBody = buf;
}
},
}));
app.use(bodyParser.json({
verify: function (req, _res, buf) {
verify (req, _res, buf) {
req.rawBody = buf;
}
},
}));
app.use(bodyParser.urlencoded({
extended: false,
verify: function (req, _res, buf) {
verify (req, _res, buf) {
req.rawBody = buf;
}
},
}));
app.use(cookieParser());
const routes = await glob("**/*.js", {
@ -34,7 +35,7 @@ const qs = require("qs");
});
const pathMatches = [];
app.use((req, _res, next) => {
console.log(`${req.path}${req.query?"?":""}${qs.stringify(req.query)}`);
console.log(`${req.path}${Object.keys(req.query).length ? "?" : ""}${qs.stringify(req.query)}`);
const requestUrl = new URL(req.url, "https://example.com/");
let candidateUrl = "";
let secondCandidateUrl = "";
@ -42,7 +43,7 @@ const qs = require("qs");
if (pathMatches[pathMatch](requestUrl.pathname)) {
// If we get an exact match, we don't need to process further.
return next();
} else if ( requestUrl.pathname.endsWith("/") && pathMatches[pathMatch](`${requestUrl.pathname}index`) ) {
} if (requestUrl.pathname.endsWith("/") && pathMatches[pathMatch](`${requestUrl.pathname}index`)) {
// If we end with a /, and the index path matches, lets do the index path, but prioritize the non-index path.
const secondRequestUrl = new URL(requestUrl);
secondRequestUrl.pathname = `${requestUrl.pathname}index`;
@ -66,7 +67,6 @@ const qs = require("qs");
});
for (const routeScript in routes) {
const route = routes[routeScript].replace(/\.js$/, "");
console.log(route);
pathMatches.push(createPathMatch(`/${route}`));
const routeObj = require(`./routes/${route}`);
if (routeObj.route) {

View file

@ -1,5 +1,5 @@
const databaseHandler = require("./database-handler");
const jsonld = require("jsonld");
const databaseHandler = require("./database-handler");
module.exports = {
jsonldCustomLoader: async (url, options) => {
@ -8,7 +8,7 @@ module.exports = {
return {
contextUrl: null,
document: JSON.parse(cache.schema),
documentUrl: url
documentUrl: url,
};
}
// TODO: Write HTTP client handler.
@ -21,14 +21,14 @@ module.exports = {
if (typeof urlOrObj === "string") {
try {
const url = new URL(urlOrObj);
return await jsonld.compact(await jsonld.expand(jsonld.documentLoaders.node()(url)), {});
return jsonld.compact(await jsonld.expand(jsonld.documentLoaders.node()(url)), {});
} catch (e) {
return await jsonld.compact(await jsonld.expand(JSON.parse(urlOrObj)), {});
return jsonld.compact(await jsonld.expand(JSON.parse(urlOrObj)), {});
}
} else {
return await jsonld.compact(await jsonld.expand(urlOrObj), {});
}
return jsonld.compact(await jsonld.expand(urlOrObj), {});
}
},
};
jsonld.documentLoader = module.exports.jsonldCustomLoader;

View file

@ -1,4 +1,5 @@
const db = require("better-sqlite3")("brainz-social.db");
db.pragma("journal_mode = WAL");
module.exports = {
@ -64,8 +65,12 @@ module.exports = {
createCsrfTokenAssociation: (...ids) => {
for (const source_id in ids) {
if (Number.parseInt(ids[source_id], 10) === ids[source_id]) {
for (const destination_id in ids) {
db.prepare("INSERT INTO csrf_token_relations (source_id, destination_id) VALUES (?, ?)").run(source_id, destination_id);
if (Number.parseInt(ids[destination_id], 10) === ids[destination_id]) {
db.prepare("INSERT INTO csrf_token_relations (source_id, destination_id) VALUES (?, ?)").run(ids[source_id], ids[destination_id]);
}
}
}
}
},
@ -99,9 +104,8 @@ module.exports = {
const vapidPrivate = db.prepare("SELECT value FROM config WHERE key = vapid_key_private").get();
if (vapidPublic.value && vapidPrivate.value) {
return {public: vapidPublic, private: vapidPrivate};
} else {
return null;
}
return null;
},
setVapidKey: (publicKey, privateKey) => {
@ -139,5 +143,5 @@ module.exports = {
storeW3idSecurityKey: (key_uri, publicKey, privateKey, expires) => {
db.prepare("INSERT INTO w3id_security_keys (key_uri, public_key, private_key) VALUES (?, ?, ?)").run(key_uri, publicKey, privateKey, expires);
}
},
};

View file

@ -17,6 +17,7 @@ module.exports = {
const max_scope_array_temp = max_scope.split(/(\s|\+)+/);
const max_scope_array = [];
for (const scope in max_scope_array_temp) {
if (scope.match(/[a-zA-Z0-9:]/)) {
max_scope_array.push(max_scope_array_temp[scope]);
if (scope === "read") {
max_scope_array.push("read:accounts", "read:blocks", "read:bookmarks", "read:favorites", "read:filters", "read:follows", "read:lists", "read:mutes", "read:notifications", "read:search", "read:statuses");
@ -38,6 +39,7 @@ module.exports = {
max_scope_array.push("admin:write:accounts", "admin:write:reports", "admin:write:domain_allows", "admin:write:domain_blocks", "admin:write:ip_blocks", "admin:write:email_domain_blocks", "admin:write:canonical_email_blocks");
}
}
}
const scope_requested_array = scope_requested.split(/(\s|\+)+/);
@ -50,5 +52,5 @@ module.exports = {
}
return true;
}
},
};

View file

@ -8,7 +8,7 @@ module.exports = {
if (!token) {
res.status(401);
res.json({
error: "UNAUTHENTICATED"
error: "UNAUTHENTICATED",
});
res.end();
return;
@ -17,7 +17,7 @@ module.exports = {
if (token.revoked) {
res.status(401);
res.json({
error: "UNAUTHENTICATED"
error: "UNAUTHENTICATED",
});
res.end();
return;
@ -26,7 +26,7 @@ module.exports = {
if (needs_user && token.user_id === 0) {
res.status(401);
res.json({
error: "INSUFFICIENT_AUTHENTICATION"
error: "INSUFFICIENT_AUTHENTICATION",
});
res.end();
return;
@ -35,7 +35,7 @@ module.exports = {
if (!input_validate(token.scopes, need_scopes)) {
res.status(401);
res.json({
error: "INSUFFICIENT_SCOPE"
error: "INSUFFICIENT_SCOPE",
});
res.end();
return;
@ -49,5 +49,5 @@ module.exports = {
next();
};
}
},
};

View file

@ -25,19 +25,19 @@ exports.up = function(db, callback) {
scopes: "string",
website: "string",
client_id: {type: "string", unique: true},
client_secret: "string"
client_secret: "string",
}),
db.addIndex.bind(db, "applications", "clientIdIndex", ["client_id"], true)
db.addIndex.bind(db, "applications", "clientIdIndex", ["client_id"], true),
], callback);
};
exports.down = function (db, callback) {
async.series([
db.removeIndex.bind(db, "applications", "clientIdIndex"),
db.dropTable.bind(db, "applications")
db.dropTable.bind(db, "applications"),
], callback);
};
exports._meta = {
version: 1
version: 1,
};

View file

@ -18,7 +18,7 @@ exports.up = function(db) {
return db.createTable("config", {
id: {type: "int", primaryKey: true, autoIncrement: true},
key: {type: "string", unique: true},
value: "string"
value: "string",
});
};
@ -27,5 +27,5 @@ exports.down = function(db) {
};
exports._meta = {
version: 1
version: 1,
};

View file

@ -25,10 +25,10 @@ exports.up = function(db, callback) {
scopes: "string",
user_id: "int",
revoked: "boolean",
created_at: "int"
created_at: "int",
}),
db.addIndex.bind(db, "oauth_tokens", "oauth_token_index", ["token"]),
db.addIndex.bind(db, "oauth_tokens", "oauth_token_user_id_index", ["user_id"])
db.addIndex.bind(db, "oauth_tokens", "oauth_token_user_id_index", ["user_id"]),
], callback);
};
@ -36,10 +36,10 @@ exports.down = function(db, callback) {
async.series([
db.removeIndex.bind(db, "oauth_tokens", "oauth_token_user_id_index"),
db.removeIndex.bind(db, "oauth_tokens", "oauth_token_index"),
db.dropTable("oauth_tokens")
db.dropTable("oauth_tokens"),
], callback);
};
exports._meta = {
version: 1
version: 1,
};

View file

@ -20,7 +20,7 @@ exports.up = function(db, callback) {
username: {type: "string", unique: true},
email: "string",
password_hash: "string",
account_tier: "int"
account_tier: "int",
}, (result) => {
if (result) {
callback(result);
@ -35,5 +35,5 @@ exports.down = function(db) {
};
exports._meta = {
version: 1
version: 1,
};

View file

@ -23,19 +23,19 @@ exports.up = function(db, callback) {
cookie_value: {type: "string", unique: true},
created_at: "int",
user_id: "int",
revoked: "boolean"
revoked: "boolean",
}),
db.addIndex.bind(db, "cookies", "cookies_cookie_value_index", ["cookie_value"])
db.addIndex.bind(db, "cookies", "cookies_cookie_value_index", ["cookie_value"]),
], callback);
};
exports.down = function (db, callback) {
async.series([
db.removeIndex.bind(db, "cookies", "cookies_cookie_value_index"),
db.dropTable.bind(db, "cookies")
db.dropTable.bind(db, "cookies"),
], callback);
};
exports._meta = {
version: 1
version: 1,
};

View file

@ -18,7 +18,7 @@ exports.up = function(db) {
return db.createTable("csrf_token", {
id: {type: "int", primaryKey: true, autoIncrement: true},
url: "string",
created_at: "int"
created_at: "int",
});
};
@ -27,5 +27,5 @@ exports.down = function(db) {
};
exports._meta = {
version: 1
version: 1,
};

View file

@ -18,7 +18,7 @@ exports.up = function(db) {
return db.createTable("csrf_token_relations", {
id: {type: "int", primaryKey: true, autoIncrement: true},
source_id: "int",
destination_id: "int"
destination_id: "int",
});
};
@ -27,5 +27,5 @@ exports.down = function(db) {
};
exports._meta = {
version: 1
version: 1,
};

View file

@ -23,5 +23,5 @@ exports.down = function(db) {
};
exports._meta = {
version: 1
version: 1,
};

View file

@ -24,19 +24,19 @@ exports.up = function(db, callback) {
application_id: "int",
scopes: "string",
user_id: "int",
created_at: "int"
created_at: "int",
}),
db.addIndex.bind(db, "oauth_code", "oauth_code_index", ["code"])
db.addIndex.bind(db, "oauth_code", "oauth_code_index", ["code"]),
], callback);
};
exports.down = function (db, callback) {
async.series([
db.removeIndex.bind(db, "oauth_code", "oauth_code_index"),
db.dropTable.bind(db, "oauth_code")
db.dropTable.bind(db, "oauth_code"),
], callback);
};
exports._meta = {
version: 1
version: 1,
};

View file

@ -23,5 +23,5 @@ exports.down = function(db) {
};
exports._meta = {
version: 1
version: 1,
};

View file

@ -19,7 +19,7 @@ exports.up = function(db) {
id: {type: "int", primaryKey: true, autoIncrements: true},
schema_uri: "string",
schema: "string",
expires: "int"
expires: "int",
});
};
@ -28,5 +28,5 @@ exports.down = function(db) {
};
exports._meta = {
version: 1
version: 1,
};

View file

@ -21,7 +21,7 @@ exports.up = function(db) {
type: "string",
local: "boolean",
uri_id: "string",
owner: "string"
owner: "string",
});
};
@ -30,5 +30,5 @@ exports.down = function(db) {
};
exports._meta = {
version: 1
version: 1,
};

View file

@ -23,5 +23,5 @@ exports.down = function(db) {
};
exports._meta = {
version: 1
version: 1,
};

View file

@ -20,7 +20,7 @@ exports.up = function(db) {
key_uri: "string",
public_key: "string",
private_key: "string",
expires: "int"
expires: "int",
});
};
@ -29,5 +29,5 @@ exports.down = function(db) {
};
exports._meta = {
version: 1
version: 1,
};

1080
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -9,6 +9,7 @@
"author": "Andrew Pietila <a.pietila@protonmail.com>",
"license": "WTFPL",
"dependencies": {
"async": "^3.2.4",
"bcrypt": "^5.1.1",
"better-sqlite3": "^8.6.0",
"body-parser": "^1.20.2",
@ -24,6 +25,8 @@
},
"type": "commonjs",
"devDependencies": {
"eslint": "^8.50.0"
"eslint": "^8.51.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-plugin-import": "^2.28.1"
}
}

View file

@ -41,8 +41,8 @@ module.exports = {
access_token: userToken,
token_type: "Bearer",
scope: application.scopes,
created_at
created_at,
});
});
})
}),
};

View file

@ -16,12 +16,12 @@ module.exports = {
modulusLength: 4096,
publicKeyEncoding: {
type: "spki",
format: "pem"
format: "pem",
},
privateKeyEncoding: {
type: "pkcs8",
format: "pem"
}
format: "pem",
},
});
databaseHandler.storeW3idSecurityKey(`https://${req.headers.host}/users/${account.username}#main-key`, keyPair.publicKey, keyPair.privateKey, (Math.floor(Date.now() / 1000) + (86400 * 90)));
@ -30,60 +30,60 @@ module.exports = {
"@id": `https://${req.headers.host}/users/${account.username}`,
"@type": "https://www.w3.org/ns/activitystreams#Person",
"http://joinmastodon.org/ns#devices": {
"@id": `https://${req.headers.host}/users/${account.username}/collections/devices`
"@id": `https://${req.headers.host}/users/${account.username}/collections/devices`,
},
"http://joinmastodon.org/ns#discoverable": true,
"http://joinmastodon.org/ns#featured": {
"@id": `https://${req.headers.host}/users/${account.username}/collections/featured`
"@id": `https://${req.headers.host}/users/${account.username}/collections/featured`,
},
"http://joinmastodon.org/ns#featuredTags": {
"@id": `https://${req.headers.host}/users/${account.username}/collections/tags`
"@id": `https://${req.headers.host}/users/${account.username}/collections/tags`,
},
"http://joinmastodon.org/ns#indexable": true,
"http://joinmastodon.org/ns#memorial": false,
"http://www.w3.org/ns/ldp#inbox": {
"@id": `https://${req.headers.host}/users/${account.username}/inbox`
"@id": `https://${req.headers.host}/users/${account.username}/inbox`,
},
"https://w3id.org/security#publicKey": {
"@id": `https://${req.headers.host}/users/${account.username}#main-key`,
"https://w3id.org/security#owner": {
"@id": `https://${req.headers.host}/users/${account.username}`
"@id": `https://${req.headers.host}/users/${account.username}`,
},
"https://w3id.org/security#publicKeyPem": keyPair.publicKey
"https://w3id.org/security#publicKeyPem": keyPair.publicKey,
},
"https://www.w3.org/ns/activitystreams#endpoints": {
"https://www.w3.org/ns/activitystreams#sharedInbox": {
"@id": `https://${req.headers.host}/inbox`
}
"@id": `https://${req.headers.host}/inbox`,
},
},
"https://www.w3.org/ns/activitystreams#followers": {
"@id": `https://${req.headers.host}/users/${account.username}/followers`
"@id": `https://${req.headers.host}/users/${account.username}/followers`,
},
"https://www.w3.org/ns/activitystreams#following": {
"@id": `https://${req.headers.host}/users/${account.username}/following`
"@id": `https://${req.headers.host}/users/${account.username}/following`,
},
"https://www.w3.org/ns/activitystreams#icon": {
"@type": "https://www.w3.org/ns/activitystreams#Image",
"https://www.w3.org/ns/activitystreams#mediaType": "image/png",
"https://www.w3.org/ns/activitystreams#url": {
"@id": `https://${req.headers.host}/res/avatar_not_found.png`
}
"@id": `https://${req.headers.host}/res/avatar_not_found.png`,
},
},
"https://www.w3.org/ns/activitystreams#manuallyApprovesFollowers": false,
"https://www.w3.org/ns/activitystreams#name": account.username,
"https://www.w3.org/ns/activitystreams#outbox": {
"@id": `https://${req.headers.host}/users/${account.username}/outbox`
"@id": `https://${req.headers.host}/users/${account.username}/outbox`,
},
"https://www.w3.org/ns/activitystreams#preferredUsername": account.username,
"https://www.w3.org/ns/activitystreams#published": {
"@type": "http://www.w3.org/2001/XMLSchema#dateTime",
"@value": new Date(Date.now()).toISOString()
"@value": new Date(Date.now()).toISOString(),
},
"https://www.w3.org/ns/activitystreams#summary": "",
"https://www.w3.org/ns/activitystreams#tag": [],
"https://www.w3.org/ns/activitystreams#url": {
"@id": `https://${req.headers.host}/@${account.username}`
}
"@id": `https://${req.headers.host}/@${account.username}`,
},
};
}
res.status(200);
@ -113,10 +113,10 @@ module.exports = {
fields: [],
privacy: "public",
sensitive: false,
language: "en"
}
language: "en",
},
});
return;
});
}
},
};

View file

@ -1,7 +1,7 @@
const crypto = require("crypto");
const webpush = require("web-push");
const database_handler = require("../../../lib/database-handler");
const input_validate = require("../../../lib/input_validate");
const webpush = require("web-push");
module.exports = {
route: ((routeObj) => {
@ -13,7 +13,8 @@ module.exports = {
return;
}
let scopes, website;
let scopes;
let website;
const client_name = req.body.client_name;
const redirect_uris = req.body.redirect_uris;
@ -69,10 +70,10 @@ module.exports = {
website,
vapid_key,
client_id,
client_secret
client_secret,
});
return;
});
})
}),
};

View file

@ -1,6 +1,6 @@
const webpush = require("web-push");
const databaseHandler = require("../../../../lib/database-handler");
const auth_middleware = require("../../../../middleware/auth");
const webpush = require("web-push");
module.exports = {
route: (routeObj) => {
@ -22,9 +22,9 @@ module.exports = {
res.json({
name: application.name,
website: application.website,
vapid_key: vapid_key["public"]
vapid_key: vapid_key["public"],
});
return;
});
}
},
};

View file

@ -5,5 +5,5 @@ module.exports = {
res.json({});
return;
});
}
},
};

View file

@ -1,7 +1,7 @@
const databaseHandler = require("../lib/database-handler");
const crypto = require("crypto");
const input_validate = require("../lib/input_validate");
const bcrypt = require("bcrypt");
const databaseHandler = require("../lib/database-handler");
const input_validate = require("../lib/input_validate");
module.exports = {
route: (routeObj) => {
@ -90,5 +90,5 @@ module.exports = {
res.end();
return;
});
}
},
};

View file

@ -6,7 +6,7 @@ module.exports = {
version: 2.0,
software: {
name: "Brainz Social",
version: "0.0.1"
version: "0.0.1",
},
protocols: [],
services: [],
@ -15,13 +15,13 @@ module.exports = {
users: {
total: 0,
activeHalfYear: 0,
activeMonth: 0
activeMonth: 0,
},
localPosts: 0,
localComments: 0
localComments: 0,
},
metadata: {}
metadata: {},
});
});
}
},
};

View file

@ -1,7 +1,7 @@
const crypto = require("crypto");
const qs = require("qs");
const databaseHandler = require("../../lib/database-handler");
const input_validate = require("../../lib/input_validate");
const qs = require("qs");
module.exports = {
route: (routeObj) => {
@ -43,7 +43,7 @@ module.exports = {
res.send(`<html><body>Error: invalid scopes requested. Contact the author of ${application_obj.client_name} to correct their scope request.</body></html>`);
res.end();
return;
} else {
}
res.status(200);
res.cookie("auth", new_cookie_value);
const approve_url = new URL("http://example.com");
@ -66,7 +66,6 @@ module.exports = {
res.end();
return;
}
} else {
const new_redirect_url = new URL("http://example.com");
new_redirect_url.host = req.headers.host;
new_redirect_url.pathname = req.path;
@ -79,7 +78,6 @@ module.exports = {
res.redirect(redirecting_to.toString());
res.end();
}
}
});
}
},
};

View file

@ -1,6 +1,6 @@
const crypto = require("crypto");
const databaseHandler = require("../../../lib/database-handler");
const qs = require("qs");
const databaseHandler = require("../../../lib/database-handler");
module.exports = {
route: (routeObj) => {
@ -54,5 +54,5 @@ module.exports = {
res.end();
return;
});
}
},
};

View file

@ -30,5 +30,5 @@ module.exports = {
res.status(200);
res.json({});
});
}
},
};

View file

@ -29,7 +29,6 @@ module.exports = {
const application = databaseHandler.getApplication(client_id);
if (!application.client_id) {
console.log("UNREGISTERED");
res.status(422);
res.json({error: "UNREGISTERED_APPLICATION"});
res.end();
@ -76,10 +75,10 @@ module.exports = {
access_token: token,
token_type: "Bearer",
scope: req.query.scope,
created_at
created_at,
});
return;
} else if ( grant_type !== "client_credentials" ) {
} if (grant_type !== "client_credentials") {
res.status(422);
res.json({error: "Validation failed, unrecognized grant_type"});
return;
@ -93,8 +92,8 @@ module.exports = {
access_token: token,
token_type: "Bearer",
scope,
created_at
created_at,
});
});
}
},
};