snort/packages/app/src/Hooks/useImgProxy.ts

41 lines
1.2 KiB
TypeScript
Raw Normal View History

import * as secp from "@noble/secp256k1";
import * as base64 from "@protobufjs/base64";
2023-03-15 11:09:20 +00:00
import { hmacSha256, unwrap } from "Util";
2023-04-14 11:33:19 +00:00
import useLogin from "Hooks/useLogin";
2023-01-31 14:41:21 +00:00
export interface ImgProxySettings {
url: string;
key: string;
salt: string;
2023-01-31 14:41:21 +00:00
}
export default function useImgProxy() {
2023-04-14 11:33:19 +00:00
const settings = useLogin().preferences.imgProxyConfig;
const te = new TextEncoder();
2023-01-31 14:41:21 +00:00
function urlSafe(s: string) {
return s.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
}
2023-01-31 14:41:21 +00:00
2023-04-18 11:47:01 +00:00
function signUrl(u: string) {
const result = hmacSha256(
2023-02-07 19:47:57 +00:00
secp.utils.hexToBytes(unwrap(settings).key),
secp.utils.hexToBytes(unwrap(settings).salt),
te.encode(u)
);
return urlSafe(base64.encode(result, 0, result.byteLength));
}
2023-01-31 14:41:21 +00:00
return {
2023-04-18 11:47:01 +00:00
proxy: (url: string, resize?: number) => {
if (!settings) return url;
2023-02-14 16:10:03 +00:00
const opt = resize ? `rs:fit:${resize}:${resize}/dpr:${window.devicePixelRatio}` : "";
const urlBytes = te.encode(url);
2023-02-09 12:26:54 +00:00
const urlEncoded = urlSafe(base64.encode(urlBytes, 0, urlBytes.byteLength));
const path = `/${opt}/${urlEncoded}`;
2023-04-18 11:47:01 +00:00
const sig = signUrl(path);
return `${new URL(settings.url).toString()}${sig}${path}`;
},
};
}