UNPKG

@mitre-attack/attack-data-model

Version:

A TypeScript API for the MITRE ATT&CK data model

76 lines (73 loc) 2.44 kB
import { stixTypeSchema, stixTypeToTypeName } from "./chunk-E6AAF2HD.js"; // src/schemas/common/stix-identifier.ts import { z } from "zod"; var isValidUuid = (uuid) => { return /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(uuid); }; var createStixIdError = (id, errorType) => { const parts = id.split("--"); const stixType = parts.length > 0 ? parts[0] : ""; const typeName = stixType in stixTypeToTypeName ? stixTypeToTypeName[stixType] : "STIX"; let message; switch (errorType) { case "format": message = `Invalid STIX Identifier for ${typeName} object: must comply with format 'type--UUIDv4'`; break; case "type": message = `Invalid STIX Identifier for ${typeName} object: contains invalid STIX type '${stixType}'`; break; case "uuid": message = `Invalid STIX Identifier for ${typeName} object: contains invalid UUIDv4 format`; break; } return { code: z.ZodIssueCode.custom, message, path: ["id"] }; }; var stixIdentifierSchema = z.string().refine( (val) => { if (typeof val !== "string") return false; if (!val.includes("--")) return false; const [type, uuid] = val.split("--"); const isValidType = stixTypeSchema.safeParse(type).success; const isValidUuidValue = isValidUuid(uuid); return isValidType && isValidUuidValue; }, (val) => { if (typeof val !== "string") { return createStixIdError(String(val), "format"); } if (!val.includes("--")) { return createStixIdError(val, "format"); } const [type, uuid] = val.split("--"); if (!stixTypeSchema.safeParse(type).success) { return createStixIdError(val, "type"); } if (!isValidUuid(uuid)) { return createStixIdError(val, "uuid"); } return createStixIdError(val, "format"); } ).describe( "Represents identifiers across the CTI specifications. The format consists of the name of the top-level object being identified, followed by two dashes (--), followed by a UUIDv4." ); function createStixIdValidator(expectedType) { const typeName = stixTypeToTypeName[expectedType] || expectedType; return stixIdentifierSchema.refine( (val) => val.startsWith(`${expectedType}--`), { message: `Invalid STIX Identifier for ${typeName}: must start with '${expectedType}--'`, path: ["id"] } ); } export { stixIdentifierSchema, createStixIdValidator };