@imigueldiaz/mongodb-labeler
Version:
A MongoDB-based labeling system for content moderation with cryptographic signing
30 lines (29 loc) • 1.15 kB
JavaScript
import { Secp256k1Keypair } from "@atproto/crypto";
import { excludeNullish } from "./util.js";
const LABEL_VERSION = 1;
function formatLabelCbor(label) {
return excludeNullish({ ...label, ver: LABEL_VERSION, neg: !!label.neg });
}
export function formatLabel(label) {
const sig = label.sig instanceof Uint8Array
? { $bytes: Buffer.from(label.sig).toString("base64") }
: label.sig;
if (!sig || !("$bytes" in sig)) {
throw new Error(`Expected sig to be an object with base64 $bytes, got ${String(sig)}`);
}
return excludeNullish({ ...label, ver: LABEL_VERSION, neg: !!label.neg, sig });
}
export async function signLabel(label, signingKey) {
const toSign = formatLabelCbor(label);
const keypair = new Secp256k1Keypair(signingKey, false);
const sig = await keypair.sign(Buffer.from(JSON.stringify(toSign)));
return { ...toSign, sig };
}
export function labelIsSigned(label) {
return "sig" in label && label.sig !== undefined;
}
export function generateExpiration(daysFromNow = 365) {
const exp = new Date();
exp.setDate(exp.getDate() + daysFromNow);
return exp.toISOString();
}