76 lines
2.1 KiB
JavaScript
76 lines
2.1 KiB
JavaScript
|
import { createVerify } from "node:crypto";
|
||
|
import assert from "node:assert"
|
||
|
import app from "./app.js";
|
||
|
import { ASSET_API_ENDPOINT, ASSET_API_M2M_REFRESH_INTERVAL } from "./consts.js";
|
||
|
|
||
|
let assetPubKey = await fetchAssetPubkey()
|
||
|
let assetAlgorithm = await fetchAssetAlgorithm()
|
||
|
|
||
|
setInterval(async () => {
|
||
|
try {
|
||
|
let pubkey = await fetchAssetPubkey();
|
||
|
let algo = await fetchAssetAlgorithm();
|
||
|
|
||
|
if (pubkey != null && algo != null) {
|
||
|
if (assetPubKey !== pubkey) {
|
||
|
app.log.warn("The M2M public key has changed!")
|
||
|
}
|
||
|
|
||
|
if (assetAlgorithm !== algo) {
|
||
|
app.log.warn("The M2M algorith has changed!");
|
||
|
}
|
||
|
|
||
|
assetPubKey = pubkey;
|
||
|
assetAlgorithm = algo;
|
||
|
app.log.debug("Successfully updated the M2M credentials");
|
||
|
} else {
|
||
|
app.log.warn("Failed to retrieve the M2M credentials");
|
||
|
}
|
||
|
} catch (e) {
|
||
|
app.log.warn("Failed to update the M2M credentials");
|
||
|
app.log.warn(e);
|
||
|
}
|
||
|
}, ASSET_API_M2M_REFRESH_INTERVAL)
|
||
|
|
||
|
async function fetchAssetPubkey() {
|
||
|
let url = new URL(ASSET_API_ENDPOINT);
|
||
|
url.pathname = "/crypto/cert";
|
||
|
|
||
|
let res = await fetch(url);
|
||
|
return await res.text();
|
||
|
}
|
||
|
|
||
|
async function fetchAssetAlgorithm() {
|
||
|
let url = new URL(ASSET_API_ENDPOINT);
|
||
|
url.pathname = "/crypto/algo";
|
||
|
|
||
|
let res = await fetch(url);
|
||
|
return await res.text();
|
||
|
}
|
||
|
|
||
|
function partsFromSigned(content) {
|
||
|
let parts = content
|
||
|
.replace("-----BEGIN SIGNED MESSAGE-----\n\n", "")
|
||
|
.replace("\n-----END SIGNATURE-----", "")
|
||
|
.split("\n\n-----BEGIN SIGNATURE-----\n\n");
|
||
|
|
||
|
assert(parts.length === 2);
|
||
|
|
||
|
return parts
|
||
|
}
|
||
|
|
||
|
export function verifySignature(content) {
|
||
|
let parts = partsFromSigned(content)
|
||
|
|
||
|
let verify = createVerify(assetAlgorithm);
|
||
|
verify.update(parts[0]);
|
||
|
|
||
|
let pubkey = Buffer.from(assetPubKey, "ascii");
|
||
|
let digest = Buffer.from(parts[1], "base64");
|
||
|
|
||
|
return verify.verify(pubkey, digest);
|
||
|
}
|
||
|
|
||
|
export function contentFromSigned(content) {
|
||
|
return partsFromSigned(content)[0];
|
||
|
}
|