2022-09-02 20:24:33 +00:00
|
|
|
import config from "./config.ts";
|
|
|
|
import { hex } from "../deps.ts";
|
|
|
|
|
2022-09-04 12:39:03 +00:00
|
|
|
export const hasKey = !!config.signKey;
|
2022-09-02 20:24:33 +00:00
|
|
|
|
|
|
|
const encoder = new TextEncoder();
|
|
|
|
|
2022-09-04 12:39:03 +00:00
|
|
|
let _signKey: CryptoKey | undefined = undefined;
|
|
|
|
|
|
|
|
async function getKey(): Promise<CryptoKey> {
|
|
|
|
if (_signKey === undefined) {
|
|
|
|
if (!config.signKey) throw new Error("Signature requested but no key configured");
|
|
|
|
|
|
|
|
_signKey = await crypto.subtle.importKey(
|
|
|
|
"raw",
|
|
|
|
hex.decode(new TextEncoder().encode(config.signKey)),
|
|
|
|
{ name: "HMAC", hash: "SHA-256" },
|
|
|
|
false,
|
|
|
|
["sign", "verify"],
|
|
|
|
);
|
|
|
|
}
|
|
|
|
return _signKey;
|
|
|
|
}
|
|
|
|
|
2022-09-02 20:24:33 +00:00
|
|
|
export async function sign(input: string): Promise<string> {
|
2022-09-04 12:39:03 +00:00
|
|
|
const key = await getKey();
|
2022-09-02 20:24:33 +00:00
|
|
|
const inputData = encoder.encode(input);
|
2022-09-04 12:39:03 +00:00
|
|
|
const sig = await crypto.subtle.sign("HMAC", key, inputData);
|
2022-09-02 20:24:33 +00:00
|
|
|
return new TextDecoder().decode(hex.encode(new Uint8Array(sig)));
|
|
|
|
}
|
2022-09-02 23:36:32 +00:00
|
|
|
|
|
|
|
export async function verify(input: string, signature: string): Promise<boolean> {
|
2022-09-04 12:39:03 +00:00
|
|
|
const key = await getKey();
|
2022-09-02 23:36:32 +00:00
|
|
|
const signatureData = hex.decode(encoder.encode(signature));
|
|
|
|
const inputData = encoder.encode(input);
|
2022-09-04 12:39:03 +00:00
|
|
|
return await crypto.subtle.verify("HMAC", key, signatureData, inputData);
|
2022-09-02 23:36:32 +00:00
|
|
|
}
|