backend: fix lint "no-throw-literal"

This commit is contained in:
Johann150 2022-08-04 11:00:02 +02:00
parent e2bf2715a6
commit 09a7eabda1
Signed by untrusted user: Johann150
GPG key ID: 9EE6577A2A06F8F1
19 changed files with 36 additions and 36 deletions

View file

@ -110,13 +110,12 @@ function loadConfigBoot(): Config {
try { try {
config = loadConfig(); config = loadConfig();
} catch (exception) { } catch (exception) {
if (typeof exception === 'string') {
configLogger.error(exception);
process.exit(1);
}
if (exception.code === 'ENOENT') { if (exception.code === 'ENOENT') {
configLogger.error('Configuration file not found', null, true); configLogger.error('Configuration file not found', null, true);
process.exit(1); process.exit(1);
} else if (e instanceof Error) {
configLogger.error(e.message);
process.exit(1);
} }
throw exception; throw exception;
} }

View file

@ -59,6 +59,6 @@ function tryCreateUrl(url: string) {
try { try {
return new URL(url); return new URL(url);
} catch (e) { } catch (e) {
throw `url="${url}" is not a valid URL.`; throw new Error(`url="${url}" is not a valid URL.`);
} }
} }

View file

@ -5,23 +5,23 @@ import { getAgentByUrl } from './fetch.js';
export async function verifyRecaptcha(secret: string, response: string) { export async function verifyRecaptcha(secret: string, response: string) {
const result = await getCaptchaResponse('https://www.recaptcha.net/recaptcha/api/siteverify', secret, response).catch(e => { const result = await getCaptchaResponse('https://www.recaptcha.net/recaptcha/api/siteverify', secret, response).catch(e => {
throw `recaptcha-request-failed: ${e}`; throw new Error(`recaptcha-request-failed: ${e.message}`);
}); });
if (result.success !== true) { if (result.success !== true) {
const errorCodes = result['error-codes'] ? result['error-codes']?.join(', ') : ''; const errorCodes = result['error-codes'] ? result['error-codes']?.join(', ') : '';
throw `recaptcha-failed: ${errorCodes}`; throw new Error(`recaptcha-failed: ${errorCodes}`);
} }
} }
export async function verifyHcaptcha(secret: string, response: string) { export async function verifyHcaptcha(secret: string, response: string) {
const result = await getCaptchaResponse('https://hcaptcha.com/siteverify', secret, response).catch(e => { const result = await getCaptchaResponse('https://hcaptcha.com/siteverify', secret, response).catch(e => {
throw `hcaptcha-request-failed: ${e}`; throw new Error(`hcaptcha-request-failed: ${e.message}`);
}); });
if (result.success !== true) { if (result.success !== true) {
const errorCodes = result['error-codes'] ? result['error-codes']?.join(', ') : ''; const errorCodes = result['error-codes'] ? result['error-codes']?.join(', ') : '';
throw `hcaptcha-failed: ${errorCodes}`; throw new Error(`hcaptcha-failed: ${errorCodes}`);
} }
} }
@ -46,11 +46,11 @@ async function getCaptchaResponse(url: string, secret: string, response: string)
//timeout: 10 * 1000, //timeout: 10 * 1000,
agent: getAgentByUrl, agent: getAgentByUrl,
}).catch(e => { }).catch(e => {
throw `${e.message || e}`; throw new Error(`${e.message || e}`);
}); });
if (!res.ok) { if (!res.ok) {
throw `${res.status}`; throw new Error(`${res.status}`);
} }
return await res.json() as CaptchaResponse; return await res.json() as CaptchaResponse;

View file

@ -13,7 +13,7 @@ export function genId(date?: Date): string {
let t = date.getTime(); let t = date.getTime();
t -= TIME2000; t -= TIME2000;
if (t < 0) t = 0; if (t < 0) t = 0;
if (isNaN(t)) throw 'Failed to create AID: Invalid Date'; if (isNaN(t)) throw new Error('Failed to create AID: Invalid Date');
const time = t.toString(36).padStart(8, '0'); const time = t.toString(36).padStart(8, '0');
counter++; counter++;

View file

@ -13,7 +13,7 @@ export function dateUTC(time: number[]): Date {
: time.length === 7 ? Date.UTC(time[0], time[1], time[2], time[3], time[4], time[5], time[6]) : time.length === 7 ? Date.UTC(time[0], time[1], time[2], time[3], time[4], time[5], time[6])
: null; : null;
if (!d) throw 'wrong number of arguments'; if (!d) throw new Error('wrong number of arguments');
return new Date(d); return new Date(d);
} }

View file

@ -55,7 +55,7 @@ export async function importBlocking(job: Bull.Job<DbUserImportJobData>, done: a
} }
if (target == null) { if (target == null) {
throw `cannot resolve user: @${username}@${host}`; throw new Error(`cannot resolve user: @${username}@${host}`);
} }
// skip myself // skip myself

