simple-fs-server/util/secret.ts

43 lines
961 B
TypeScript
Raw Permalink Normal View History

2023-01-05 18:18:07 +09:00
export async function generateSecretKey() {
2023-01-06 18:24:27 +09:00
const key = await crypto.subtle.generateKey(
{ name: "HMAC", hash: "SHA-512" },
true,
["sign", "verify"],
);
return key;
}
2023-01-06 23:22:00 +09:00
let cacheKey: CryptoKey | undefined;
let previousKey = "invalid";
2023-01-06 18:24:27 +09:00
export async function prepareSecretKey() {
const key = Deno.env.get("SECRET_KEY");
2023-01-06 23:22:00 +09:00
if (key === previousKey) {
return cacheKey!;
}
2023-01-06 18:24:27 +09:00
if (key) {
const jwk = JSON.parse(key) as JsonWebKey;
2023-01-06 23:22:00 +09:00
previousKey = key;
2023-01-06 18:24:27 +09:00
{
const key = await crypto.subtle.importKey(
"jwk",
jwk,
2023-01-05 18:18:07 +09:00
{ name: "HMAC", hash: "SHA-512" },
true,
["sign", "verify"],
);
2023-01-06 23:22:00 +09:00
cacheKey = key;
2023-01-06 18:24:27 +09:00
return key;
}
} else {
const key = await generateSecretKey();
const out = await crypto.subtle.exportKey("jwk", key);
2023-01-06 23:22:00 +09:00
const outStr = JSON.stringify(out);
Deno.env.set("SECRET_KEY", outStr);
cacheKey = key;
previousKey = outStr;
2023-01-05 18:18:07 +09:00
return key;
2023-01-06 18:24:27 +09:00
}
2023-01-05 18:18:07 +09:00
}