Compare commits

..

No commits in common. "283275c80dae524f3b20599eb0aacf5f280fdcb3" and "467c609b0f8b262936c2669e67c9eeaa23030eb5" have entirely different histories.

15 changed files with 1204 additions and 54 deletions

View File

@ -354,6 +354,57 @@ export class Meta {
}) })
public swPrivateKey: string | null; public swPrivateKey: string | null;
@Column("boolean", {
default: false,
})
public enableTwitterIntegration: boolean;
@Column("varchar", {
length: 128,
nullable: true,
})
public twitterConsumerKey: string | null;
@Column("varchar", {
length: 128,
nullable: true,
})
public twitterConsumerSecret: string | null;
@Column("boolean", {
default: false,
})
public enableGithubIntegration: boolean;
@Column("varchar", {
length: 128,
nullable: true,
})
public githubClientId: string | null;
@Column("varchar", {
length: 128,
nullable: true,
})
public githubClientSecret: string | null;
@Column("boolean", {
default: false,
})
public enableDiscordIntegration: boolean;
@Column("varchar", {
length: 128,
nullable: true,
})
public discordClientId: string | null;
@Column("varchar", {
length: 128,
nullable: true,
})
public discordClientSecret: string | null;
@Column("varchar", { @Column("varchar", {
length: 128, length: 128,
nullable: true, nullable: true,

View File

@ -1,4 +1,11 @@
import {Column, Entity, Index, JoinColumn, OneToOne, PrimaryColumn,} from "typeorm"; import {
Entity,
Column,
Index,
OneToOne,
JoinColumn,
PrimaryColumn,
} from "typeorm";
import { ffVisibility, notificationTypes } from "@/types.js"; import { ffVisibility, notificationTypes } from "@/types.js";
import { id } from "../id.js"; import { id } from "../id.js";
import { User } from "./user.js"; import { User } from "./user.js";
@ -201,6 +208,11 @@ export class UserProfile {
@JoinColumn() @JoinColumn()
public pinnedPage: Page | null; public pinnedPage: Page | null;
@Column("jsonb", {
default: {},
})
public integrations: Record<string, any>;
@Index() @Index()
@Column("boolean", { @Column("boolean", {
default: false, default: false,

View File

@ -504,6 +504,7 @@ export const UserRepository = db.getRepository(User).extend({
hasUnreadNotification: this.getHasUnreadNotification(user.id), hasUnreadNotification: this.getHasUnreadNotification(user.id),
hasPendingReceivedFollowRequest: hasPendingReceivedFollowRequest:
this.getHasPendingReceivedFollowRequest(user.id), this.getHasPendingReceivedFollowRequest(user.id),
integrations: profile!.integrations,
mutedWords: profile!.mutedWords, mutedWords: profile!.mutedWords,
mutedInstances: profile!.mutedInstances, mutedInstances: profile!.mutedInstances,
mutingNotificationTypes: profile!.mutingNotificationTypes, mutingNotificationTypes: profile!.mutingNotificationTypes,

View File

@ -449,6 +449,11 @@ export const packedMeDetailedOnlySchema = {
nullable: false, nullable: false,
optional: false, optional: false,
}, },
integrations: {
type: "object",
nullable: true,
optional: false,
},
mutedWords: { mutedWords: {
type: "array", type: "array",
nullable: false, nullable: false,

View File

@ -5,8 +5,15 @@ import config from "@/config/index.js";
import { registerOrFetchInstanceDoc } from "@/services/register-or-fetch-instance-doc.js"; import { registerOrFetchInstanceDoc } from "@/services/register-or-fetch-instance-doc.js";
import type { Note } from "@/models/entities/note.js"; import type { Note } from "@/models/entities/note.js";
import { updateUsertags } from "@/services/update-hashtag.js"; import { updateUsertags } from "@/services/update-hashtag.js";
import {Followings, Instances, UserProfiles, UserPublickeys, Users,} from "@/models/index.js"; import {
import type {CacheableUser, IRemoteUser} from "@/models/entities/user.js"; Users,
Instances,
DriveFiles,
Followings,
UserProfiles,
UserPublickeys,
} from "@/models/index.js";
import type { IRemoteUser, CacheableUser } from "@/models/entities/user.js";
import { User } from "@/models/entities/user.js"; import { User } from "@/models/entities/user.js";
import type { Emoji } from "@/models/entities/emoji.js"; import type { Emoji } from "@/models/entities/emoji.js";
import { UserNotePining } from "@/models/entities/user-note-pining.js"; import { UserNotePining } from "@/models/entities/user-note-pining.js";
@ -27,19 +34,19 @@ import {db} from "@/db/postgre.js";
import { apLogger } from "../logger.js"; import { apLogger } from "../logger.js";
import { htmlToMfm } from "../misc/html-to-mfm.js"; import { htmlToMfm } from "../misc/html-to-mfm.js";
import { fromHtml } from "../../../mfm/from-html.js"; import { fromHtml } from "../../../mfm/from-html.js";
import type {IActor, IObject} from "../type.js"; import type { IActor, IObject, IApPropertyValue } from "../type.js";
import { import {
getApId,
getApType,
getOneApHrefNullable,
isActor,
isCollection,
isCollectionOrOrderedCollection, isCollectionOrOrderedCollection,
isCollection,
getApId,
getOneApHrefNullable,
isPropertyValue, isPropertyValue,
getApType,
isActor,
} from "../type.js"; } from "../type.js";
import Resolver from "../resolver.js"; import Resolver from "../resolver.js";
import { extractApHashtags } from "./tag.js"; import { extractApHashtags } from "./tag.js";
import {extractEmojis, resolveNote} from "./note.js"; import { resolveNote, extractEmojis } from "./note.js";
import { resolveImage } from "./image.js"; import { resolveImage } from "./image.js";
const logger = apLogger; const logger = apLogger;
@ -581,6 +588,39 @@ export async function resolvePerson(
return await createPerson(uri, resolver); return await createPerson(uri, resolver);
} }
const services: {
[x: string]: (id: string, username: string) => any;
} = {
"misskey:authentication:twitter": (userId, screenName) => ({
userId,
screenName,
}),
"misskey:authentication:github": (id, login) => ({ id, login }),
"misskey:authentication:discord": (id, name) => $discord(id, name),
};
const $discord = (id: string, name: string) => {
if (typeof name !== "string") {
name = "unknown#0000";
}
const [username, discriminator] = name.split("#");
return { id, username, discriminator };
};
function addService(target: { [x: string]: any }, source: IApPropertyValue) {
const service = services[source.name];
if (typeof source.value !== "string") {
source.value = "unknown";
}
const [id, username] = source.value.split("@");
if (service) {
target[source.name.split(":")[2]] = service(id, username);
}
}
export function analyzeAttachments( export function analyzeAttachments(
attachments: IObject | IObject[] | undefined, attachments: IObject | IObject[] | undefined,
) { ) {
@ -588,11 +628,13 @@ export function analyzeAttachments(
name: string; name: string;
value: string; value: string;
}[] = []; }[] = [];
const services: { [x: string]: any } = {};
if (Array.isArray(attachments)) { if (Array.isArray(attachments)) {
for (const attachment of attachments.filter(isPropertyValue)) { for (const attachment of attachments.filter(isPropertyValue)) {
// TODO: This doesn't sound right if (isPropertyValue(attachment.identifier)) {
if (!isPropertyValue(attachment.identifier)) { addService(services, attachment.identifier);
} else {
fields.push({ fields.push({
name: attachment.name, name: attachment.name,
value: fromHtml(attachment.value), value: fromHtml(attachment.value),
@ -601,7 +643,7 @@ export function analyzeAttachments(
} }
} }
return { fields }; return { fields, services };
} }
export async function updateFeatured(userId: User["id"], resolver?: Resolver) { export async function updateFeatured(userId: User["id"], resolver?: Resolver) {

View File

@ -272,6 +272,7 @@ import * as ep___recommendedInstances from "./endpoints/recommended-instances.js
import * as ep___pinnedUsers from "./endpoints/pinned-users.js"; import * as ep___pinnedUsers from "./endpoints/pinned-users.js";
import * as ep___customMOTD from "./endpoints/custom-motd.js"; import * as ep___customMOTD from "./endpoints/custom-motd.js";
import * as ep___customSplashIcons from "./endpoints/custom-splash-icons.js"; import * as ep___customSplashIcons from "./endpoints/custom-splash-icons.js";
import * as ep___latestVersion from "./endpoints/latest-version.js";
import * as ep___release from "./endpoints/release.js"; import * as ep___release from "./endpoints/release.js";
import * as ep___promo_read from "./endpoints/promo/read.js"; import * as ep___promo_read from "./endpoints/promo/read.js";
import * as ep___requestResetPassword from "./endpoints/request-reset-password.js"; import * as ep___requestResetPassword from "./endpoints/request-reset-password.js";
@ -608,6 +609,7 @@ const eps = [
["renote-mute/list", ep___renote_mute_list], ["renote-mute/list", ep___renote_mute_list],
["custom-motd", ep___customMOTD], ["custom-motd", ep___customMOTD],
["custom-splash-icons", ep___customSplashIcons], ["custom-splash-icons", ep___customSplashIcons],
["latest-version", ep___latestVersion],
["release", ep___release], ["release", ep___release],
["promo/read", ep___promo_read], ["promo/read", ep___promo_read],
["request-reset-password", ep___requestResetPassword], ["request-reset-password", ep___requestResetPassword],

View File

@ -1,7 +1,8 @@
import config from "@/config/index.js"; import config from "@/config/index.js";
import { fetchMeta } from "@/misc/fetch-meta.js"; import { fetchMeta } from "@/misc/fetch-meta.js";
import {MAX_CAPTION_TEXT_LENGTH, MAX_NOTE_TEXT_LENGTH} from "@/const.js"; import { MAX_NOTE_TEXT_LENGTH, MAX_CAPTION_TEXT_LENGTH } from "@/const.js";
import define from "../../define.js"; import define from "../../define.js";
import { Exp } from "@tensorflow/tfjs";
export const meta = { export const meta = {
tags: ["meta"], tags: ["meta"],
@ -169,6 +170,21 @@ export const meta = {
optional: false, optional: false,
nullable: 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: { enableServiceWorker: {
type: "boolean", type: "boolean",
optional: false, optional: false,
@ -310,6 +326,36 @@ export const meta = {
nullable: true, nullable: true,
format: "id", 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: { summaryProxy: {
type: "string", type: "string",
optional: true, optional: true,
@ -486,6 +532,9 @@ export default define(meta, paramDef, async (ps, me) => {
defaultLightTheme: instance.defaultLightTheme, defaultLightTheme: instance.defaultLightTheme,
defaultDarkTheme: instance.defaultDarkTheme, defaultDarkTheme: instance.defaultDarkTheme,
enableEmail: instance.enableEmail, enableEmail: instance.enableEmail,
enableTwitterIntegration: instance.enableTwitterIntegration,
enableGithubIntegration: instance.enableGithubIntegration,
enableDiscordIntegration: instance.enableDiscordIntegration,
enableServiceWorker: instance.enableServiceWorker, enableServiceWorker: instance.enableServiceWorker,
translatorAvailable: translatorAvailable:
instance.deeplAuthKey != null || instance.libreTranslateApiUrl != null, instance.deeplAuthKey != null || instance.libreTranslateApiUrl != null,
@ -512,6 +561,12 @@ export default define(meta, paramDef, async (ps, me) => {
enableSensitiveMediaDetectionForVideos: enableSensitiveMediaDetectionForVideos:
instance.enableSensitiveMediaDetectionForVideos, instance.enableSensitiveMediaDetectionForVideos,
proxyAccountId: instance.proxyAccountId, proxyAccountId: instance.proxyAccountId,
twitterConsumerKey: instance.twitterConsumerKey,
twitterConsumerSecret: instance.twitterConsumerSecret,
githubClientId: instance.githubClientId,
githubClientSecret: instance.githubClientSecret,
discordClientId: instance.discordClientId,
discordClientSecret: instance.discordClientSecret,
summalyProxy: instance.summalyProxy, summalyProxy: instance.summalyProxy,
email: instance.email, email: instance.email,
smtpSecure: instance.smtpSecure, smtpSecure: instance.smtpSecure,

View File

@ -46,6 +46,13 @@ export default define(meta, paramDef, async (ps, me) => {
}; };
} }
const maskedKeys = ["accessToken", "accessTokenSecret", "refreshToken"];
Object.keys(profile.integrations).forEach((integration) => {
maskedKeys.forEach(
(key) => (profile.integrations[integration][key] = "<MASKED>"),
);
});
const signins = await Signins.findBy({ userId: user.id }); const signins = await Signins.findBy({ userId: user.id });
return { return {
@ -59,6 +66,7 @@ export default define(meta, paramDef, async (ps, me) => {
carefulBot: profile.carefulBot, carefulBot: profile.carefulBot,
injectFeaturedNote: profile.injectFeaturedNote, injectFeaturedNote: profile.injectFeaturedNote,
receiveAnnouncementEmail: profile.receiveAnnouncementEmail, receiveAnnouncementEmail: profile.receiveAnnouncementEmail,
integrations: profile.integrations,
mutedWords: profile.mutedWords, mutedWords: profile.mutedWords,
mutedInstances: profile.mutedInstances, mutedInstances: profile.mutedInstances,
mutingNotificationTypes: profile.mutingNotificationTypes, mutingNotificationTypes: profile.mutingNotificationTypes,

View File

@ -1,5 +1,6 @@
import { Meta } from "@/models/entities/meta.js"; import { Meta } from "@/models/entities/meta.js";
import { insertModerationLog } from "@/services/insert-moderation-log.js"; import { insertModerationLog } from "@/services/insert-moderation-log.js";
import { DB_MAX_NOTE_TEXT_LENGTH } from "@/misc/hard-limits.js";
import { db } from "@/db/postgre.js"; import { db } from "@/db/postgre.js";
import define from "../../define.js"; import define from "../../define.js";
@ -132,6 +133,15 @@ export const paramDef = {
deeplIsPro: { type: "boolean" }, deeplIsPro: { type: "boolean" },
libreTranslateApiUrl: { type: "string", nullable: true }, libreTranslateApiUrl: { type: "string", nullable: true },
libreTranslateApiKey: { type: "string", nullable: true }, libreTranslateApiKey: { type: "string", nullable: true },
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" }, enableEmail: { type: "boolean" },
email: { type: "string", nullable: true }, email: { type: "string", nullable: true },
smtpSecure: { type: "boolean" }, smtpSecure: { type: "boolean" },
@ -375,6 +385,42 @@ export default define(meta, paramDef, async (ps, me) => {
set.summalyProxy = ps.summalyProxy; 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) { if (ps.enableEmail !== undefined) {
set.enableEmail = ps.enableEmail; set.enableEmail = ps.enableEmail;
} }

View File

@ -0,0 +1,29 @@
import define from "../define.js";
export const meta = {
tags: ["meta"],
requireCredential: false,
requireCredentialPrivateMode: true,
} as const;
export const paramDef = {
type: "object",
properties: {},
required: [],
} as const;
export default define(meta, paramDef, async () => {
let tag_name;
await fetch(
"https://codeberg.org/api/v1/repos/calckey/calckey/releases?draft=false&pre-release=false&page=1&limit=1",
)
.then((response) => response.json())
.then((data) => {
tag_name = data[0].tag_name;
});
return {
tag_name,
};
});

View File

@ -3,7 +3,7 @@ import {IsNull, MoreThan} from "typeorm";
import config from "@/config/index.js"; import config from "@/config/index.js";
import { fetchMeta } from "@/misc/fetch-meta.js"; import { fetchMeta } from "@/misc/fetch-meta.js";
import { Ads, Emojis, Users } from "@/models/index.js"; import { Ads, Emojis, Users } from "@/models/index.js";
import {MAX_CAPTION_TEXT_LENGTH, MAX_NOTE_TEXT_LENGTH} from "@/const.js"; import { MAX_NOTE_TEXT_LENGTH, MAX_CAPTION_TEXT_LENGTH } from "@/const.js";
import define from "../define.js"; import define from "../define.js";
export const meta = { export const meta = {
@ -268,6 +268,21 @@ export const meta = {
optional: false, optional: false,
nullable: 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: { enableServiceWorker: {
type: "boolean", type: "boolean",
optional: false, optional: false,
@ -328,6 +343,21 @@ export const meta = {
optional: false, optional: false,
nullable: 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: { serviceWorker: {
type: "boolean", type: "boolean",
optional: false, optional: false,
@ -452,6 +482,10 @@ export default define(meta, paramDef, async (ps, me) => {
})), })),
enableEmail: instance.enableEmail, enableEmail: instance.enableEmail,
enableTwitterIntegration: instance.enableTwitterIntegration,
enableGithubIntegration: instance.enableGithubIntegration,
enableDiscordIntegration: instance.enableDiscordIntegration,
enableServiceWorker: instance.enableServiceWorker, enableServiceWorker: instance.enableServiceWorker,
translatorAvailable: translatorAvailable:
@ -491,6 +525,9 @@ export default define(meta, paramDef, async (ps, me) => {
hcaptcha: instance.enableHcaptcha, hcaptcha: instance.enableHcaptcha,
recaptcha: instance.enableRecaptcha, recaptcha: instance.enableRecaptcha,
objectStorage: instance.useObjectStorage, objectStorage: instance.useObjectStorage,
twitter: instance.enableTwitterIntegration,
github: instance.enableGithubIntegration,
discord: instance.enableDiscordIntegration,
serviceWorker: instance.enableServiceWorker, serviceWorker: instance.enableServiceWorker,
postEditing: instance.experimentalFeatures?.postEditing || false, postEditing: instance.experimentalFeatures?.postEditing || false,
postImports: instance.experimentalFeatures?.postImports || false, postImports: instance.experimentalFeatures?.postImports || false,

View File

@ -16,6 +16,9 @@ import signup from "./private/signup.js";
import signin from "./private/signin.js"; import signin from "./private/signin.js";
import signupPending from "./private/signup-pending.js"; import signupPending from "./private/signup-pending.js";
import verifyEmail from "./private/verify-email.js"; import verifyEmail from "./private/verify-email.js";
import discord from "./service/discord.js";
import github from "./service/github.js";
import twitter from "./service/twitter.js";
// Init app // Init app
const app = new Koa(); const app = new Koa();
@ -102,6 +105,10 @@ router.post("/signin", signin);
router.post("/signup-pending", signupPending); router.post("/signup-pending", signupPending);
router.post("/verify-email", verifyEmail); router.post("/verify-email", verifyEmail);
router.use(discord.routes());
router.use(github.routes());
router.use(twitter.routes());
router.post("/miauth/:session/check", async (ctx) => { router.post("/miauth/:session/check", async (ctx) => {
const token = await AccessTokens.findOneBy({ const token = await AccessTokens.findOneBy({
session: ctx.params.session, session: ctx.params.session,

View File

@ -0,0 +1,333 @@
import type Koa from "koa";
import Router from "@koa/router";
import { OAuth2 } from "oauth";
import { v4 as uuid } from "uuid";
import { IsNull } from "typeorm";
import { getJson } from "@/misc/fetch.js";
import config from "@/config/index.js";
import { publishMainStream } from "@/services/stream.js";
import { fetchMeta } from "@/misc/fetch-meta.js";
import { Users, UserProfiles } from "@/models/index.js";
import type { ILocalUser } from "@/models/entities/user.js";
import { redisClient } from "../../../db/redis.js";
import signin from "../common/signin.js";
function getUserToken(ctx: Koa.BaseContext): string | null {
return ((ctx.headers["cookie"] || "").match(/igi=(\w+)/) || [null, null])[1];
}
function compareOrigin(ctx: Koa.BaseContext): boolean {
function normalizeUrl(url?: string): string {
return url ? (url.endsWith("/") ? url.substr(0, url.length - 1) : url) : "";
}
const referer = ctx.headers["referer"];
return normalizeUrl(referer) === normalizeUrl(config.url);
}
// Init router
const router = new Router();
router.get("/disconnect/discord", async (ctx) => {
if (!compareOrigin(ctx)) {
ctx.throw(400, "invalid origin");
return;
}
const userToken = getUserToken(ctx);
if (!userToken) {
ctx.throw(400, "signin required");
return;
}
const user = await Users.findOneByOrFail({
host: IsNull(),
token: userToken,
});
const profile = await UserProfiles.findOneByOrFail({ userId: user.id });
profile.integrations.discord = undefined;
await UserProfiles.update(user.id, {
integrations: profile.integrations,
});
ctx.body = "Discordの連携を解除しました :v:";
// Publish i updated event
publishMainStream(
user.id,
"meUpdated",
await Users.pack(user, user, {
detail: true,
includeSecrets: true,
}),
);
});
async function getOAuth2() {
const meta = await fetchMeta(true);
if (meta.enableDiscordIntegration) {
return new OAuth2(
meta.discordClientId!,
meta.discordClientSecret!,
"https://discord.com/",
"api/oauth2/authorize",
"api/oauth2/token",
);
} else {
return null;
}
}
router.get("/connect/discord", async (ctx) => {
if (!compareOrigin(ctx)) {
ctx.throw(400, "invalid origin");
return;
}
const userToken = getUserToken(ctx);
if (!userToken) {
ctx.throw(400, "signin required");
return;
}
const params = {
redirect_uri: `${config.url}/api/dc/cb`,
scope: ["identify"],
state: uuid(),
response_type: "code",
};
redisClient.set(userToken, JSON.stringify(params));
const oauth2 = await getOAuth2();
ctx.redirect(oauth2!.getAuthorizeUrl(params));
});
router.get("/signin/discord", async (ctx) => {
const sessid = uuid();
const params = {
redirect_uri: `${config.url}/api/dc/cb`,
scope: ["identify"],
state: uuid(),
response_type: "code",
};
ctx.cookies.set("signin_with_discord_sid", sessid, {
path: "/",
secure: config.url.startsWith("https"),
httpOnly: true,
});
redisClient.set(sessid, JSON.stringify(params));
const oauth2 = await getOAuth2();
ctx.redirect(oauth2!.getAuthorizeUrl(params));
});
router.get("/dc/cb", async (ctx) => {
const userToken = getUserToken(ctx);
const oauth2 = await getOAuth2();
if (!userToken) {
const sessid = ctx.cookies.get("signin_with_discord_sid");
if (!sessid) {
ctx.throw(400, "invalid session");
return;
}
const code = ctx.query.code;
if (!code || typeof code !== "string") {
ctx.throw(400, "invalid session");
return;
}
const { redirect_uri, state } = await new Promise<any>((res, rej) => {
redisClient.get(sessid, async (_, state) => {
res(JSON.parse(state));
});
});
if (ctx.query.state !== state) {
ctx.throw(400, "invalid session");
return;
}
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 getJson(
"https://discord.com/api/users/@me",
"*/*",
10 * 1000,
{
Authorization: `Bearer ${accessToken}`,
},
)) as Record<string, unknown>;
if (
typeof id !== "string" ||
typeof username !== "string" ||
typeof discriminator !== "string"
) {
ctx.throw(400, "invalid session");
return;
}
const profile = await UserProfiles.createQueryBuilder()
.where("\"integrations\"->'discord'->>'id' = :id", { id: id })
.andWhere('"userHost" IS NULL')
.getOne();
if (profile == null) {
ctx.throw(
404,
`@${username}#${discriminator}と連携しているMisskeyアカウントはありませんでした...`,
);
return;
}
await UserProfiles.update(profile.userId, {
integrations: {
...profile.integrations,
discord: {
id: id,
accessToken: accessToken,
refreshToken: refreshToken,
expiresDate: expiresDate,
username: username,
discriminator: discriminator,
},
},
});
signin(
ctx,
(await Users.findOneBy({ id: profile.userId })) as ILocalUser,
true,
);
} else {
const code = ctx.query.code;
if (!code || typeof code !== "string") {
ctx.throw(400, "invalid session");
return;
}
const { redirect_uri, state } = await new Promise<any>((res, rej) => {
redisClient.get(userToken, async (_, state) => {
res(JSON.parse(state));
});
});
if (ctx.query.state !== state) {
ctx.throw(400, "invalid session");
return;
}
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 getJson(
"https://discord.com/api/users/@me",
"*/*",
10 * 1000,
{
Authorization: `Bearer ${accessToken}`,
},
)) as Record<string, unknown>;
if (
typeof id !== "string" ||
typeof username !== "string" ||
typeof discriminator !== "string"
) {
ctx.throw(400, "invalid session");
return;
}
const user = await Users.findOneByOrFail({
host: IsNull(),
token: userToken,
});
const profile = await UserProfiles.findOneByOrFail({ userId: user.id });
await UserProfiles.update(user.id, {
integrations: {
...profile.integrations,
discord: {
accessToken: accessToken,
refreshToken: refreshToken,
expiresDate: expiresDate,
id: id,
username: username,
discriminator: discriminator,
},
},
});
ctx.body = `Discord: @${username}#${discriminator} を、Misskey: @${user.username} に接続しました!`;
// Publish i updated event
publishMainStream(
user.id,
"meUpdated",
await Users.pack(user, user, {
detail: true,
includeSecrets: true,
}),
);
}
});
export default router;

View File

@ -0,0 +1,296 @@
import type Koa from "koa";
import Router from "@koa/router";
import { OAuth2 } from "oauth";
import { v4 as uuid } from "uuid";
import { IsNull } from "typeorm";
import { getJson } from "@/misc/fetch.js";
import config from "@/config/index.js";
import { publishMainStream } from "@/services/stream.js";
import { fetchMeta } from "@/misc/fetch-meta.js";
import { Users, UserProfiles } from "@/models/index.js";
import type { ILocalUser } from "@/models/entities/user.js";
import { redisClient } from "../../../db/redis.js";
import signin from "../common/signin.js";
function getUserToken(ctx: Koa.BaseContext): string | null {
return ((ctx.headers["cookie"] || "").match(/igi=(\w+)/) || [null, null])[1];
}
function compareOrigin(ctx: Koa.BaseContext): boolean {
function normalizeUrl(url?: string): string {
return url ? (url.endsWith("/") ? url.substr(0, url.length - 1) : url) : "";
}
const referer = ctx.headers["referer"];
return normalizeUrl(referer) === normalizeUrl(config.url);
}
// Init router
const router = new Router();
router.get("/disconnect/github", async (ctx) => {
if (!compareOrigin(ctx)) {
ctx.throw(400, "invalid origin");
return;
}
const userToken = getUserToken(ctx);
if (!userToken) {
ctx.throw(400, "signin required");
return;
}
const user = await Users.findOneByOrFail({
host: IsNull(),
token: userToken,
});
const profile = await UserProfiles.findOneByOrFail({ userId: user.id });
profile.integrations.github = undefined;
await UserProfiles.update(user.id, {
integrations: profile.integrations,
});
ctx.body = "GitHubの連携を解除しました :v:";
// Publish i updated event
publishMainStream(
user.id,
"meUpdated",
await Users.pack(user, user, {
detail: true,
includeSecrets: true,
}),
);
});
async function getOath2() {
const meta = await fetchMeta(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;
}
}
router.get("/connect/github", async (ctx) => {
if (!compareOrigin(ctx)) {
ctx.throw(400, "invalid origin");
return;
}
const userToken = getUserToken(ctx);
if (!userToken) {
ctx.throw(400, "signin required");
return;
}
const params = {
redirect_uri: `${config.url}/api/gh/cb`,
scope: ["read:user"],
state: uuid(),
};
redisClient.set(userToken, JSON.stringify(params));
const oauth2 = await getOath2();
ctx.redirect(oauth2!.getAuthorizeUrl(params));
});
router.get("/signin/github", async (ctx) => {
const sessid = uuid();
const params = {
redirect_uri: `${config.url}/api/gh/cb`,
scope: ["read:user"],
state: uuid(),
};
ctx.cookies.set("signin_with_github_sid", sessid, {
path: "/",
secure: config.url.startsWith("https"),
httpOnly: true,
});
redisClient.set(sessid, JSON.stringify(params));
const oauth2 = await getOath2();
ctx.redirect(oauth2!.getAuthorizeUrl(params));
});
router.get("/gh/cb", async (ctx) => {
const userToken = getUserToken(ctx);
const oauth2 = await getOath2();
if (!userToken) {
const sessid = ctx.cookies.get("signin_with_github_sid");
if (!sessid) {
ctx.throw(400, "invalid session");
return;
}
const code = ctx.query.code;
if (!code || typeof code !== "string") {
ctx.throw(400, "invalid session");
return;
}
const { redirect_uri, state } = await new Promise<any>((res, rej) => {
redisClient.get(sessid, async (_, state) => {
res(JSON.parse(state));
});
});
if (ctx.query.state !== state) {
ctx.throw(400, "invalid session");
return;
}
const { accessToken } = await new Promise<any>((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 getJson(
"https://api.github.com/user",
"application/vnd.github.v3+json",
10 * 1000,
{
Authorization: `bearer ${accessToken}`,
},
)) as Record<string, unknown>;
if (typeof login !== "string" || typeof id !== "string") {
ctx.throw(400, "invalid session");
return;
}
const link = await UserProfiles.createQueryBuilder()
.where("\"integrations\"->'github'->>'id' = :id", { id: id })
.andWhere('"userHost" IS NULL')
.getOne();
if (link == null) {
ctx.throw(
404,
`@${login}と連携しているMisskeyアカウントはありませんでした...`,
);
return;
}
signin(
ctx,
(await Users.findOneBy({ id: link.userId })) as ILocalUser,
true,
);
} else {
const code = ctx.query.code;
if (!code || typeof code !== "string") {
ctx.throw(400, "invalid session");
return;
}
const { redirect_uri, state } = await new Promise<any>((res, rej) => {
redisClient.get(userToken, async (_, state) => {
res(JSON.parse(state));
});
});
if (ctx.query.state !== state) {
ctx.throw(400, "invalid session");
return;
}
const { accessToken } = await new Promise<any>((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 getJson(
"https://api.github.com/user",
"application/vnd.github.v3+json",
10 * 1000,
{
Authorization: `bearer ${accessToken}`,
},
)) as Record<string, unknown>;
if (typeof login !== "string" || typeof id !== "string") {
ctx.throw(400, "invalid session");
return;
}
const user = await Users.findOneByOrFail({
host: IsNull(),
token: userToken,
});
const profile = await UserProfiles.findOneByOrFail({ userId: user.id });
await UserProfiles.update(user.id, {
integrations: {
...profile.integrations,
github: {
accessToken: accessToken,
id: id,
login: login,
},
},
});
ctx.body = `GitHub: @${login} を、Misskey: @${user.username} に接続しました!`;
// Publish i updated event
publishMainStream(
user.id,
"meUpdated",
await Users.pack(user, user, {
detail: true,
includeSecrets: true,
}),
);
}
});
export default router;

View File

@ -0,0 +1,226 @@
import type Koa from "koa";
import Router from "@koa/router";
import { v4 as uuid } from "uuid";
import autwh from "autwh";
import { IsNull } from "typeorm";
import { publishMainStream } from "@/services/stream.js";
import config from "@/config/index.js";
import { fetchMeta } from "@/misc/fetch-meta.js";
import { Users, UserProfiles } from "@/models/index.js";
import type { ILocalUser } from "@/models/entities/user.js";
import signin from "../common/signin.js";
import { redisClient } from "../../../db/redis.js";
function getUserToken(ctx: Koa.BaseContext): string | null {
return ((ctx.headers["cookie"] || "").match(/igi=(\w+)/) || [null, null])[1];
}
function compareOrigin(ctx: Koa.BaseContext): boolean {
function normalizeUrl(url?: string): string {
return url == null
? ""
: url.endsWith("/")
? url.substr(0, url.length - 1)
: url;
}
const referer = ctx.headers["referer"];
return normalizeUrl(referer) === normalizeUrl(config.url);
}
// Init router
const router = new Router();
router.get("/disconnect/twitter", async (ctx) => {
if (!compareOrigin(ctx)) {
ctx.throw(400, "invalid origin");
return;
}
const userToken = getUserToken(ctx);
if (userToken == null) {
ctx.throw(400, "signin required");
return;
}
const user = await Users.findOneByOrFail({
host: IsNull(),
token: userToken,
});
const profile = await UserProfiles.findOneByOrFail({ userId: user.id });
profile.integrations.twitter = undefined;
await UserProfiles.update(user.id, {
integrations: profile.integrations,
});
ctx.body = "Twitterの連携を解除しました :v:";
// Publish i updated event
publishMainStream(
user.id,
"meUpdated",
await Users.pack(user, user, {
detail: true,
includeSecrets: true,
}),
);
});
async function getTwAuth() {
const meta = await fetchMeta(true);
if (
meta.enableTwitterIntegration &&
meta.twitterConsumerKey &&
meta.twitterConsumerSecret
) {
return autwh({
consumerKey: meta.twitterConsumerKey,
consumerSecret: meta.twitterConsumerSecret,
callbackUrl: `${config.url}/api/tw/cb`,
});
} else {
return null;
}
}
router.get("/connect/twitter", async (ctx) => {
if (!compareOrigin(ctx)) {
ctx.throw(400, "invalid origin");
return;
}
const userToken = getUserToken(ctx);
if (userToken == null) {
ctx.throw(400, "signin required");
return;
}
const twAuth = await getTwAuth();
const twCtx = await twAuth!.begin();
redisClient.set(userToken, JSON.stringify(twCtx));
ctx.redirect(twCtx.url);
});
router.get("/signin/twitter", async (ctx) => {
const twAuth = await getTwAuth();
const twCtx = await twAuth!.begin();
const sessid = uuid();
redisClient.set(sessid, JSON.stringify(twCtx));
ctx.cookies.set("signin_with_twitter_sid", sessid, {
path: "/",
secure: config.url.startsWith("https"),
httpOnly: true,
});
ctx.redirect(twCtx.url);
});
router.get("/tw/cb", async (ctx) => {
const userToken = getUserToken(ctx);
const twAuth = await getTwAuth();
if (userToken == null) {
const sessid = ctx.cookies.get("signin_with_twitter_sid");
if (sessid == null) {
ctx.throw(400, "invalid session");
return;
}
const get = new Promise<any>((res, rej) => {
redisClient.get(sessid, async (_, twCtx) => {
res(twCtx);
});
});
const twCtx = await get;
const verifier = ctx.query.oauth_verifier;
if (!verifier || typeof verifier !== "string") {
ctx.throw(400, "invalid session");
return;
}
const result = await twAuth!.done(JSON.parse(twCtx), verifier);
const link = await UserProfiles.createQueryBuilder()
.where("\"integrations\"->'twitter'->>'userId' = :id", {
id: result.userId,
})
.andWhere('"userHost" IS NULL')
.getOne();
if (link == null) {
ctx.throw(
404,
`@${result.screenName}と連携しているMisskeyアカウントはありませんでした...`,
);
return;
}
signin(
ctx,
(await Users.findOneBy({ id: link.userId })) as ILocalUser,
true,
);
} else {
const verifier = ctx.query.oauth_verifier;
if (!verifier || typeof verifier !== "string") {
ctx.throw(400, "invalid session");
return;
}
const get = new Promise<any>((res, rej) => {
redisClient.get(userToken, async (_, twCtx) => {
res(twCtx);
});
});
const twCtx = await get;
const result = await twAuth!.done(JSON.parse(twCtx), verifier);
const user = await Users.findOneByOrFail({
host: IsNull(),
token: userToken,
});
const profile = await UserProfiles.findOneByOrFail({ userId: user.id });
await UserProfiles.update(user.id, {
integrations: {
...profile.integrations,
twitter: {
accessToken: result.accessToken,
accessTokenSecret: result.accessTokenSecret,
userId: result.userId,
screenName: result.screenName,
},
},
});
ctx.body = `Twitter: @${result.screenName} を、Misskey: @${user.username} に接続しました!`;
// Publish i updated event
publishMainStream(
user.id,
"meUpdated",
await Users.pack(user, user, {
detail: true,
includeSecrets: true,
}),
);
}
});
export default router;