2022-12-03 19:42:05 +09:00
|
|
|
import { pipeline } from 'node:stream';
|
|
|
|
import * as fs from 'node:fs';
|
|
|
|
import { promisify } from 'node:util';
|
2022-09-18 03:27:08 +09:00
|
|
|
import { Inject, Injectable } from '@nestjs/common';
|
2023-02-26 17:12:15 +09:00
|
|
|
import { v4 as uuid } from 'uuid';
|
2022-09-18 03:27:08 +09:00
|
|
|
import { DI } from '@/di-symbols.js';
|
|
|
|
import { getIpHash } from '@/misc/get-ip-hash.js';
|
2023-02-13 15:50:22 +09:00
|
|
|
import type { LocalUser, User } from '@/models/entities/User.js';
|
2022-09-18 03:27:08 +09:00
|
|
|
import type { AccessToken } from '@/models/entities/AccessToken.js';
|
|
|
|
import type Logger from '@/logger.js';
|
2022-09-21 05:33:11 +09:00
|
|
|
import type { UserIpsRepository } from '@/models/index.js';
|
2022-09-18 03:27:08 +09:00
|
|
|
import { MetaService } from '@/core/MetaService.js';
|
2022-12-03 19:42:05 +09:00
|
|
|
import { createTemp } from '@/misc/create-temp.js';
|
2022-12-04 15:03:09 +09:00
|
|
|
import { bindThis } from '@/decorators.js';
|
2023-01-12 21:02:26 +09:00
|
|
|
import { RoleService } from '@/core/RoleService.js';
|
2022-09-18 03:27:08 +09:00
|
|
|
import { ApiError } from './error.js';
|
|
|
|
import { RateLimiterService } from './RateLimiterService.js';
|
|
|
|
import { ApiLoggerService } from './ApiLoggerService.js';
|
|
|
|
import { AuthenticateService, AuthenticationError } from './AuthenticateService.js';
|
2022-12-14 00:01:45 +09:00
|
|
|
import type { FastifyRequest, FastifyReply } from 'fastify';
|
2022-09-18 03:27:08 +09:00
|
|
|
import type { OnApplicationShutdown } from '@nestjs/common';
|
|
|
|
import type { IEndpointMeta, IEndpoint } from './endpoints.js';
|
2022-12-03 19:42:05 +09:00
|
|
|
|
|
|
|
const pump = promisify(pipeline);
|
2022-09-18 03:27:08 +09:00
|
|
|
|
|
|
|
const accessDenied = {
|
|
|
|
message: 'Access denied.',
|
|
|
|
code: 'ACCESS_DENIED',
|
|
|
|
id: '56f35758-7dd5-468b-8439-5d6fb8ec9b8e',
|
|
|
|
};
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class ApiCallService implements OnApplicationShutdown {
|
2022-09-19 03:11:50 +09:00
|
|
|
private logger: Logger;
|
|
|
|
private userIpHistories: Map<User['id'], Set<string>>;
|
|
|
|
private userIpHistoriesClearIntervalId: NodeJS.Timer;
|
2022-09-18 03:27:08 +09:00
|
|
|
|
|
|
|
constructor(
|
|
|
|
@Inject(DI.userIpsRepository)
|
|
|
|
private userIpsRepository: UserIpsRepository,
|
|
|
|
|
|
|
|
private metaService: MetaService,
|
|
|
|
private authenticateService: AuthenticateService,
|
|
|
|
private rateLimiterService: RateLimiterService,
|
2023-01-12 21:02:26 +09:00
|
|
|
private roleService: RoleService,
|
2022-09-18 03:27:08 +09:00
|
|
|
private apiLoggerService: ApiLoggerService,
|
|
|
|
) {
|
2022-09-19 03:11:50 +09:00
|
|
|
this.logger = this.apiLoggerService.logger;
|
|
|
|
this.userIpHistories = new Map<User['id'], Set<string>>();
|
2022-09-18 03:27:08 +09:00
|
|
|
|
2022-09-19 03:11:50 +09:00
|
|
|
this.userIpHistoriesClearIntervalId = setInterval(() => {
|
|
|
|
this.userIpHistories.clear();
|
2022-09-18 03:27:08 +09:00
|
|
|
}, 1000 * 60 * 60);
|
|
|
|
}
|
|
|
|
|
2022-12-04 15:03:09 +09:00
|
|
|
@bindThis
|
2022-12-03 19:42:05 +09:00
|
|
|
public handleRequest(
|
|
|
|
endpoint: IEndpoint & { exec: any },
|
2022-12-19 15:57:36 +09:00
|
|
|
request: FastifyRequest<{ Body: Record<string, unknown> | undefined, Querystring: Record<string, unknown> }>,
|
2022-12-03 19:42:05 +09:00
|
|
|
reply: FastifyReply,
|
|
|
|
) {
|
|
|
|
const body = request.method === 'GET'
|
|
|
|
? request.query
|
|
|
|
: request.body;
|
|
|
|
|
2022-12-19 15:57:36 +09:00
|
|
|
const token = body?.['i'];
|
2022-12-03 19:42:05 +09:00
|
|
|
if (token != null && typeof token !== 'string') {
|
|
|
|
reply.code(400);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
this.authenticateService.authenticate(token).then(([user, app]) => {
|
|
|
|
this.call(endpoint, user, app, body, null, request).then((res) => {
|
2022-12-19 15:57:36 +09:00
|
|
|
if (request.method === 'GET' && endpoint.meta.cacheSec && !body?.['i'] && !user) {
|
2022-12-03 19:42:05 +09:00
|
|
|
reply.header('Cache-Control', `public, max-age=${endpoint.meta.cacheSec}`);
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
2022-12-03 19:42:05 +09:00
|
|
|
this.send(reply, res);
|
|
|
|
}).catch((err: ApiError) => {
|
2023-03-09 14:27:16 +09:00
|
|
|
this.send(reply, err.httpStatusCode ? err.httpStatusCode : err.kind === 'client' ? 400 : err.kind === 'permission' ? 403 : 500, err);
|
2022-09-18 03:27:08 +09:00
|
|
|
});
|
2022-12-03 19:42:05 +09:00
|
|
|
|
|
|
|
if (user) {
|
|
|
|
this.logIp(request, user);
|
|
|
|
}
|
|
|
|
}).catch(err => {
|
|
|
|
if (err instanceof AuthenticationError) {
|
|
|
|
this.send(reply, 403, new ApiError({
|
|
|
|
message: 'Authentication failed. Please ensure your token is correct.',
|
|
|
|
code: 'AUTHENTICATION_FAILED',
|
|
|
|
id: 'b0a7f5f8-dc2f-4171-b91f-de88ad238e14',
|
|
|
|
}));
|
|
|
|
} else {
|
|
|
|
this.send(reply, 500, new ApiError());
|
|
|
|
}
|
2022-09-18 03:27:08 +09:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-12-04 15:03:09 +09:00
|
|
|
@bindThis
|
2022-12-03 19:42:05 +09:00
|
|
|
public async handleMultipartRequest(
|
|
|
|
endpoint: IEndpoint & { exec: any },
|
|
|
|
request: FastifyRequest<{ Body: Record<string, unknown>, Querystring: Record<string, unknown> }>,
|
|
|
|
reply: FastifyReply,
|
|
|
|
) {
|
2023-03-03 11:13:12 +09:00
|
|
|
const multipartData = await request.file().catch(() => {
|
|
|
|
/* Fastify throws if the remote didn't send multipart data. Return 400 below. */
|
|
|
|
});
|
2022-12-03 19:42:05 +09:00
|
|
|
if (multipartData == null) {
|
|
|
|
reply.code(400);
|
2023-03-03 11:13:12 +09:00
|
|
|
reply.send();
|
2022-12-03 19:42:05 +09:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const [path] = await createTemp();
|
|
|
|
await pump(multipartData.file, fs.createWriteStream(path));
|
|
|
|
|
2023-02-20 08:13:37 +09:00
|
|
|
const fields = {} as Record<string, unknown>;
|
2022-12-03 19:42:05 +09:00
|
|
|
for (const [k, v] of Object.entries(multipartData.fields)) {
|
2023-02-20 08:13:37 +09:00
|
|
|
fields[k] = typeof v === 'object' && 'value' in v ? v.value : undefined;
|
2022-12-03 19:42:05 +09:00
|
|
|
}
|
2022-12-19 15:57:36 +09:00
|
|
|
|
2022-12-03 19:42:05 +09:00
|
|
|
const token = fields['i'];
|
|
|
|
if (token != null && typeof token !== 'string') {
|
|
|
|
reply.code(400);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
this.authenticateService.authenticate(token).then(([user, app]) => {
|
|
|
|
this.call(endpoint, user, app, fields, {
|
|
|
|
name: multipartData.filename,
|
|
|
|
path: path,
|
|
|
|
}, request).then((res) => {
|
|
|
|
this.send(reply, res);
|
|
|
|
}).catch((err: ApiError) => {
|
2023-03-09 14:27:16 +09:00
|
|
|
this.send(reply, err.httpStatusCode ? err.httpStatusCode : err.kind === 'client' ? 400 : err.kind === 'permission' ? 403 : 500, err);
|
2022-12-03 19:42:05 +09:00
|
|
|
});
|
|
|
|
|
|
|
|
if (user) {
|
|
|
|
this.logIp(request, user);
|
|
|
|
}
|
|
|
|
}).catch(err => {
|
|
|
|
if (err instanceof AuthenticationError) {
|
|
|
|
this.send(reply, 403, new ApiError({
|
|
|
|
message: 'Authentication failed. Please ensure your token is correct.',
|
|
|
|
code: 'AUTHENTICATION_FAILED',
|
|
|
|
id: 'b0a7f5f8-dc2f-4171-b91f-de88ad238e14',
|
|
|
|
}));
|
|
|
|
} else {
|
|
|
|
this.send(reply, 500, new ApiError());
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-12-04 15:03:09 +09:00
|
|
|
@bindThis
|
2022-12-03 19:42:05 +09:00
|
|
|
private send(reply: FastifyReply, x?: any, y?: ApiError) {
|
|
|
|
if (x == null) {
|
|
|
|
reply.code(204);
|
2022-12-10 15:25:39 +09:00
|
|
|
reply.send();
|
2022-12-03 19:42:05 +09:00
|
|
|
} else if (typeof x === 'number' && y) {
|
|
|
|
reply.code(x);
|
|
|
|
reply.send({
|
|
|
|
error: {
|
|
|
|
message: y!.message,
|
|
|
|
code: y!.code,
|
|
|
|
id: y!.id,
|
|
|
|
kind: y!.kind,
|
|
|
|
...(y!.info ? { info: y!.info } : {}),
|
|
|
|
},
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
// 文字列を返す場合は、JSON.stringify通さないとJSONと認識されない
|
|
|
|
reply.send(typeof x === 'string' ? JSON.stringify(x) : x);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-04 15:03:09 +09:00
|
|
|
@bindThis
|
2023-02-13 15:50:22 +09:00
|
|
|
private async logIp(request: FastifyRequest, user: LocalUser) {
|
2022-12-03 19:42:05 +09:00
|
|
|
const meta = await this.metaService.fetch();
|
|
|
|
if (!meta.enableIpLogging) return;
|
|
|
|
const ip = request.ip;
|
|
|
|
const ips = this.userIpHistories.get(user.id);
|
|
|
|
if (ips == null || !ips.has(ip)) {
|
|
|
|
if (ips == null) {
|
|
|
|
this.userIpHistories.set(user.id, new Set([ip]));
|
|
|
|
} else {
|
|
|
|
ips.add(ip);
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
this.userIpsRepository.createQueryBuilder().insert().values({
|
|
|
|
createdAt: new Date(),
|
|
|
|
userId: user.id,
|
|
|
|
ip: ip,
|
|
|
|
}).orIgnore(true).execute();
|
|
|
|
} catch {
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-04 15:03:09 +09:00
|
|
|
@bindThis
|
2022-09-19 03:11:50 +09:00
|
|
|
private async call(
|
2022-12-03 19:42:05 +09:00
|
|
|
ep: IEndpoint & { exec: any },
|
2023-02-13 15:50:22 +09:00
|
|
|
user: LocalUser | null | undefined,
|
2022-09-18 03:27:08 +09:00
|
|
|
token: AccessToken | null | undefined,
|
|
|
|
data: any,
|
2022-12-03 19:42:05 +09:00
|
|
|
file: {
|
|
|
|
name: string;
|
|
|
|
path: string;
|
|
|
|
} | null,
|
2022-12-19 15:57:36 +09:00
|
|
|
request: FastifyRequest<{ Body: Record<string, unknown> | undefined, Querystring: Record<string, unknown> }>,
|
2022-09-18 03:27:08 +09:00
|
|
|
) {
|
|
|
|
const isSecure = user != null && token == null;
|
|
|
|
|
|
|
|
if (ep.meta.secure && !isSecure) {
|
|
|
|
throw new ApiError(accessDenied);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (ep.meta.limit) {
|
|
|
|
// koa will automatically load the `X-Forwarded-For` header if `proxy: true` is configured in the app.
|
|
|
|
let limitActor: string;
|
|
|
|
if (user) {
|
|
|
|
limitActor = user.id;
|
|
|
|
} else {
|
2022-12-03 19:42:05 +09:00
|
|
|
limitActor = getIpHash(request.ip);
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
const limit = Object.assign({}, ep.meta.limit);
|
|
|
|
|
2023-02-17 15:36:36 +09:00
|
|
|
if (limit.key == null) {
|
|
|
|
(limit as any).key = ep.name;
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
|
2023-01-15 16:52:12 +09:00
|
|
|
// TODO: 毎リクエスト計算するのもあれだしキャッシュしたい
|
2023-01-15 20:52:53 +09:00
|
|
|
const factor = user ? (await this.roleService.getUserPolicies(user.id)).rateLimitFactor : 1;
|
2023-01-15 16:52:12 +09:00
|
|
|
|
2023-02-12 10:26:27 +09:00
|
|
|
if (factor > 0) {
|
|
|
|
// Rate limit
|
|
|
|
await this.rateLimiterService.limit(limit as IEndpointMeta['limit'] & { key: NonNullable<string> }, limitActor, factor).catch(err => {
|
|
|
|
throw new ApiError({
|
|
|
|
message: 'Rate limit exceeded. Please try again later.',
|
|
|
|
code: 'RATE_LIMIT_EXCEEDED',
|
|
|
|
id: 'd5826d14-3982-4d2e-8011-b9e9f02499ef',
|
|
|
|
httpStatusCode: 429,
|
|
|
|
});
|
2022-09-18 03:27:08 +09:00
|
|
|
});
|
2023-02-12 10:26:27 +09:00
|
|
|
}
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
|
2023-01-12 21:02:26 +09:00
|
|
|
if (ep.meta.requireCredential || ep.meta.requireModerator || ep.meta.requireAdmin) {
|
|
|
|
if (user == null) {
|
|
|
|
throw new ApiError({
|
|
|
|
message: 'Credential required.',
|
|
|
|
code: 'CREDENTIAL_REQUIRED',
|
|
|
|
id: '1384574d-a912-4b81-8601-c7b1c4085df1',
|
|
|
|
httpStatusCode: 401,
|
|
|
|
});
|
|
|
|
} else if (user!.isSuspended) {
|
|
|
|
throw new ApiError({
|
|
|
|
message: 'Your account has been suspended.',
|
|
|
|
code: 'YOUR_ACCOUNT_SUSPENDED',
|
|
|
|
id: 'a8c724b3-6e9c-4b46-b1a8-bc3ed6258370',
|
|
|
|
httpStatusCode: 403,
|
|
|
|
});
|
|
|
|
}
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
|
2023-01-12 21:02:26 +09:00
|
|
|
if ((ep.meta.requireModerator || ep.meta.requireAdmin) && !user!.isRoot) {
|
|
|
|
const myRoles = await this.roleService.getUserRoles(user!.id);
|
|
|
|
if (ep.meta.requireModerator && !myRoles.some(r => r.isModerator || r.isAdministrator)) {
|
|
|
|
throw new ApiError({
|
|
|
|
message: 'You are not assigned to a moderator role.',
|
|
|
|
code: 'ROLE_PERMISSION_DENIED',
|
|
|
|
id: 'd33d5333-db36-423d-a8f9-1a2b9549da41',
|
|
|
|
});
|
|
|
|
}
|
|
|
|
if (ep.meta.requireAdmin && !myRoles.some(r => r.isAdministrator)) {
|
|
|
|
throw new ApiError({
|
|
|
|
message: 'You are not assigned to an administrator role.',
|
|
|
|
code: 'ROLE_PERMISSION_DENIED',
|
|
|
|
id: 'c3d38592-54c0-429d-be96-5636b0431a61',
|
|
|
|
});
|
|
|
|
}
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
|
2023-01-15 20:52:53 +09:00
|
|
|
if (ep.meta.requireRolePolicy != null && !user!.isRoot) {
|
|
|
|
const policies = await this.roleService.getUserPolicies(user!.id);
|
|
|
|
if (!policies[ep.meta.requireRolePolicy]) {
|
2023-01-13 14:46:56 +09:00
|
|
|
throw new ApiError({
|
|
|
|
message: 'You are not assigned to a required role.',
|
|
|
|
code: 'ROLE_PERMISSION_DENIED',
|
|
|
|
id: '7f86f06f-7e15-4057-8561-f4b6d4ac755a',
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-18 03:27:08 +09:00
|
|
|
if (token && ep.meta.kind && !token.permission.some(p => p === ep.meta.kind)) {
|
|
|
|
throw new ApiError({
|
|
|
|
message: 'Your app does not have the necessary permissions to use this endpoint.',
|
|
|
|
code: 'PERMISSION_DENIED',
|
|
|
|
id: '1370e5b7-d4eb-4566-bb1d-7748ee6a1838',
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// Cast non JSON input
|
2022-12-03 19:42:05 +09:00
|
|
|
if ((ep.meta.requireFile || request.method === 'GET') && ep.params.properties) {
|
2022-09-18 03:27:08 +09:00
|
|
|
for (const k of Object.keys(ep.params.properties)) {
|
|
|
|
const param = ep.params.properties![k];
|
|
|
|
if (['boolean', 'number', 'integer'].includes(param.type ?? '') && typeof data[k] === 'string') {
|
|
|
|
try {
|
|
|
|
data[k] = JSON.parse(data[k]);
|
|
|
|
} catch (e) {
|
|
|
|
throw new ApiError({
|
|
|
|
message: 'Invalid param.',
|
|
|
|
code: 'INVALID_PARAM',
|
|
|
|
id: '0b5f1631-7c1a-41a6-b399-cce335f34d85',
|
|
|
|
}, {
|
|
|
|
param: k,
|
|
|
|
reason: `cannot cast to ${param.type}`,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// API invoking
|
2022-12-03 19:42:05 +09:00
|
|
|
return await ep.exec(data, user, token, file, request.ip, request.headers).catch((err: Error) => {
|
2023-03-09 14:27:16 +09:00
|
|
|
if (err instanceof ApiError || err instanceof AuthenticationError) {
|
2022-09-18 03:27:08 +09:00
|
|
|
throw err;
|
|
|
|
} else {
|
2023-02-26 17:12:15 +09:00
|
|
|
const errId = uuid();
|
2022-09-19 03:11:50 +09:00
|
|
|
this.logger.error(`Internal error occurred in ${ep.name}: ${err.message}`, {
|
2022-09-18 03:27:08 +09:00
|
|
|
ep: ep.name,
|
|
|
|
ps: data,
|
|
|
|
e: {
|
|
|
|
message: err.message,
|
|
|
|
code: err.name,
|
|
|
|
stack: err.stack,
|
2023-02-26 17:12:15 +09:00
|
|
|
id: errId,
|
2022-09-18 03:27:08 +09:00
|
|
|
},
|
|
|
|
});
|
2023-02-26 17:12:15 +09:00
|
|
|
console.error(err, errId);
|
2022-09-18 03:27:08 +09:00
|
|
|
throw new ApiError(null, {
|
|
|
|
e: {
|
|
|
|
message: err.message,
|
|
|
|
code: err.name,
|
2023-02-26 17:12:15 +09:00
|
|
|
id: errId,
|
2022-09-18 03:27:08 +09:00
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-12-04 15:03:09 +09:00
|
|
|
@bindThis
|
2022-09-18 03:27:08 +09:00
|
|
|
public onApplicationShutdown(signal?: string | undefined) {
|
2022-09-19 03:11:50 +09:00
|
|
|
clearInterval(this.userIpHistoriesClearIntervalId);
|
2022-09-18 03:27:08 +09:00
|
|
|
}
|
|
|
|
}
|