barkey/packages/backend/src/server/WellKnownServerService.ts

169 lines
5.2 KiB
TypeScript
Raw Normal View History

2022-09-17 18:27:08 +00:00
import { Inject, Injectable } from '@nestjs/common';
import { IsNull } from 'typeorm';
import vary from 'vary';
2022-09-17 18:27:08 +00:00
import { DI } from '@/di-symbols.js';
2022-09-20 20:33:11 +00:00
import type { UsersRepository } from '@/models/index.js';
import type { Config } from '@/config.js';
2022-09-17 18:27:08 +00:00
import { escapeAttribute, escapeValue } from '@/misc/prelude/xml.js';
import type { User } from '@/models/entities/User.js';
import * as Acct from '@/misc/acct.js';
import { NodeinfoServerService } from './NodeinfoServerService.js';
enhance: account migration (#10592) * copy block and mute then create follow and unfollow jobs * copy block and mute and update lists when detecting an account has moved * no need to care promise orders * refactor updating actor and target * automatically accept if a locked account had accepted an old account * fix exception format * prevent the old account from calling some endpoints * do not unfollow when moving * adjust following and follower counts * check movedToUri when receiving a follow request * skip if no need to adjust * Revert "disable account migration" This reverts commit 2321214c98591bcfe1385c1ab5bf0ff7b471ae1d. * fix translation specifier * fix checking alsoKnownAs and uri * fix updating account * fix refollowing locked account * decrease followersCount if followed by the old account * adjust following and followers counts when unfollowing * fix copying mutings * prohibit moved account from moving again * fix move service * allow app creation after moving * fix lint * remove unnecessary field * fix cache update * add e2e test * add e2e test of accepting the new account automatically * force follow if any error happens * remove unnecessary joins * use Array.map instead of for const of * ユーザーリストの移行は追加のみを行う * nanka iroiro * fix misskey-js? * :v: * 移行を行ったアカウントからのフォローリクエストの自動許可を調整 * newUriを外に出す * newUriを外に出す2 * clean up * fix newUri * prevent moving if the destination account has already moved * set alsoKnownAs via /i/update * fix database initialization * add return type * prohibit updating alsoKnownAs after moving * skip to add to alsoKnownAs if toUrl is known * skip adding to the list if it already has * use Acct.parse instead * rename error code * :art: * 制限を5から10に緩和 * movedTo(Uri), alsoKnownAsはユーザーidを返すように * test api res * fix * 元アカウントはミュートし続ける * :art: * unfollow * fix * getUserUriをUserEntityServiceに * ? * job! * :art: * instance => server * accountMovedShort, forbiddenBecauseYouAreMigrated * accountMovedShort * fix test * import, pin禁止 * 実績を凍結する * clean up * :v: * change message * ブロック, フォロー, ミュート, リストのインポートファイルの制限を32MiBに * Revert "ブロック, フォロー, ミュート, リストのインポートファイルの制限を32MiBに" This reverts commit 3bd7be35d8aa455cb01ae58f8172a71a50485db1. * validateAlsoKnownAs * 移行後2時間以内はインポート可能なファイルサイズを拡大 * clean up * どうせactorをupdatePersonで更新するならupdatePersonしか移行処理を発行しないことにする * handle error? * リモートからの移行処理の条件を是正 * log, port * fix * fix * enhance(dev): non-production環境でhttpサーバー間でもユーザー、ノートの連合が可能なように * refactor (use checkHttps) * MISSKEY_WEBFINGER_USE_HTTP * Environment Variable readme * NEVER USE IN PRODUCTION * fix punyHost * fix indent * fix * experimental --------- Co-authored-by: tamaina <tamaina@hotmail.co.jp> Co-authored-by: syuilo <Syuilotan@yahoo.co.jp>
2023-04-29 15:09:29 +00:00
import { UserEntityService } from '@/core/entities/UserEntityService.js';
2022-09-17 18:27:08 +00:00
import type { FindOptionsWhere } from 'typeorm';
import { bindThis } from '@/decorators.js';
import type { FastifyInstance, FastifyPluginOptions } from 'fastify';
2022-12-22 08:46:46 +00:00
import fastifyAccepts from '@fastify/accepts';
2022-09-17 18:27:08 +00:00
@Injectable()
export class WellKnownServerService {
constructor(
@Inject(DI.config)
private config: Config,
@Inject(DI.usersRepository)
private usersRepository: UsersRepository,
private nodeinfoServerService: NodeinfoServerService,
enhance: account migration (#10592) * copy block and mute then create follow and unfollow jobs * copy block and mute and update lists when detecting an account has moved * no need to care promise orders * refactor updating actor and target * automatically accept if a locked account had accepted an old account * fix exception format * prevent the old account from calling some endpoints * do not unfollow when moving * adjust following and follower counts * check movedToUri when receiving a follow request * skip if no need to adjust * Revert "disable account migration" This reverts commit 2321214c98591bcfe1385c1ab5bf0ff7b471ae1d. * fix translation specifier * fix checking alsoKnownAs and uri * fix updating account * fix refollowing locked account * decrease followersCount if followed by the old account * adjust following and followers counts when unfollowing * fix copying mutings * prohibit moved account from moving again * fix move service * allow app creation after moving * fix lint * remove unnecessary field * fix cache update * add e2e test * add e2e test of accepting the new account automatically * force follow if any error happens * remove unnecessary joins * use Array.map instead of for const of * ユーザーリストの移行は追加のみを行う * nanka iroiro * fix misskey-js? * :v: * 移行を行ったアカウントからのフォローリクエストの自動許可を調整 * newUriを外に出す * newUriを外に出す2 * clean up * fix newUri * prevent moving if the destination account has already moved * set alsoKnownAs via /i/update * fix database initialization * add return type * prohibit updating alsoKnownAs after moving * skip to add to alsoKnownAs if toUrl is known * skip adding to the list if it already has * use Acct.parse instead * rename error code * :art: * 制限を5から10に緩和 * movedTo(Uri), alsoKnownAsはユーザーidを返すように * test api res * fix * 元アカウントはミュートし続ける * :art: * unfollow * fix * getUserUriをUserEntityServiceに * ? * job! * :art: * instance => server * accountMovedShort, forbiddenBecauseYouAreMigrated * accountMovedShort * fix test * import, pin禁止 * 実績を凍結する * clean up * :v: * change message * ブロック, フォロー, ミュート, リストのインポートファイルの制限を32MiBに * Revert "ブロック, フォロー, ミュート, リストのインポートファイルの制限を32MiBに" This reverts commit 3bd7be35d8aa455cb01ae58f8172a71a50485db1. * validateAlsoKnownAs * 移行後2時間以内はインポート可能なファイルサイズを拡大 * clean up * どうせactorをupdatePersonで更新するならupdatePersonしか移行処理を発行しないことにする * handle error? * リモートからの移行処理の条件を是正 * log, port * fix * fix * enhance(dev): non-production環境でhttpサーバー間でもユーザー、ノートの連合が可能なように * refactor (use checkHttps) * MISSKEY_WEBFINGER_USE_HTTP * Environment Variable readme * NEVER USE IN PRODUCTION * fix punyHost * fix indent * fix * experimental --------- Co-authored-by: tamaina <tamaina@hotmail.co.jp> Co-authored-by: syuilo <Syuilotan@yahoo.co.jp>
2023-04-29 15:09:29 +00:00
private userEntityService: UserEntityService,
2022-09-17 18:27:08 +00:00
) {
//this.createServer = this.createServer.bind(this);
2022-09-17 18:27:08 +00:00
}
@bindThis
public createServer(fastify: FastifyInstance, options: FastifyPluginOptions, done: (err?: Error) => void) {
2022-09-17 18:27:08 +00:00
const XRD = (...x: { element: string, value?: string, attributes?: Record<string, string> }[]) =>
`<?xml version="1.0" encoding="UTF-8"?><XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">${x.map(({ element, value, attributes }) =>
`<${
Object.entries(typeof attributes === 'object' && attributes || {}).reduce((a, [k, v]) => `${a} ${k}="${escapeAttribute(v)}"`, element)
}${
typeof value === 'string' ? `>${escapeValue(value)}</${element}` : '/'
}>`).reduce((a, c) => a + c, '')}</XRD>`;
const allPath = '/.well-known/*';
2022-09-17 18:27:08 +00:00
const webFingerPath = '/.well-known/webfinger';
const jrd = 'application/jrd+json';
const xrd = 'application/xrd+xml';
2022-12-22 08:46:46 +00:00
fastify.register(fastifyAccepts);
fastify.addHook('onRequest', (request, reply, done) => {
reply.header('Access-Control-Allow-Headers', 'Accept');
reply.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
reply.header('Access-Control-Allow-Origin', '*');
reply.header('Access-Control-Expose-Headers', 'Vary');
done();
2022-09-17 18:27:08 +00:00
});
fastify.options(allPath, async (request, reply) => {
reply.code(204);
2022-09-17 18:27:08 +00:00
});
fastify.get('/.well-known/host-meta', async (request, reply) => {
reply.header('Content-Type', xrd);
return XRD({ element: 'Link', attributes: {
2022-09-17 18:27:08 +00:00
rel: 'lrdd',
type: xrd,
template: `${this.config.url}${webFingerPath}?resource={uri}`,
} });
});
fastify.get('/.well-known/host-meta.json', async (request, reply) => {
reply.header('Content-Type', jrd);
return {
2022-09-17 18:27:08 +00:00
links: [{
rel: 'lrdd',
type: jrd,
template: `${this.config.url}${webFingerPath}?resource={uri}`,
}],
};
});
fastify.get('/.well-known/nodeinfo', async (request, reply) => {
return { links: this.nodeinfoServerService.getLinks() };
2022-09-17 18:27:08 +00:00
});
/* TODO
fastify.get('/.well-known/change-password', async (request, reply) => {
2022-09-17 18:27:08 +00:00
});
*/
fastify.get<{ Querystring: { resource: string } }>(webFingerPath, async (request, reply) => {
2022-09-17 18:27:08 +00:00
const fromId = (id: User['id']): FindOptionsWhere<User> => ({
id,
host: IsNull(),
isSuspended: false,
});
const generateQuery = (resource: string): FindOptionsWhere<User> | number =>
resource.startsWith(`${this.config.url.toLowerCase()}/users/`) ?
fromId(resource.split('/').pop()!) :
fromAcct(Acct.parse(
resource.startsWith(`${this.config.url.toLowerCase()}/@`) ? resource.split('/').pop()! :
resource.startsWith('acct:') ? resource.slice('acct:'.length) :
resource));
const fromAcct = (acct: Acct.Acct): FindOptionsWhere<User> | number =>
!acct.host || acct.host === this.config.host.toLowerCase() ? {
usernameLower: acct.username,
host: IsNull(),
isSuspended: false,
} : 422;
if (typeof request.query.resource !== 'string') {
reply.code(400);
2022-09-17 18:27:08 +00:00
return;
}
const query = generateQuery(request.query.resource.toLowerCase());
2022-09-17 18:27:08 +00:00
if (typeof query === 'number') {
reply.code(query);
2022-09-17 18:27:08 +00:00
return;
}
const user = await this.usersRepository.findOneBy(query);
if (user == null) {
reply.code(404);
2022-09-17 18:27:08 +00:00
return;
}
const subject = `acct:${user.username}@${this.config.host}`;
const self = {
rel: 'self',
type: 'application/activity+json',
enhance: account migration (#10592) * copy block and mute then create follow and unfollow jobs * copy block and mute and update lists when detecting an account has moved * no need to care promise orders * refactor updating actor and target * automatically accept if a locked account had accepted an old account * fix exception format * prevent the old account from calling some endpoints * do not unfollow when moving * adjust following and follower counts * check movedToUri when receiving a follow request * skip if no need to adjust * Revert "disable account migration" This reverts commit 2321214c98591bcfe1385c1ab5bf0ff7b471ae1d. * fix translation specifier * fix checking alsoKnownAs and uri * fix updating account * fix refollowing locked account * decrease followersCount if followed by the old account * adjust following and followers counts when unfollowing * fix copying mutings * prohibit moved account from moving again * fix move service * allow app creation after moving * fix lint * remove unnecessary field * fix cache update * add e2e test * add e2e test of accepting the new account automatically * force follow if any error happens * remove unnecessary joins * use Array.map instead of for const of * ユーザーリストの移行は追加のみを行う * nanka iroiro * fix misskey-js? * :v: * 移行を行ったアカウントからのフォローリクエストの自動許可を調整 * newUriを外に出す * newUriを外に出す2 * clean up * fix newUri * prevent moving if the destination account has already moved * set alsoKnownAs via /i/update * fix database initialization * add return type * prohibit updating alsoKnownAs after moving * skip to add to alsoKnownAs if toUrl is known * skip adding to the list if it already has * use Acct.parse instead * rename error code * :art: * 制限を5から10に緩和 * movedTo(Uri), alsoKnownAsはユーザーidを返すように * test api res * fix * 元アカウントはミュートし続ける * :art: * unfollow * fix * getUserUriをUserEntityServiceに * ? * job! * :art: * instance => server * accountMovedShort, forbiddenBecauseYouAreMigrated * accountMovedShort * fix test * import, pin禁止 * 実績を凍結する * clean up * :v: * change message * ブロック, フォロー, ミュート, リストのインポートファイルの制限を32MiBに * Revert "ブロック, フォロー, ミュート, リストのインポートファイルの制限を32MiBに" This reverts commit 3bd7be35d8aa455cb01ae58f8172a71a50485db1. * validateAlsoKnownAs * 移行後2時間以内はインポート可能なファイルサイズを拡大 * clean up * どうせactorをupdatePersonで更新するならupdatePersonしか移行処理を発行しないことにする * handle error? * リモートからの移行処理の条件を是正 * log, port * fix * fix * enhance(dev): non-production環境でhttpサーバー間でもユーザー、ノートの連合が可能なように * refactor (use checkHttps) * MISSKEY_WEBFINGER_USE_HTTP * Environment Variable readme * NEVER USE IN PRODUCTION * fix punyHost * fix indent * fix * experimental --------- Co-authored-by: tamaina <tamaina@hotmail.co.jp> Co-authored-by: syuilo <Syuilotan@yahoo.co.jp>
2023-04-29 15:09:29 +00:00
href: this.userEntityService.genLocalUserUri(user.id),
2022-09-17 18:27:08 +00:00
};
const profilePage = {
rel: 'http://webfinger.net/rel/profile-page',
type: 'text/html',
href: `${this.config.url}/@${user.username}`,
};
const subscribe = {
rel: 'http://ostatus.org/schema/1.0/subscribe',
template: `${this.config.url}/authorize-follow?acct={uri}`,
};
vary(reply.raw, 'Accept');
reply.header('Cache-Control', 'public, max-age=180');
if (request.accepts().type([jrd, xrd]) === xrd) {
reply.type(xrd);
return XRD(
2022-09-17 18:27:08 +00:00
{ element: 'Subject', value: subject },
{ element: 'Link', attributes: self },
{ element: 'Link', attributes: profilePage },
{ element: 'Link', attributes: subscribe });
} else {
reply.type(jrd);
return {
2022-09-17 18:27:08 +00:00
subject,
links: [self, profilePage, subscribe],
};
}
});
done();
2022-09-17 18:27:08 +00:00
}
}