drop twitter/github/discord integrations

Close #9775
This commit is contained in:
syuilo
2023-02-03 15:01:31 +09:00
parent 65ed702d87
commit 562b02310f
24 changed files with 6 additions and 1426 deletions

View File

@@ -12,9 +12,6 @@ import endpoints, { IEndpoint } from './endpoints.js';
import { ApiCallService } from './ApiCallService.js';
import { SignupApiService } from './SignupApiService.js';
import { SigninApiService } from './SigninApiService.js';
import { GithubServerService } from './integration/GithubServerService.js';
import { DiscordServerService } from './integration/DiscordServerService.js';
import { TwitterServerService } from './integration/TwitterServerService.js';
import type { FastifyInstance, FastifyPluginOptions } from 'fastify';
@Injectable()
@@ -38,9 +35,6 @@ export class ApiServerService {
private apiCallService: ApiCallService,
private signupApiService: SignupApiService,
private signinApiService: SigninApiService,
private githubServerService: GithubServerService,
private discordServerService: DiscordServerService,
private twitterServerService: TwitterServerService,
) {
//this.createServer = this.createServer.bind(this);
}
@@ -133,10 +127,6 @@ export class ApiServerService {
fastify.post<{ Body: { code: string; } }>('/signup-pending', (request, reply) => this.signupApiService.signupPending(request, reply));
fastify.register(this.discordServerService.create);
fastify.register(this.githubServerService.create);
fastify.register(this.twitterServerService.create);
fastify.get('/v1/instance/peers', async (request, reply) => {
const instances = await this.instancesRepository.find({
select: ['host'],

View File

@@ -138,18 +138,6 @@ export const meta = {
type: 'boolean',
optional: false, nullable: false,
},
enableTwitterIntegration: {
type: 'boolean',
optional: false, nullable: false,
},
enableGithubIntegration: {
type: 'boolean',
optional: false, nullable: false,
},
enableDiscordIntegration: {
type: 'boolean',
optional: false, nullable: false,
},
enableServiceWorker: {
type: 'boolean',
optional: false, nullable: false,
@@ -223,30 +211,6 @@ export const meta = {
optional: true, nullable: true,
format: 'id',
},
twitterConsumerKey: {
type: 'string',
optional: true, nullable: true,
},
twitterConsumerSecret: {
type: 'string',
optional: true, nullable: true,
},
githubClientId: {
type: 'string',
optional: true, nullable: true,
},
githubClientSecret: {
type: 'string',
optional: true, nullable: true,
},
discordClientId: {
type: 'string',
optional: true, nullable: true,
},
discordClientSecret: {
type: 'string',
optional: true, nullable: true,
},
summaryProxy: {
type: 'string',
optional: true, nullable: true,
@@ -389,9 +353,6 @@ export default class extends Endpoint<typeof meta, typeof paramDef> {
defaultLightTheme: instance.defaultLightTheme,
defaultDarkTheme: instance.defaultDarkTheme,
enableEmail: instance.enableEmail,
enableTwitterIntegration: instance.enableTwitterIntegration,
enableGithubIntegration: instance.enableGithubIntegration,
enableDiscordIntegration: instance.enableDiscordIntegration,
enableServiceWorker: instance.enableServiceWorker,
translatorAvailable: instance.deeplAuthKey != null,
pinnedPages: instance.pinnedPages,
@@ -409,12 +370,6 @@ export default class extends Endpoint<typeof meta, typeof paramDef> {
setSensitiveFlagAutomatically: instance.setSensitiveFlagAutomatically,
enableSensitiveMediaDetectionForVideos: instance.enableSensitiveMediaDetectionForVideos,
proxyAccountId: instance.proxyAccountId,
twitterConsumerKey: instance.twitterConsumerKey,
twitterConsumerSecret: instance.twitterConsumerSecret,
githubClientId: instance.githubClientId,
githubClientSecret: instance.githubClientSecret,
discordClientId: instance.discordClientId,
discordClientSecret: instance.discordClientSecret,
summalyProxy: instance.summalyProxy,
email: instance.email,
smtpSecure: instance.smtpSecure,

View File

@@ -65,11 +65,6 @@ export default class extends Endpoint<typeof meta, typeof paramDef> {
};
}
const maskedKeys = ['accessToken', 'accessTokenSecret', 'refreshToken'];
Object.keys(profile.integrations).forEach(integration => {
maskedKeys.forEach(key => profile.integrations[integration][key] = '<MASKED>');
});
const signins = await this.signinsRepository.findBy({ userId: user.id });
const roles = await this.roleService.getUserRoles(user.id);
@@ -84,7 +79,6 @@ export default class extends Endpoint<typeof meta, typeof paramDef> {
carefulBot: profile.carefulBot,
injectFeaturedNote: profile.injectFeaturedNote,
receiveAnnouncementEmail: profile.receiveAnnouncementEmail,
integrations: profile.integrations,
mutedWords: profile.mutedWords,
mutedInstances: profile.mutedInstances,
mutingNotificationTypes: profile.mutingNotificationTypes,

View File

@@ -68,15 +68,6 @@ export const paramDef = {
summalyProxy: { type: 'string', nullable: true },
deeplAuthKey: { type: 'string', nullable: true },
deeplIsPro: { type: 'boolean' },
enableTwitterIntegration: { type: 'boolean' },
twitterConsumerKey: { type: 'string', nullable: true },
twitterConsumerSecret: { type: 'string', nullable: true },
enableGithubIntegration: { type: 'boolean' },
githubClientId: { type: 'string', nullable: true },
githubClientSecret: { type: 'string', nullable: true },
enableDiscordIntegration: { type: 'boolean' },
discordClientId: { type: 'string', nullable: true },
discordClientSecret: { type: 'string', nullable: true },
enableEmail: { type: 'boolean' },
email: { type: 'string', nullable: true },
smtpSecure: { type: 'boolean' },
@@ -270,42 +261,6 @@ export default class extends Endpoint<typeof meta, typeof paramDef> {
set.summalyProxy = ps.summalyProxy;
}
if (ps.enableTwitterIntegration !== undefined) {
set.enableTwitterIntegration = ps.enableTwitterIntegration;
}
if (ps.twitterConsumerKey !== undefined) {
set.twitterConsumerKey = ps.twitterConsumerKey;
}
if (ps.twitterConsumerSecret !== undefined) {
set.twitterConsumerSecret = ps.twitterConsumerSecret;
}
if (ps.enableGithubIntegration !== undefined) {
set.enableGithubIntegration = ps.enableGithubIntegration;
}
if (ps.githubClientId !== undefined) {
set.githubClientId = ps.githubClientId;
}
if (ps.githubClientSecret !== undefined) {
set.githubClientSecret = ps.githubClientSecret;
}
if (ps.enableDiscordIntegration !== undefined) {
set.enableDiscordIntegration = ps.enableDiscordIntegration;
}
if (ps.discordClientId !== undefined) {
set.discordClientId = ps.discordClientId;
}
if (ps.discordClientSecret !== undefined) {
set.discordClientSecret = ps.discordClientSecret;
}
if (ps.enableEmail !== undefined) {
set.enableEmail = ps.enableEmail;
}

View File

@@ -169,18 +169,6 @@ export const meta = {
type: 'boolean',
optional: false, nullable: false,
},
enableTwitterIntegration: {
type: 'boolean',
optional: false, nullable: false,
},
enableGithubIntegration: {
type: 'boolean',
optional: false, nullable: false,
},
enableDiscordIntegration: {
type: 'boolean',
optional: false, nullable: false,
},
enableServiceWorker: {
type: 'boolean',
optional: false, nullable: false,
@@ -225,18 +213,6 @@ export const meta = {
type: 'boolean',
optional: false, nullable: false,
},
twitter: {
type: 'boolean',
optional: false, nullable: false,
},
github: {
type: 'boolean',
optional: false, nullable: false,
},
discord: {
type: 'boolean',
optional: false, nullable: false,
},
serviceWorker: {
type: 'boolean',
optional: false, nullable: false,
@@ -325,11 +301,6 @@ export default class extends Endpoint<typeof meta, typeof paramDef> {
imageUrl: ad.imageUrl,
})),
enableEmail: instance.enableEmail,
enableTwitterIntegration: instance.enableTwitterIntegration,
enableGithubIntegration: instance.enableGithubIntegration,
enableDiscordIntegration: instance.enableDiscordIntegration,
enableServiceWorker: instance.enableServiceWorker,
translatorAvailable: instance.deeplAuthKey != null,
@@ -358,9 +329,6 @@ export default class extends Endpoint<typeof meta, typeof paramDef> {
recaptcha: instance.enableRecaptcha,
turnstile: instance.enableTurnstile,
objectStorage: instance.useObjectStorage,
twitter: instance.enableTwitterIntegration,
github: instance.enableGithubIntegration,
discord: instance.enableDiscordIntegration,
serviceWorker: instance.enableServiceWorker,
miauth: true,
};

View File

@@ -1,308 +0,0 @@
import { Inject, Injectable } from '@nestjs/common';
import Redis from 'ioredis';
import { OAuth2 } from 'oauth';
import { v4 as uuid } from 'uuid';
import { IsNull } from 'typeorm';
import type { Config } from '@/config.js';
import type { UserProfilesRepository, UsersRepository } from '@/models/index.js';
import { DI } from '@/di-symbols.js';
import { HttpRequestService } from '@/core/HttpRequestService.js';
import type { ILocalUser } from '@/models/entities/User.js';
import { GlobalEventService } from '@/core/GlobalEventService.js';
import { MetaService } from '@/core/MetaService.js';
import { UserEntityService } from '@/core/entities/UserEntityService.js';
import { FastifyReplyError } from '@/misc/fastify-reply-error.js';
import { bindThis } from '@/decorators.js';
import { SigninService } from '../SigninService.js';
import type { FastifyInstance, FastifyRequest, FastifyPluginOptions } from 'fastify';
@Injectable()
export class DiscordServerService {
constructor(
@Inject(DI.config)
private config: Config,
@Inject(DI.redis)
private redisClient: Redis.Redis,
@Inject(DI.usersRepository)
private usersRepository: UsersRepository,
@Inject(DI.userProfilesRepository)
private userProfilesRepository: UserProfilesRepository,
private userEntityService: UserEntityService,
private httpRequestService: HttpRequestService,
private globalEventService: GlobalEventService,
private metaService: MetaService,
private signinService: SigninService,
) {
//this.create = this.create.bind(this);
}
@bindThis
public create(fastify: FastifyInstance, options: FastifyPluginOptions, done: (err?: Error) => void) {
fastify.get('/disconnect/discord', async (request, reply) => {
if (!this.compareOrigin(request)) {
throw new FastifyReplyError(400, 'invalid origin');
}
const userToken = this.getUserToken(request);
if (!userToken) {
throw new FastifyReplyError(400, 'signin required');
}
const user = await this.usersRepository.findOneByOrFail({
host: IsNull(),
token: userToken,
});
const profile = await this.userProfilesRepository.findOneByOrFail({ userId: user.id });
delete profile.integrations.discord;
await this.userProfilesRepository.update(user.id, {
integrations: profile.integrations,
});
// Publish i updated event
this.globalEventService.publishMainStream(user.id, 'meUpdated', await this.userEntityService.pack(user, user, {
detail: true,
includeSecrets: true,
}));
return 'Discordの連携を解除しました :v:';
});
const getOAuth2 = async () => {
const meta = await this.metaService.fetch(true);
if (meta.enableDiscordIntegration) {
return new OAuth2(
meta.discordClientId!,
meta.discordClientSecret!,
'https://discord.com/',
'api/oauth2/authorize',
'api/oauth2/token');
} else {
return null;
}
};
fastify.get('/connect/discord', async (request, reply) => {
if (!this.compareOrigin(request)) {
throw new FastifyReplyError(400, 'invalid origin');
}
const userToken = this.getUserToken(request);
if (!userToken) {
throw new FastifyReplyError(400, 'signin required');
}
const params = {
redirect_uri: `${this.config.url}/api/dc/cb`,
scope: ['identify'],
state: uuid(),
response_type: 'code',
};
this.redisClient.set(userToken, JSON.stringify(params));
const oauth2 = await getOAuth2();
reply.redirect(oauth2!.getAuthorizeUrl(params));
});
fastify.get('/signin/discord', async (request, reply) => {
const sessid = uuid();
const params = {
redirect_uri: `${this.config.url}/api/dc/cb`,
scope: ['identify'],
state: uuid(),
response_type: 'code',
};
reply.setCookie('signin_with_discord_sid', sessid, {
path: '/',
secure: this.config.url.startsWith('https'),
httpOnly: true,
});
this.redisClient.set(sessid, JSON.stringify(params));
const oauth2 = await getOAuth2();
reply.redirect(oauth2!.getAuthorizeUrl(params));
});
fastify.get<{ Querystring: { code: string; state: string; } }>('/dc/cb', async (request, reply) => {
const userToken = this.getUserToken(request);
const oauth2 = await getOAuth2();
if (!userToken) {
const sessid = request.cookies['signin_with_discord_sid'];
if (!sessid) {
throw new FastifyReplyError(400, 'invalid session');
}
const code = request.query.code;
if (!code || typeof code !== 'string') {
throw new FastifyReplyError(400, 'invalid session');
}
const { redirect_uri, state } = await new Promise<any>((res, rej) => {
this.redisClient.get(sessid, async (_, state) => {
if (state == null) throw new Error('empty state');
res(JSON.parse(state));
});
});
if (request.query.state !== state) {
throw new FastifyReplyError(400, 'invalid session');
}
const { accessToken, refreshToken, expiresDate } = await new Promise<any>((res, rej) =>
oauth2!.getOAuthAccessToken(code, {
grant_type: 'authorization_code',
redirect_uri,
}, (err, accessToken, refreshToken, result) => {
if (err) {
rej(err);
} else if (result.error) {
rej(result.error);
} else {
res({
accessToken,
refreshToken,
expiresDate: Date.now() + Number(result.expires_in) * 1000,
});
}
}));
const { id, username, discriminator } = (await this.httpRequestService.getJson('https://discord.com/api/users/@me', '*/*', {
'Authorization': `Bearer ${accessToken}`,
})) as Record<string, unknown>;
if (typeof id !== 'string' || typeof username !== 'string' || typeof discriminator !== 'string') {
throw new FastifyReplyError(400, 'invalid session');
}
const profile = await this.userProfilesRepository.createQueryBuilder()
.where('"integrations"->\'discord\'->>\'id\' = :id', { id: id })
.andWhere('"userHost" IS NULL')
.getOne();
if (profile == null) {
throw new FastifyReplyError(404, `@${username}#${discriminator}と連携しているMisskeyアカウントはありませんでした...`);
}
await this.userProfilesRepository.update(profile.userId, {
integrations: {
...profile.integrations,
discord: {
id: id,
accessToken: accessToken,
refreshToken: refreshToken,
expiresDate: expiresDate,
username: username,
discriminator: discriminator,
},
},
});
return this.signinService.signin(request, reply, await this.usersRepository.findOneBy({ id: profile.userId }) as ILocalUser, true);
} else {
const code = request.query.code;
if (!code || typeof code !== 'string') {
throw new FastifyReplyError(400, 'invalid session');
}
const { redirect_uri, state } = await new Promise<any>((res, rej) => {
this.redisClient.get(userToken, async (_, state) => {
if (state == null) throw new Error('empty state');
res(JSON.parse(state));
});
});
if (request.query.state !== state) {
throw new FastifyReplyError(400, 'invalid session');
}
const { accessToken, refreshToken, expiresDate } = await new Promise<any>((res, rej) =>
oauth2!.getOAuthAccessToken(code, {
grant_type: 'authorization_code',
redirect_uri,
}, (err, accessToken, refreshToken, result) => {
if (err) {
rej(err);
} else if (result.error) {
rej(result.error);
} else {
res({
accessToken,
refreshToken,
expiresDate: Date.now() + Number(result.expires_in) * 1000,
});
}
}));
const { id, username, discriminator } = (await this.httpRequestService.getJson('https://discord.com/api/users/@me', '*/*', {
'Authorization': `Bearer ${accessToken}`,
})) as Record<string, unknown>;
if (typeof id !== 'string' || typeof username !== 'string' || typeof discriminator !== 'string') {
throw new FastifyReplyError(400, 'invalid session');
}
const user = await this.usersRepository.findOneByOrFail({
host: IsNull(),
token: userToken,
});
const profile = await this.userProfilesRepository.findOneByOrFail({ userId: user.id });
await this.userProfilesRepository.update(user.id, {
integrations: {
...profile.integrations,
discord: {
accessToken: accessToken,
refreshToken: refreshToken,
expiresDate: expiresDate,
id: id,
username: username,
discriminator: discriminator,
},
},
});
// Publish i updated event
this.globalEventService.publishMainStream(user.id, 'meUpdated', await this.userEntityService.pack(user, user, {
detail: true,
includeSecrets: true,
}));
return `Discord: @${username}#${discriminator} を、Misskey: @${user.username} に接続しました!`;
}
});
done();
}
@bindThis
private getUserToken(request: FastifyRequest): string | null {
return ((request.headers['cookie'] ?? '').match(/igi=(\w+)/) ?? [null, null])[1];
}
@bindThis
private compareOrigin(request: FastifyRequest): boolean {
function normalizeUrl(url?: string): string {
return url ? url.endsWith('/') ? url.substr(0, url.length - 1) : url : '';
}
const referer = request.headers['referer'];
return (normalizeUrl(referer) === normalizeUrl(this.config.url));
}
}

View File

@@ -1,280 +0,0 @@
import { Inject, Injectable } from '@nestjs/common';
import Redis from 'ioredis';
import { OAuth2 } from 'oauth';
import { v4 as uuid } from 'uuid';
import { IsNull } from 'typeorm';
import type { Config } from '@/config.js';
import type { UserProfilesRepository, UsersRepository } from '@/models/index.js';
import { DI } from '@/di-symbols.js';
import { HttpRequestService } from '@/core/HttpRequestService.js';
import type { ILocalUser } from '@/models/entities/User.js';
import { GlobalEventService } from '@/core/GlobalEventService.js';
import { MetaService } from '@/core/MetaService.js';
import { UserEntityService } from '@/core/entities/UserEntityService.js';
import { FastifyReplyError } from '@/misc/fastify-reply-error.js';
import { bindThis } from '@/decorators.js';
import { SigninService } from '../SigninService.js';
import type { FastifyInstance, FastifyRequest, FastifyPluginOptions } from 'fastify';
@Injectable()
export class GithubServerService {
constructor(
@Inject(DI.config)
private config: Config,
@Inject(DI.redis)
private redisClient: Redis.Redis,
@Inject(DI.usersRepository)
private usersRepository: UsersRepository,
@Inject(DI.userProfilesRepository)
private userProfilesRepository: UserProfilesRepository,
private userEntityService: UserEntityService,
private httpRequestService: HttpRequestService,
private globalEventService: GlobalEventService,
private metaService: MetaService,
private signinService: SigninService,
) {
//this.create = this.create.bind(this);
}
@bindThis
public create(fastify: FastifyInstance, options: FastifyPluginOptions, done: (err?: Error) => void) {
fastify.get('/disconnect/github', async (request, reply) => {
if (!this.compareOrigin(request)) {
throw new FastifyReplyError(400, 'invalid origin');
}
const userToken = this.getUserToken(request);
if (!userToken) {
throw new FastifyReplyError(400, 'signin required');
}
const user = await this.usersRepository.findOneByOrFail({
host: IsNull(),
token: userToken,
});
const profile = await this.userProfilesRepository.findOneByOrFail({ userId: user.id });
delete profile.integrations.github;
await this.userProfilesRepository.update(user.id, {
integrations: profile.integrations,
});
// Publish i updated event
this.globalEventService.publishMainStream(user.id, 'meUpdated', await this.userEntityService.pack(user, user, {
detail: true,
includeSecrets: true,
}));
return 'GitHubの連携を解除しました :v:';
});
const getOath2 = async () => {
const meta = await this.metaService.fetch(true);
if (meta.enableGithubIntegration && meta.githubClientId && meta.githubClientSecret) {
return new OAuth2(
meta.githubClientId,
meta.githubClientSecret,
'https://github.com/',
'login/oauth/authorize',
'login/oauth/access_token');
} else {
return null;
}
};
fastify.get('/connect/github', async (request, reply) => {
if (!this.compareOrigin(request)) {
throw new FastifyReplyError(400, 'invalid origin');
}
const userToken = this.getUserToken(request);
if (!userToken) {
throw new FastifyReplyError(400, 'signin required');
}
const params = {
redirect_uri: `${this.config.url}/api/gh/cb`,
scope: ['read:user'],
state: uuid(),
};
this.redisClient.set(userToken, JSON.stringify(params));
const oauth2 = await getOath2();
reply.redirect(oauth2!.getAuthorizeUrl(params));
});
fastify.get('/signin/github', async (request, reply) => {
const sessid = uuid();
const params = {
redirect_uri: `${this.config.url}/api/gh/cb`,
scope: ['read:user'],
state: uuid(),
};
reply.setCookie('signin_with_github_sid', sessid, {
path: '/',
secure: this.config.url.startsWith('https'),
httpOnly: true,
});
this.redisClient.set(sessid, JSON.stringify(params));
const oauth2 = await getOath2();
reply.redirect(oauth2!.getAuthorizeUrl(params));
});
fastify.get<{ Querystring: { code: string; state: string; } }>('/gh/cb', async (request, reply) => {
const userToken = this.getUserToken(request);
const oauth2 = await getOath2();
if (!userToken) {
const sessid = request.cookies['signin_with_github_sid'];
if (!sessid) {
throw new FastifyReplyError(400, 'invalid session');
}
const code = request.query.code;
if (!code || typeof code !== 'string') {
throw new FastifyReplyError(400, 'invalid session');
}
const { redirect_uri, state } = await new Promise<any>((res, rej) => {
this.redisClient.get(sessid, async (_, state) => {
if (state == null) throw new Error('empty state');
res(JSON.parse(state));
});
});
if (request.query.state !== state) {
throw new FastifyReplyError(400, 'invalid session');
}
const { accessToken } = await new Promise<{ accessToken: string }>((res, rej) =>
oauth2!.getOAuthAccessToken(code, {
redirect_uri,
}, (err, accessToken, refresh, result) => {
if (err) {
rej(err);
} else if (result.error) {
rej(result.error);
} else {
res({ accessToken });
}
}));
const { login, id } = (await this.httpRequestService.getJson('https://api.github.com/user', 'application/vnd.github.v3+json', {
'Authorization': `bearer ${accessToken}`,
})) as Record<string, unknown>;
if (typeof login !== 'string' || typeof id !== 'string') {
throw new FastifyReplyError(400, 'invalid session');
}
const link = await this.userProfilesRepository.createQueryBuilder()
.where('"integrations"->\'github\'->>\'id\' = :id', { id: id })
.andWhere('"userHost" IS NULL')
.getOne();
if (link == null) {
throw new FastifyReplyError(404, `@${login}と連携しているMisskeyアカウントはありませんでした...`);
}
return this.signinService.signin(request, reply, await this.usersRepository.findOneBy({ id: link.userId }) as ILocalUser, true);
} else {
const code = request.query.code;
if (!code || typeof code !== 'string') {
throw new FastifyReplyError(400, 'invalid session');
}
const { redirect_uri, state } = await new Promise<any>((res, rej) => {
this.redisClient.get(userToken, async (_, state) => {
if (state == null) throw new Error('empty state');
res(JSON.parse(state));
});
});
if (request.query.state !== state) {
throw new FastifyReplyError(400, 'invalid session');
}
const { accessToken } = await new Promise<{ accessToken: string }>((res, rej) =>
oauth2!.getOAuthAccessToken(
code,
{ redirect_uri },
(err, accessToken, refresh, result) => {
if (err) {
rej(err);
} else if (result.error) {
rej(result.error);
} else {
res({ accessToken });
}
}));
const { login, id } = (await this.httpRequestService.getJson('https://api.github.com/user', 'application/vnd.github.v3+json', {
'Authorization': `bearer ${accessToken}`,
})) as Record<string, unknown>;
if (typeof login !== 'string' || typeof id !== 'number') {
throw new FastifyReplyError(400, 'invalid session');
}
const user = await this.usersRepository.findOneByOrFail({
host: IsNull(),
token: userToken,
});
const profile = await this.userProfilesRepository.findOneByOrFail({ userId: user.id });
await this.userProfilesRepository.update(user.id, {
integrations: {
...profile.integrations,
github: {
accessToken: accessToken,
id: id,
login: login,
},
},
});
// Publish i updated event
this.globalEventService.publishMainStream(user.id, 'meUpdated', await this.userEntityService.pack(user, user, {
detail: true,
includeSecrets: true,
}));
return `GitHub: @${login} を、Misskey: @${user.username} に接続しました!`;
}
});
done();
}
@bindThis
private getUserToken(request: FastifyRequest): string | null {
return ((request.headers['cookie'] ?? '').match(/igi=(\w+)/) ?? [null, null])[1];
}
@bindThis
private compareOrigin(request: FastifyRequest): boolean {
function normalizeUrl(url?: string): string {
return url ? url.endsWith('/') ? url.substr(0, url.length - 1) : url : '';
}
const referer = request.headers['referer'];
return (normalizeUrl(referer) === normalizeUrl(this.config.url));
}
}

View File

@@ -1,225 +0,0 @@
import { Inject, Injectable } from '@nestjs/common';
import Redis from 'ioredis';
import { v4 as uuid } from 'uuid';
import { IsNull } from 'typeorm';
import * as autwh from 'autwh';
import type { Config } from '@/config.js';
import type { UserProfilesRepository, UsersRepository } from '@/models/index.js';
import { DI } from '@/di-symbols.js';
import { HttpRequestService } from '@/core/HttpRequestService.js';
import type { ILocalUser } from '@/models/entities/User.js';
import { GlobalEventService } from '@/core/GlobalEventService.js';
import { MetaService } from '@/core/MetaService.js';
import { UserEntityService } from '@/core/entities/UserEntityService.js';
import { FastifyReplyError } from '@/misc/fastify-reply-error.js';
import { bindThis } from '@/decorators.js';
import { SigninService } from '../SigninService.js';
import type { FastifyInstance, FastifyRequest, FastifyPluginOptions } from 'fastify';
@Injectable()
export class TwitterServerService {
constructor(
@Inject(DI.config)
private config: Config,
@Inject(DI.redis)
private redisClient: Redis.Redis,
@Inject(DI.usersRepository)
private usersRepository: UsersRepository,
@Inject(DI.userProfilesRepository)
private userProfilesRepository: UserProfilesRepository,
private userEntityService: UserEntityService,
private httpRequestService: HttpRequestService,
private globalEventService: GlobalEventService,
private metaService: MetaService,
private signinService: SigninService,
) {
//this.create = this.create.bind(this);
}
@bindThis
public create(fastify: FastifyInstance, options: FastifyPluginOptions, done: (err?: Error) => void) {
fastify.get('/disconnect/twitter', async (request, reply) => {
if (!this.compareOrigin(request)) {
throw new FastifyReplyError(400, 'invalid origin');
}
const userToken = this.getUserToken(request);
if (userToken == null) {
throw new FastifyReplyError(400, 'signin required');
}
const user = await this.usersRepository.findOneByOrFail({
host: IsNull(),
token: userToken,
});
const profile = await this.userProfilesRepository.findOneByOrFail({ userId: user.id });
delete profile.integrations.twitter;
await this.userProfilesRepository.update(user.id, {
integrations: profile.integrations,
});
// Publish i updated event
this.globalEventService.publishMainStream(user.id, 'meUpdated', await this.userEntityService.pack(user, user, {
detail: true,
includeSecrets: true,
}));
return 'Twitterの連携を解除しました :v:';
});
const getTwAuth = async () => {
const meta = await this.metaService.fetch(true);
if (meta.enableTwitterIntegration && meta.twitterConsumerKey && meta.twitterConsumerSecret) {
return autwh({
consumerKey: meta.twitterConsumerKey,
consumerSecret: meta.twitterConsumerSecret,
callbackUrl: `${this.config.url}/api/tw/cb`,
});
} else {
return null;
}
};
fastify.get('/connect/twitter', async (request, reply) => {
if (!this.compareOrigin(request)) {
throw new FastifyReplyError(400, 'invalid origin');
}
const userToken = this.getUserToken(request);
if (userToken == null) {
throw new FastifyReplyError(400, 'signin required');
}
const twAuth = await getTwAuth();
const twCtx = await twAuth!.begin();
this.redisClient.set(userToken, JSON.stringify(twCtx));
reply.redirect(twCtx.url);
});
fastify.get('/signin/twitter', async (request, reply) => {
const twAuth = await getTwAuth();
const twCtx = await twAuth!.begin();
const sessid = uuid();
this.redisClient.set(sessid, JSON.stringify(twCtx));
reply.setCookie('signin_with_twitter_sid', sessid, {
path: '/',
secure: this.config.url.startsWith('https'),
httpOnly: true,
});
reply.redirect(twCtx.url);
});
fastify.get('/tw/cb', async (request, reply) => {
const userToken = this.getUserToken(request);
const twAuth = await getTwAuth();
if (userToken == null) {
const sessid = request.cookies['signin_with_twitter_sid'];
if (sessid == null) {
throw new FastifyReplyError(400, 'invalid session');
}
const get = new Promise<any>((res, rej) => {
this.redisClient.get(sessid, async (_, twCtx) => {
res(twCtx);
});
});
const twCtx = await get;
const verifier = request.query.oauth_verifier;
if (!verifier || typeof verifier !== 'string') {
throw new FastifyReplyError(400, 'invalid session');
}
const result = await twAuth!.done(JSON.parse(twCtx), verifier);
const link = await this.userProfilesRepository.createQueryBuilder()
.where('"integrations"->\'twitter\'->>\'userId\' = :id', { id: result.userId })
.andWhere('"userHost" IS NULL')
.getOne();
if (link == null) {
throw new FastifyReplyError(404, `@${result.screenName}と連携しているMisskeyアカウントはありませんでした...`);
}
return this.signinService.signin(request, reply, await this.usersRepository.findOneBy({ id: link.userId }) as ILocalUser, true);
} else {
const verifier = request.query.oauth_verifier;
if (!verifier || typeof verifier !== 'string') {
throw new FastifyReplyError(400, 'invalid session');
}
const get = new Promise<any>((res, rej) => {
this.redisClient.get(userToken, async (_, twCtx) => {
res(twCtx);
});
});
const twCtx = await get;
const result = await twAuth!.done(JSON.parse(twCtx), verifier);
const user = await this.usersRepository.findOneByOrFail({
host: IsNull(),
token: userToken,
});
const profile = await this.userProfilesRepository.findOneByOrFail({ userId: user.id });
await this.userProfilesRepository.update(user.id, {
integrations: {
...profile.integrations,
twitter: {
accessToken: result.accessToken,
accessTokenSecret: result.accessTokenSecret,
userId: result.userId,
screenName: result.screenName,
},
},
});
// Publish i updated event
this.globalEventService.publishMainStream(user.id, 'meUpdated', await this.userEntityService.pack(user, user, {
detail: true,
includeSecrets: true,
}));
return `Twitter: @${result.screenName} を、Misskey: @${user.username} に接続しました!`;
}
});
done();
}
@bindThis
private getUserToken(request: FastifyRequest): string | null {
return ((request.headers['cookie'] ?? '').match(/igi=(\w+)/) ?? [null, null])[1];
}
@bindThis
private compareOrigin(request: FastifyRequest): boolean {
function normalizeUrl(url?: string): string {
return url ? url.endsWith('/') ? url.substr(0, url.length - 1) : url : '';
}
const referer = request.headers['referer'];
return (normalizeUrl(referer) === normalizeUrl(this.config.url));
}
}