From 06f502dd89fe019c920eeddd5f29f94c3c53bc9b Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Sun, 22 Sep 2024 15:53:58 +1200 Subject: [PATCH] Store Discord media proxy hashes in the database --- src/discord/utils.js | 10 ++++++++++ src/web/routes/download-discord.js | 10 +++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/discord/utils.js b/src/discord/utils.js index 8cb241b..dc96ff8 100644 --- a/src/discord/utils.js +++ b/src/discord/utils.js @@ -5,6 +5,13 @@ const assert = require("assert").strict const {reg} = require("../matrix/read-registration") +const {db} = require("../passthrough") + +/** @type {import("xxhash-wasm").XXHashAPI} */ // @ts-ignore +let hasher = null +// @ts-ignore +require("xxhash-wasm")().then(h => hasher = h) + const EPOCH = 1420070400000 /** @@ -123,6 +130,9 @@ function timestampToSnowflakeInexact(timestamp) { function getPublicUrlForCdn(url) { const match = url.match(/https:\/\/(cdn|media)\.discordapp\.(?:com|net)\/attachments\/([0-9]+)\/([0-9]+)\/([-A-Za-z0-9_.,]+)/) if (!match) return url + const unsignedHash = hasher.h64(match[3]) // attachment ID + const signedHash = unsignedHash - 0x8000000000000000n // shifting down to signed 64-bit range + db.prepare("INSERT OR IGNORE INTO media_proxy (permitted_hash) VALUES (?)").run(signedHash) return `${reg.ooye.bridge_origin}/download/discord${match[1]}/${match[2]}/${match[3]}/${match[4]}` } diff --git a/src/web/routes/download-discord.js b/src/web/routes/download-discord.js index 047dd94..ee64074 100644 --- a/src/web/routes/download-discord.js +++ b/src/web/routes/download-discord.js @@ -4,6 +4,11 @@ const assert = require("assert/strict") const {defineEventHandler, getValidatedRouterParams, sendRedirect, createError} = require("h3") const {z} = require("zod") +/** @type {import("xxhash-wasm").XXHashAPI} */ // @ts-ignore +let hasher = null +// @ts-ignore +require("xxhash-wasm")().then(h => hasher = h) + const {discord, as, select} = require("../../passthrough") const schema = { @@ -31,7 +36,10 @@ function defineMediaProxyHandler(domain) { return defineEventHandler(async event => { const params = await getValidatedRouterParams(event, schema.params.parse) - const row = select("channel_room", "channel_id", {channel_id: params.channel_id}).get() + const unsignedHash = hasher.h64(params.attachment_id) + const signedHash = unsignedHash - 0x8000000000000000n // shifting down to signed 64-bit range + + const row = select("media_proxy", "permitted_hash", {permitted_hash: signedHash}).get() if (row == null) { throw createError({ status: 403,