View file

@ -55,7 +55,7 @@ export async function importFollowing(job: Bull.Job<DbUserImportJobData>, done:
} }
if (target == null) { if (target == null) {
throw `cannot resolve user: @${username}@${host}`; throw new Error(`cannot resolve user: @${username}@${host}`);
} }
// skip myself // skip myself

View file

@ -56,7 +56,7 @@ export async function importMuting(job: Bull.Job<DbUserImportJobData>, done: any
} }
if (target == null) { if (target == null) {
throw `cannot resolve user: @${username}@${host}`; throw new Error(`cannot resolve user: @${username}@${host}`);
} }
// skip myself // skip myself

View file

@ -89,7 +89,7 @@ export default async (job: Bull.Job<DeliverJobData>) => {
} }
// 5xx etc. // 5xx etc.
throw `${res.statusCode} ${res.statusMessage}`; throw new Error(`${res.statusCode} ${res.statusMessage}`);
} else { } else {
// DNS error, socket error, timeout ... // DNS error, socket error, timeout ...
throw res; throw res;

View file

@ -62,7 +62,7 @@ export default async (job: Bull.Job<InboxJobData>): Promise<string> => {
if (e.isClientError) { if (e.isClientError) {
return `skip: Ignored deleted actors on both ends ${activity.actor} - ${e.statusCode}`; return `skip: Ignored deleted actors on both ends ${activity.actor} - ${e.statusCode}`;
} }
throw `Error in actor ${activity.actor} - ${e.statusCode || e}`; throw new Error(`Error in actor ${activity.actor} - ${e.statusCode || e}`);
} }
} }
} }

View file

