fix: harden share bot uploads
This commit is contained in:
@@ -24,6 +24,18 @@ export interface DiscordMemberProfile {
|
||||
roles: DiscordRole[];
|
||||
}
|
||||
|
||||
export type DiscordSenderProfile = Pick<
|
||||
DiscordMemberProfile,
|
||||
"id" | "username" | "globalName" | "avatarUrl"
|
||||
>;
|
||||
|
||||
export class DiscordProfileLookupError extends Error {
|
||||
constructor(message = "Discord profile lookup is unavailable") {
|
||||
super(message);
|
||||
this.name = "DiscordProfileLookupError";
|
||||
}
|
||||
}
|
||||
|
||||
interface CacheEntry<T> {
|
||||
data: T;
|
||||
expiresAt: number;
|
||||
@@ -213,3 +225,49 @@ export async function getDiscordMemberProfile(discordId: string): Promise<Discor
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getDiscordSenderProfile(
|
||||
discordId: string,
|
||||
): Promise<DiscordSenderProfile | null> {
|
||||
try {
|
||||
const { token, guildId } = getDiscordServerConfig();
|
||||
const response = await fetch(
|
||||
`https://discord.com/api/v10/guilds/${encodeURIComponent(guildId)}/members/${encodeURIComponent(discordId)}`,
|
||||
{
|
||||
headers: { Authorization: `Bot ${token}` },
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(5000),
|
||||
},
|
||||
);
|
||||
|
||||
if (response.status === 404) return null;
|
||||
if (!response.ok) throw new DiscordProfileLookupError();
|
||||
|
||||
const member = (await response.json()) as {
|
||||
user?: {
|
||||
id?: string;
|
||||
username?: string;
|
||||
global_name?: string | null;
|
||||
avatar?: string | null;
|
||||
};
|
||||
};
|
||||
const user = member.user;
|
||||
if (!user?.id || !user.username || user.id !== discordId) {
|
||||
throw new DiscordProfileLookupError("Discord returned an invalid sender profile");
|
||||
}
|
||||
|
||||
const avatarUrl = user.avatar
|
||||
? `https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}.${user.avatar.startsWith("a_") ? "gif" : "png"}?size=128`
|
||||
: null;
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
globalName: user.global_name ?? null,
|
||||
avatarUrl,
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof DiscordProfileLookupError) throw error;
|
||||
throw new DiscordProfileLookupError();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user