UNPKG

@ndn/packet

Version:

NDNts: Network Layer Packets

64 lines (63 loc) 2.84 kB
import { EvDecoder } from "@ndn/tlv"; import { toUtf8 } from "@ndn/util"; import { TT } from "./an_node.js"; const timestampRe = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})$/; function decodeTimestamp(str) { const match = timestampRe.exec(str); if (!match) { throw new Error("invalid ISO8601 compact timestamp"); } const [y, m, d, h, i, s] = match.slice(1).map((c) => Number.parseInt(c, 10)); return Date.UTC(y, m - 1, d, h, i, s); } function encodeTimestamp(timestamp) { const dt = new Date(timestamp); const p = (f, size = 2, add = 0) => (add + dt[`getUTC${f}`]()).toString().padStart(size, "0"); return `${p("FullYear", 4)}${p("Month", 2, 1)}${p("Date")}T${p("Hours")}${p("Minutes")}${p("Seconds")}`; } const EVD = new EvDecoder("ValidityPeriod", TT.ValidityPeriod) .add(TT.NotBefore, (t, { text }) => t.notBefore = decodeTimestamp(text), { required: true }) .add(TT.NotAfter, (t, { text }) => t.notAfter = decodeTimestamp(text), { required: true }); /** Certificate validity period. */ export class ValidityPeriod { static decodeFrom(decoder) { return EVD.decode(new ValidityPeriod(), decoder); } constructor(notBefore = 0, notAfter = 0) { this.notBefore = Number(notBefore); this.notAfter = Number(notAfter); } notBefore; notAfter; encodeTo(encoder) { return encoder.prependTlv(TT.ValidityPeriod, [TT.NotBefore, toUtf8(encodeTimestamp(this.notBefore))], [TT.NotAfter, toUtf8(encodeTimestamp(this.notAfter))]); } /** Determine whether the specified timestamp is within validity period. */ includes(t) { t = Number(t); return this.notBefore <= t && t <= this.notAfter; } /** Determine whether this validity period equals another. */ equals({ notBefore, notAfter }) { return this.notBefore === notBefore && this.notAfter === notAfter; } /** Compute the intersection of this and other validity periods. */ intersect(...validityPeriods) { return new ValidityPeriod(Math.max(this.notBefore, ...validityPeriods.map(({ notBefore }) => notBefore)), Math.min(this.notAfter, ...validityPeriods.map(({ notAfter }) => notAfter))); } toString() { return `${encodeTimestamp(this.notBefore)}-${encodeTimestamp(this.notAfter)}`; } } (function (ValidityPeriod) { /** A very long ValidityPeriod. */ ValidityPeriod.MAX = new ValidityPeriod(540109800000, 253402300799000); /** Construct ValidityPeriod for n days from now. */ function daysFromNow(n) { const notBefore = Date.now(); const notAfter = new Date(notBefore); notAfter.setUTCDate(notAfter.getUTCDate() + n); return new ValidityPeriod(notBefore, notAfter); } ValidityPeriod.daysFromNow = daysFromNow; })(ValidityPeriod || (ValidityPeriod = {}));