forked from mtusi2026/mtusi2026lab7
77 lines
1.9 KiB
TypeScript
77 lines
1.9 KiB
TypeScript
import {
|
|
X509Certificate,
|
|
createPrivateKey,
|
|
createPublicKey,
|
|
timingSafeEqual,
|
|
} from "node:crypto";
|
|
import { requireThat } from "./runtime";
|
|
export function validAge(age: number, maximum: number): number {
|
|
requireThat(
|
|
Number.isFinite(age) &&
|
|
age >= 0 &&
|
|
Number.isFinite(maximum) &&
|
|
maximum >= 0 &&
|
|
age <= maximum,
|
|
"INVALID_EVIDENCE_AGE",
|
|
);
|
|
return age;
|
|
}
|
|
export function allowedIdentity(
|
|
identity: string,
|
|
allowed: readonly string[],
|
|
): string {
|
|
requireThat(allowed.includes(identity), "FORBIDDEN_CERTIFICATE_ROLE");
|
|
return identity;
|
|
}
|
|
export function requireTLSURL(address: string, hostname: string): URL {
|
|
const u = new URL(address);
|
|
requireThat(
|
|
u.protocol === "https:" &&
|
|
u.hostname === hostname &&
|
|
!u.username &&
|
|
!u.password,
|
|
"INVALID_TLS_ENDPOINT",
|
|
);
|
|
return u;
|
|
}
|
|
export function validateLeaf(
|
|
certPEM: string,
|
|
keyPEM: string,
|
|
caPEM: string,
|
|
hostname: string,
|
|
now = Date.now(),
|
|
) {
|
|
const cert = new X509Certificate(certPEM),
|
|
ca = new X509Certificate(caPEM);
|
|
for (const c of [cert, ca])
|
|
requireThat(
|
|
Number.isFinite(Date.parse(c.validFrom)) &&
|
|
Date.parse(c.validFrom) <= now &&
|
|
now < Date.parse(c.validTo),
|
|
"CERTIFICATE_LIFETIME_INVALID",
|
|
);
|
|
requireThat(
|
|
ca.ca && !cert.ca && cert.verify(ca.publicKey),
|
|
"CERTIFICATE_CA_INVALID",
|
|
);
|
|
requireThat(
|
|
cert.checkHost(hostname, { subject: "never" }) === hostname,
|
|
"CERTIFICATE_SAN_INVALID",
|
|
);
|
|
const publicKey = createPublicKey(createPrivateKey(keyPEM)).export({
|
|
format: "der",
|
|
type: "spki",
|
|
}),
|
|
expected = cert.publicKey.export({ format: "der", type: "spki" });
|
|
requireThat(
|
|
publicKey.length === expected.length &&
|
|
timingSafeEqual(publicKey, expected),
|
|
"CERTIFICATE_KEY_MISMATCH",
|
|
);
|
|
return {
|
|
serial: cert.serialNumber,
|
|
fingerprint: cert.fingerprint256,
|
|
expires: cert.validTo,
|
|
};
|
|
}
|