Sharkey/packages/backend/src/core/RemoteUserResolveService.ts

159 lines
5.2 KiB
TypeScript
Raw Normal View History

/*
* SPDX-FileCopyrightText: syuilo and other misskey contributors
* SPDX-License-Identifier: AGPL-3.0-only
*/
2022-09-17 20:27:08 +02:00
import { URL } from 'node:url';
import { Inject, Injectable } from '@nestjs/common';
import chalk from 'chalk';
import { IsNull } from 'typeorm';
import { DI } from '@/di-symbols.js';
import type { UsersRepository } from '@/models/_.js';
import type { MiLocalUser, MiRemoteUser } from '@/models/User.js';
2022-09-20 22:33:11 +02:00
import type { Config } from '@/config.js';
2022-09-17 20:27:08 +02:00
import type Logger from '@/logger.js';
2022-12-04 02:16:03 +01:00
import { UtilityService } from '@/core/UtilityService.js';
import { ILink, WebfingerService } from '@/core/WebfingerService.js';
2022-12-04 02:16:03 +01:00
import { RemoteLoggerService } from '@/core/RemoteLoggerService.js';
import { ApDbResolverService } from '@/core/activitypub/ApDbResolverService.js';
2022-12-04 02:16:03 +01:00
import { ApPersonService } from '@/core/activitypub/models/ApPersonService.js';
import { bindThis } from '@/decorators.js';
2022-09-17 20:27:08 +02:00
@Injectable()
2022-12-04 02:16:03 +01:00
export class RemoteUserResolveService {
2022-09-18 20:11:50 +02:00
private logger: Logger;
2022-09-17 20:27:08 +02:00
constructor(
@Inject(DI.config)
private config: Config,
@Inject(DI.usersRepository)
private usersRepository: UsersRepository,
private utilityService: UtilityService,
private webfingerService: WebfingerService,
private remoteLoggerService: RemoteLoggerService,
private apDbResolverService: ApDbResolverService,
2022-09-17 20:27:08 +02:00
private apPersonService: ApPersonService,
) {
2022-09-18 20:11:50 +02:00
this.logger = this.remoteLoggerService.logger.createSubLogger('resolve-user');
2022-09-17 20:27:08 +02:00
}
@bindThis
public async resolveUser(username: string, host: string | null): Promise<MiLocalUser | MiRemoteUser> {
2022-09-17 20:27:08 +02:00
const usernameLower = username.toLowerCase();
2022-09-17 20:27:08 +02:00
if (host == null) {
2022-09-18 20:11:50 +02:00
this.logger.info(`return local user: ${usernameLower}`);
2022-09-17 20:27:08 +02:00
return await this.usersRepository.findOneBy({ usernameLower, host: IsNull() }).then(u => {
if (u == null) {
throw new Error('user not found');
} else {
return u;
}
}) as MiLocalUser;
2022-09-17 20:27:08 +02:00
}
2022-09-17 20:27:08 +02:00
host = this.utilityService.toPuny(host);
2022-09-17 20:27:08 +02:00
if (this.config.host === host) {
2022-09-18 20:11:50 +02:00
this.logger.info(`return local user: ${usernameLower}`);
2022-09-17 20:27:08 +02:00
return await this.usersRepository.findOneBy({ usernameLower, host: IsNull() }).then(u => {
if (u == null) {
throw new Error('user not found');
} else {
return u;
}
}) as MiLocalUser;
2022-09-17 20:27:08 +02:00
}
const user = await this.usersRepository.findOneBy({ usernameLower, host }) as MiRemoteUser | null;
2022-09-17 20:27:08 +02:00
const acctLower = `${usernameLower}@${host}`;
2022-09-17 20:27:08 +02:00
if (user == null) {
2022-09-18 20:11:50 +02:00
const self = await this.resolveSelf(acctLower);
if (self.href.startsWith(this.config.url)) {
const local = this.apDbResolverService.parseUri(self.href);
if (local.local && local.type === 'users') {
// the LR points to local
return (await this.apDbResolverService
.getUserFromApId(self.href)
.then((u) => {
if (u == null) {
throw new Error('local user not found');
} else {
return u;
}
})) as MiLocalUser;
}
}
2022-09-18 20:11:50 +02:00
this.logger.succ(`return new remote user: ${chalk.magenta(acctLower)}`);
2022-09-17 20:27:08 +02:00
return await this.apPersonService.createPerson(self.href);
}
2023-07-15 03:01:41 +02:00
// ユーザー情報が古い場合は、WebFingerからやりなおして返す
2022-09-17 20:27:08 +02:00
if (user.lastFetchedAt == null || Date.now() - user.lastFetchedAt.getTime() > 1000 * 60 * 60 * 24) {
// 繋がらないインスタンスに何回も試行するのを防ぐ, 後続の同様処理の連続試行を防ぐ ため 試行前にも更新する
await this.usersRepository.update(user.id, {
lastFetchedAt: new Date(),
});
2022-09-18 20:11:50 +02:00
this.logger.info(`try resync: ${acctLower}`);
const self = await this.resolveSelf(acctLower);
2022-09-17 20:27:08 +02:00
if (user.uri !== self.href) {
2023-02-13 07:50:22 +01:00
// if uri mismatch, Fix (user@host <=> AP's Person id(RemoteUser.uri)) mapping.
2022-09-18 20:11:50 +02:00
this.logger.info(`uri missmatch: ${acctLower}`);
this.logger.info(`recovery missmatch uri for (username=${username}, host=${host}) from ${user.uri} to ${self.href}`);
2022-09-17 20:27:08 +02:00
// validate uri
const uri = new URL(self.href);
if (uri.hostname !== host) {
throw new Error('Invalid uri');
}
2022-09-17 20:27:08 +02:00
await this.usersRepository.update({
usernameLower,
host: host,
}, {
uri: self.href,
});
} else {
2022-09-18 20:11:50 +02:00
this.logger.info(`uri is fine: ${acctLower}`);
2022-09-17 20:27:08 +02:00
}
2022-09-17 20:27:08 +02:00
await this.apPersonService.updatePerson(self.href);
2022-09-18 20:11:50 +02:00
this.logger.info(`return resynced remote user: ${acctLower}`);
2022-09-17 20:27:08 +02:00
return await this.usersRepository.findOneBy({ uri: self.href }).then(u => {
if (u == null) {
throw new Error('user not found');
} else {
return u as MiLocalUser | MiRemoteUser;
2022-09-17 20:27:08 +02:00
}
});
}
2022-09-18 20:11:50 +02:00
this.logger.info(`return existing remote user: ${acctLower}`);
2022-09-17 20:27:08 +02:00
return user;
}
@bindThis
private async resolveSelf(acctLower: string): Promise<ILink> {
2022-09-18 20:11:50 +02:00
this.logger.info(`WebFinger for ${chalk.yellow(acctLower)}`);
2022-09-17 20:27:08 +02:00
const finger = await this.webfingerService.webfinger(acctLower).catch(err => {
2022-09-18 20:11:50 +02:00
this.logger.error(`Failed to WebFinger for ${chalk.yellow(acctLower)}: ${ err.statusCode ?? err.message }`);
2022-09-17 20:27:08 +02:00
throw new Error(`Failed to WebFinger for ${acctLower}: ${ err.statusCode ?? err.message }`);
});
const self = finger.links.find(link => link.rel != null && link.rel.toLowerCase() === 'self');
if (!self) {
2022-09-18 20:11:50 +02:00
this.logger.error(`Failed to WebFinger for ${chalk.yellow(acctLower)}: self link not found`);
2022-09-17 20:27:08 +02:00
throw new Error('self link not found');
}
return self;
}
}