iceshrimp-legacy/packages/backend/src/services/fetch-rel-me.ts
Kainoa Kanter 15ffb8cf40 feat: verify links with rel=me (#10506)
Adds Mastodon-style `rel=me` link verification, and creates a background job to verify said links

Closes #9341

![image](/attachments/861e01eb-660f-4c62-8d83-d824cb79da48)

Co-authored-by: ThatOneCalculator <kainoa@t1c.dev>
Co-authored-by: Namekuji <nmkj@waah.day>
Reviewed-on: https://codeberg.org/calckey/calckey/pulls/10506
2023-07-17 05:31:34 +00:00

34 lines
946 B
TypeScript

import { getHtml } from "@/misc/fetch.js";
import { JSDOM } from "jsdom";
import config from "@/config/index.js";
async function getRelMeLinks(url: string): Promise<string[]> {
try {
const html = await getHtml(url);
const dom = new JSDOM(html);
const relMeLinks = [
...dom.window.document.querySelectorAll("a[rel='me']"),
...dom.window.document.querySelectorAll("link[rel='me']"),
].map((a) => (a as HTMLAnchorElement | HTMLLinkElement).href);
return relMeLinks;
} catch {
return [];
}
}
export async function verifyLink(link: string, username: string): Promise<boolean> {
let verified = false;
if (link.startsWith("http")) {
const relMeLinks = await getRelMeLinks(link);
verified = relMeLinks.some((href) =>
new RegExp(
`^https?:\/\/${config.host.replace(
/[.*+\-?^${}()|[\]\\]/g,
"\\$&",
)}\/@${username.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&")}$`,
).test(href),
);
}
return verified;
}