Log in with Matrix
This commit is contained in:
@@ -26,7 +26,7 @@ const schema = {
|
||||
as.router.post("/api/autocreate", defineEventHandler(async event => {
|
||||
const parsedBody = await readValidatedBody(event, schema.autocreate.parse)
|
||||
const session = await useSession(event, {password: reg.as_token})
|
||||
if (!(session.data.managedGuilds || []).includes(parsedBody.guild_id)) throw createError({status: 403, message: "Forbidden", data: "Can't change settings for a guild you don't have Manage Server permissions in"})
|
||||
if (!(session.data.managedGuilds || []).concat(session.data.matrixGuilds || []).includes(parsedBody.guild_id)) throw createError({status: 403, message: "Forbidden", data: "Can't change settings for a guild you don't have Manage Server permissions in"})
|
||||
|
||||
db.prepare("UPDATE guild_active SET autocreate = ? WHERE guild_id = ?").run(+!!parsedBody.autocreate, parsedBody.guild_id)
|
||||
return null // 204
|
||||
@@ -35,7 +35,7 @@ as.router.post("/api/autocreate", defineEventHandler(async event => {
|
||||
as.router.post("/api/privacy-level", defineEventHandler(async event => {
|
||||
const parsedBody = await readValidatedBody(event, schema.privacyLevel.parse)
|
||||
const session = await useSession(event, {password: reg.as_token})
|
||||
if (!(session.data.managedGuilds || []).includes(parsedBody.guild_id)) throw createError({status: 403, message: "Forbidden", data: "Can't change settings for a guild you don't have Manage Server permissions in"})
|
||||
if (!(session.data.managedGuilds || []).concat(session.data.matrixGuilds || []).includes(parsedBody.guild_id)) throw createError({status: 403, message: "Forbidden", data: "Can't change settings for a guild you don't have Manage Server permissions in"})
|
||||
|
||||
const i = levels.indexOf(parsedBody.level)
|
||||
assert.notEqual(i, -1)
|
||||
|
||||
@@ -114,7 +114,7 @@ as.router.get("/guild", defineEventHandler(async event => {
|
||||
const guild = discord.guilds.get(guild_id)
|
||||
|
||||
// Permission problems
|
||||
if (!guild_id || !guild || !session.data.managedGuilds || !session.data.managedGuilds.includes(guild_id)) {
|
||||
if (!guild_id || !guild || !(session.data.managedGuilds || []).concat(session.data.matrixGuilds || []).includes(guild_id)) {
|
||||
return pugSync.render(event, "guild_access_denied.pug", {guild_id})
|
||||
}
|
||||
|
||||
@@ -159,7 +159,7 @@ as.router.post("/api/invite", defineEventHandler(async event => {
|
||||
// Check guild ID or nonce
|
||||
if (parsedBody.guild_id) {
|
||||
var guild_id = parsedBody.guild_id
|
||||
if (!(session.data.managedGuilds || []).includes(guild_id)) throw createError({status: 403, message: "Forbidden", data: "Can't invite users to a guild you don't have Manage Server permissions in"})
|
||||
if (!(session.data.managedGuilds || []).concat(session.data.matrixGuilds || []).includes(guild_id)) throw createError({status: 403, message: "Forbidden", data: "Can't invite users to a guild you don't have Manage Server permissions in"})
|
||||
} else if (parsedBody.nonce) {
|
||||
if (!validNonce.has(parsedBody.nonce)) throw createError({status: 403, message: "Nonce expired", data: "Nonce means number-used-once, and, well, you tried to use it twice..."})
|
||||
let ok = validNonce.get(parsedBody.nonce)
|
||||
|
||||
@@ -33,7 +33,7 @@ as.router.post("/api/link", defineEventHandler(async event => {
|
||||
|
||||
// Check guild ID or nonce
|
||||
const guildID = parsedBody.guild_id
|
||||
if (!(session.data.managedGuilds || []).includes(guildID)) throw createError({status: 403, message: "Forbidden", data: "Can't edit a guild you don't have Manage Server permissions in"})
|
||||
if (!(session.data.managedGuilds || []).concat(session.data.matrixGuilds || []).includes(guildID)) throw createError({status: 403, message: "Forbidden", data: "Can't edit a guild you don't have Manage Server permissions in"})
|
||||
|
||||
// Check guild is bridged
|
||||
const guild = discord.guilds.get(guildID)
|
||||
@@ -81,7 +81,7 @@ as.router.post("/api/unlink", defineEventHandler(async event => {
|
||||
const session = await useSession(event, {password: reg.as_token})
|
||||
|
||||
// Check guild ID or nonce
|
||||
if (!(session.data.managedGuilds || []).includes(guild_id)) throw createError({status: 403, message: "Forbidden", data: "Can't edit a guild you don't have Manage Server permissions in"})
|
||||
if (!(session.data.managedGuilds || []).concat(session.data.matrixGuilds || []).includes(guild_id)) throw createError({status: 403, message: "Forbidden", data: "Can't edit a guild you don't have Manage Server permissions in"})
|
||||
|
||||
// Check channel is part of this guild
|
||||
const channel = discord.channels.get(channel_id)
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
// @ts-check
|
||||
|
||||
const {z} = require("zod")
|
||||
const {randomUUID} = require("crypto")
|
||||
const {defineEventHandler, getValidatedQuery, sendRedirect, readValidatedBody, useSession, createError, getRequestHeader} = require("h3")
|
||||
const {SnowTransfer} = require("snowtransfer")
|
||||
const DiscordTypes = require("discord-api-types/v10")
|
||||
const fetch = require("node-fetch")
|
||||
const getRelativePath = require("get-relative-path")
|
||||
const {LRUCache} = require("lru-cache")
|
||||
|
||||
const {as, db, select, from} = require("../../passthrough")
|
||||
const {id} = require("../../../addbot")
|
||||
const {reg} = require("../../matrix/read-registration")
|
||||
|
||||
const {sync} = require("../../passthrough")
|
||||
const assert = require("assert").strict
|
||||
/** @type {import("../pug-sync")} */
|
||||
const pugSync = sync.require("../pug-sync")
|
||||
/** @type {import("../../matrix/api")} */
|
||||
const api = sync.require("../../matrix/api")
|
||||
|
||||
const redirect_uri = `${reg.ooye.bridge_origin}/oauth`
|
||||
|
||||
const schema = {
|
||||
form: z.object({
|
||||
mxid: z.string()
|
||||
}),
|
||||
token: z.object({
|
||||
token: z.string()
|
||||
})
|
||||
}
|
||||
|
||||
/** @type {LRUCache<string, string>} token to mxid */
|
||||
const validToken = new LRUCache({max: 200})
|
||||
|
||||
/*
|
||||
1st request, GET, they clicked the button, need to input their mxid
|
||||
2nd request, POST, they input their mxid and we need to send a link
|
||||
3rd request, GET, they clicked the link and we need to set the session data (just their mxid)
|
||||
*/
|
||||
|
||||
as.router.get("/log-in-with-matrix", defineEventHandler(async event => {
|
||||
const parsed = await getValidatedQuery(event, schema.token.safeParse)
|
||||
|
||||
if (!parsed.success) {
|
||||
// We are in the first request and need to tell them to input their mxid
|
||||
return pugSync.render(event, "log-in-with-matrix.pug", {})
|
||||
}
|
||||
|
||||
const userAgent = getRequestHeader(event, "User-Agent")
|
||||
if (userAgent?.match(/bot/)) throw createError({status: 400, data: "Sorry URL previewer, you can't have this URL."})
|
||||
|
||||
const token = parsed.data.token
|
||||
if (!validToken.has(token)) return sendRedirect(event, `${reg.ooye.bridge_origin}/log-in-with-matrix`, 302)
|
||||
|
||||
const session = await useSession(event, {password: reg.as_token})
|
||||
const mxid = validToken.get(token)
|
||||
assert(mxid)
|
||||
validToken.delete(token)
|
||||
|
||||
const matrixGuilds = db.prepare("SELECT guild_id FROM guild_space INNER JOIN member_cache ON space_id = room_id WHERE mxid = ? AND power_level >= 50").pluck().all(mxid)
|
||||
|
||||
await session.update({mxid, matrixGuilds})
|
||||
|
||||
return sendRedirect(event, "./", 302) // open to homepage where they can see they're logged in
|
||||
}))
|
||||
|
||||
as.router.post("/api/log-in-with-matrix", defineEventHandler(async event => {
|
||||
const {mxid} = await readValidatedBody(event, schema.form.parse)
|
||||
let roomID = null
|
||||
|
||||
// Don't extend a duplicate invite for the same user
|
||||
for (const alreadyInvited of validToken.values()) {
|
||||
if (mxid === alreadyInvited) {
|
||||
return sendRedirect(event, "../ok?msg=We already sent you a link on Matrix. Please click it!", 302)
|
||||
}
|
||||
}
|
||||
|
||||
// See if we can reuse an existing room from account data
|
||||
let directData = {}
|
||||
try {
|
||||
directData = await api.getAccountData("m.direct")
|
||||
} catch (e) {}
|
||||
const rooms = directData[mxid] || []
|
||||
for (const candidate of rooms) {
|
||||
// Check that the person is/still in the room
|
||||
let member
|
||||
try {
|
||||
member = await api.getStateEvent(candidate, "m.room.member", mxid)
|
||||
} catch (e) {}
|
||||
if (!member || member.membership === "leave") {
|
||||
// We can reinvite them back to the same room!
|
||||
await api.inviteToRoom(candidate, mxid)
|
||||
roomID = candidate
|
||||
} else {
|
||||
// Member is in this room
|
||||
roomID = candidate
|
||||
}
|
||||
if (roomID) break // no need to check other candidates
|
||||
}
|
||||
|
||||
// No candidates available, create a new room and invite
|
||||
if (!roomID) {
|
||||
roomID = await api.createRoom({
|
||||
invite: [mxid],
|
||||
is_direct: true,
|
||||
preset: "trusted_private_chat"
|
||||
})
|
||||
// Store the newly created room in account data (Matrix doesn't do this for us automatically, sigh...)
|
||||
;(directData[mxid] ??= []).push(roomID)
|
||||
await api.setAccountData("m.direct", directData)
|
||||
}
|
||||
|
||||
const token = randomUUID()
|
||||
validToken.set(token, mxid)
|
||||
|
||||
console.log(`web log in requested for ${mxid}`)
|
||||
const body = `Hi, this is Out Of Your Element! You just clicked the "log in" button on the website.\nOpen this link to finish: ${reg.ooye.bridge_origin}/log-in-with-matrix?token=${token}\nThe link can be used once.`
|
||||
await api.sendEvent(roomID, "m.room.message", {
|
||||
msgtype: "m.text",
|
||||
body
|
||||
})
|
||||
|
||||
return sendRedirect(event, "../ok?msg=Please check your inbox on Matrix!&spot=SpotMailXL", 302)
|
||||
}))
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
const {z} = require("zod")
|
||||
const {randomUUID} = require("crypto")
|
||||
const {defineEventHandler, getValidatedQuery, sendRedirect, getQuery, useSession, createError} = require("h3")
|
||||
const {defineEventHandler, getValidatedQuery, sendRedirect, useSession, createError} = require("h3")
|
||||
const {SnowTransfer} = require("snowtransfer")
|
||||
const DiscordTypes = require("discord-api-types/v10")
|
||||
const fetch = require("node-fetch")
|
||||
@@ -75,11 +75,12 @@ as.router.get("/oauth", defineEventHandler(async event => {
|
||||
throw createError({status: 502, message: "Invalid token response", data: `Discord completed OAuth, but returned this instead of an OAuth access token: ${JSON.stringify(root)}`})
|
||||
}
|
||||
|
||||
const userID = Buffer.from(parsedToken.data.access_token.split(".")[0], "base64").toString()
|
||||
const client = new SnowTransfer(`Bearer ${parsedToken.data.access_token}`)
|
||||
try {
|
||||
const guilds = await client.user.getGuilds()
|
||||
var managedGuilds = guilds.filter(g => BigInt(g.permissions) & DiscordTypes.PermissionFlagsBits.ManageGuild).map(g => g.id)
|
||||
await session.update({managedGuilds})
|
||||
await session.update({managedGuilds, userID, state: undefined})
|
||||
} catch (e) {
|
||||
throw createError({status: 502, message: "API call failed", data: e.message})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user