@ -49,7 +49,7 @@ export default async (job: Bull.Job<WebhookDeliverJobData>) => {
} }
// 5xx etc. // 5xx etc.
throw `${res.statusCode} ${res.statusMessage}`; throw new Error(`${res.statusCode} ${res.statusMessage}`);
} else { } else {
// DNS error, socket error, timeout ... // DNS error, socket error, timeout ...
throw res; throw res;

View file

@ -85,7 +85,7 @@ export class LdSignature {
private getLoader() { private getLoader() {
return async (url: string): Promise<any> => { return async (url: string): Promise<any> => {
if (!url.match('^https?\:\/\/')) throw `Invalid URL ${url}`; if (!url.match('^https?\:\/\/')) throw new Error(`Invalid URL ${url}`);
if (this.preLoad) { if (this.preLoad) {
if (url in CONTEXTS) { if (url in CONTEXTS) {
@ -118,7 +118,7 @@ export class LdSignature {
agent: u => u.protocol === 'http:' ? httpAgent : httpsAgent, agent: u => u.protocol === 'http:' ? httpAgent : httpsAgent,
}).then(res => { }).then(res => {
if (!res.ok) { if (!res.ok) {
throw `${res.status} ${res.statusText}`; throw new Error(`${res.status} ${res.statusText}`);
} else { } else {
return res.json(); return res.json();
} }

View file

@ -189,7 +189,7 @@ export async function createNote(value: string | IObject, resolver?: Resolver, s
quote = results.filter((x): x is { status: 'ok', res: Note | null } => x.status === 'ok').map(x => x.res).find(x => x); quote = results.filter((x): x is { status: 'ok', res: Note | null } => x.status === 'ok').map(x => x.res).find(x => x);
if (!quote) { if (!quote) {
if (results.some(x => x.status === 'temperror')) { if (results.some(x => x.status === 'temperror')) {
throw 'quote resolve failed'; throw new Error('quote resolve failed');
} }
} }
} }
@ -276,7 +276,7 @@ export async function resolveNote(value: string | IObject, resolver?: Resolver):
// ブロックしてたら中断 // ブロックしてたら中断
const meta = await fetchMeta(); const meta = await fetchMeta();
if (meta.blockedHosts.includes(extractDbHost(uri))) throw { statusCode: 451 }; if (meta.blockedHosts.includes(extractDbHost(uri))) throw new StatusError('host blocked', 451, `host ${extractDbHost(uri)} is blocked`);
const unlock = await getApLock(uri); const unlock = await getApLock(uri);

View file

@ -27,6 +27,7 @@ export const meta = {
format: 'id', format: 'id',
}, },
inbox: { inbox: {
description: 'URL of the inbox, must be a https scheme URL',
type: 'string', type: 'string',
optional: false, nullable: false, optional: false, nullable: false,
format: 'url', format: 'url',
@ -56,7 +57,7 @@ export const paramDef = {
// eslint-disable-next-line import/no-default-export // eslint-disable-next-line import/no-default-export
export default define(meta, paramDef, async (ps, user) => { export default define(meta, paramDef, async (ps, user) => {
try { try {
if (new URL(ps.inbox).protocol !== 'https:') throw 'https only'; if (new URL(ps.inbox).protocol !== 'https:') throw new Error('https only');
} catch { } catch {
throw new ApiError(meta.errors.invalidUrl); throw new ApiError(meta.errors.invalidUrl);
} }

View file

@ -68,7 +68,7 @@ async function unFollowAll(follower: User) {
}); });
if (followee == null) { if (followee == null) {
throw `Cant find followee ${following.followeeId}`; throw new Error(`Cant find followee ${following.followeeId}`);
} }
await deleteFollowing(follower, followee, true); await deleteFollowing(follower, followee, true);

View file

@ -86,14 +86,14 @@ export default define(meta, paramDef, async (ps, me) => {
try { try {
if (ps.tag) { if (ps.tag) {
if (!safeForSql(ps.tag)) throw 'Injection'; if (!safeForSql(ps.tag)) throw new Error('Injection');
query.andWhere(`'{"${normalizeForSearch(ps.tag)}"}' <@ note.tags`); query.andWhere(`'{"${normalizeForSearch(ps.tag)}"}' <@ note.tags`);
} else { } else {
query.andWhere(new Brackets(qb => { query.andWhere(new Brackets(qb => {
for (const tags of ps.query!) { for (const tags of ps.query!) {
qb.orWhere(new Brackets(qb => { qb.orWhere(new Brackets(qb => {
for (const tag of tags) { for (const tag of tags) {
if (!safeForSql(tag)) throw 'Injection'; if (!safeForSql(tag)) throw new Error('Injection');
qb.andWhere(`'{"${normalizeForSearch(tag)}"}' <@ note.tags`); qb.andWhere(`'{"${normalizeForSearch(tag)}"}' <@ note.tags`);
} }
})); }));
@ -101,7 +101,7 @@ export default define(meta, paramDef, async (ps, me) => {
})); }));
} }
} catch (e) { } catch (e) {
if (e === 'Injection') return []; if (e.message === 'Injection') return [];
throw e; throw e;
} }

View file

@ -21,7 +21,7 @@ export const paramDef = {
// eslint-disable-next-line import/no-default-export // eslint-disable-next-line import/no-default-export
export default define(meta, paramDef, async (ps, user) => { export default define(meta, paramDef, async (ps, user) => {
if (process.env.NODE_ENV !== 'test') throw 'NODE_ENV is not a test'; if (process.env.NODE_ENV !== 'test') throw new Error('NODE_ENV is not a test');
await resetDb(); await resetDb();

View file

@ -94,14 +94,14 @@ async function fetchNodeinfo(instance: Instance): Promise<NodeInfo> {
const wellknown = await getJson('https://' + instance.host + '/.well-known/nodeinfo') const wellknown = await getJson('https://' + instance.host + '/.well-known/nodeinfo')
.catch(e => { .catch(e => {
if (e.statusCode === 404) { if (e.statusCode === 404) {
throw 'No nodeinfo provided'; throw new Error('No nodeinfo provided');
} else { } else {
throw e.statusCode || e.message; throw new Error(e.statusCode || e.message);
} }
}) as Record<string, unknown>; }) as Record<string, unknown>;
if (wellknown.links == null || !Array.isArray(wellknown.links)) { if (wellknown.links == null || !Array.isArray(wellknown.links)) {
throw 'No wellknown links'; throw new Error('No wellknown links');
} }
const links = wellknown.links as any[]; const links = wellknown.links as any[];
@ -112,19 +112,19 @@ async function fetchNodeinfo(instance: Instance): Promise<NodeInfo> {
const link = lnik2_1 || lnik2_0 || lnik1_0; const link = lnik2_1 || lnik2_0 || lnik1_0;
if (link == null) { if (link == null) {
throw 'No nodeinfo link provided'; throw new Error('No nodeinfo link provided');
} }
const info = await getJson(link.href) const info = await getJson(link.href)
.catch(e => { .catch(e => {
throw e.statusCode || e.message; throw new Error(e.statusCode || e.message);
}); });
logger.succ(`Successfuly fetched nodeinfo of ${instance.host}`); logger.succ(`Successfuly fetched nodeinfo of ${instance.host}`);
return info as NodeInfo; return info as NodeInfo;
} catch (e) { } catch (e) {
logger.error(`Failed to fetch nodeinfo of ${instance.host}: ${e}`); logger.error(`Failed to fetch nodeinfo of ${instance.host}: ${e.message}`);
throw e; throw e;
} }

View file

@ -47,7 +47,7 @@ export async function removeRelay(inbox: string) {
}); });
if (relay == null) { if (relay == null) {
throw 'relay not found'; throw new Error('relay not found');
} }
const relayActor = await getRelayActor(); const relayActor = await getRelayActor();