// Identity. Store your memories and mental belongings // Copyright (C) 2024 SofĂ­a Aritz // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . 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]; }