UNPKG

@ndn/packet

Version:

NDNts: Network Layer Packets

104 lines (103 loc) 3.38 kB
import { assert, sha256, timingSafeEqual } from "@ndn/util"; import { SigType } from "../an_node.js"; import { KeyLocator } from "../key-locator_node.js"; import { SigInfo } from "../sig-info_node.js"; export var LLSign; (function (LLSign) { LLSign.OP = Symbol("@ndn/packet#LLSign.OP"); })(LLSign || (LLSign = {})); export var LLVerify; (function (LLVerify) { LLVerify.OP = Symbol("@ndn/packet#LLVerify.OP"); })(LLVerify || (LLVerify = {})); export var Signer; (function (Signer) { /** * Put SigInfo on packet if it does not exist. * @param pkt - Target packet. * @param sigType - Optionally set sigType. * @param keyLocator - Optionally set keyLocator; `false` to delete KeyLocator. * @returns Existing or modified SigInfo. */ function putSigInfo(pkt, sigType, keyLocator) { pkt.sigInfo ??= new SigInfo(); if (sigType !== undefined) { pkt.sigInfo.type = sigType; } if (keyLocator === false) { pkt.sigInfo.keyLocator = undefined; } else if (keyLocator !== undefined) { pkt.sigInfo.keyLocator = new KeyLocator(keyLocator); } return pkt.sigInfo; } Signer.putSigInfo = putSigInfo; /** * Create a Signer that signs a packet only if it does not already have a non-Null signature. * @param signer - Inner signer. */ function onlyIfUnsigned(signer) { return { async sign(pkt) { if (!pkt.sigInfo || pkt.sigInfo.type === SigType.Null) { await signer.sign(pkt); } }, }; } Signer.onlyIfUnsigned = onlyIfUnsigned; })(Signer || (Signer = {})); export var Verifier; (function (Verifier) { /** * Ensure packet has the correct SigType. * * @throws Error * Thrown if `pkt` lacks SigInfo or its SigType differs from `expectedSigType`. */ function checkSigType(pkt, expectedSigType) { assert(pkt.sigInfo?.type === expectedSigType, `packet does not have SigType ${expectedSigType}`); } Verifier.checkSigType = checkSigType; /** Throw bad signature error if not OK. */ function throwOnBadSig(ok) { assert(ok, "bad signature value"); } Verifier.throwOnBadSig = throwOnBadSig; })(Verifier || (Verifier = {})); /** Signer and Verifier that do nothing. */ export const noopSigning = { sign() { return Promise.resolve(); }, verify() { return Promise.resolve(); }, }; /** Signer and Verifier for SigType.Sha256 digest. */ export const digestSigning = { sign(pkt) { Signer.putSigInfo(pkt, SigType.Sha256, false); return pkt[LLSign.OP]((input) => sha256(input)); }, async verify(pkt) { Verifier.checkSigType(pkt, SigType.Sha256); return pkt[LLVerify.OP](async (input, sig) => { const h = await sha256(input); const ok = timingSafeEqual(sig, h); Verifier.throwOnBadSig(ok); }); }, }; const nullSigValue = Promise.resolve(new Uint8Array()); /** * Signer for SigType.Null, a packet that is not signed. * @see https://redmine.named-data.net/projects/ndn-tlv/wiki/NullSignature */ export const nullSigner = { sign(pkt) { Signer.putSigInfo(pkt, SigType.Null, false); return pkt[LLSign.OP](() => nullSigValue); }, };