Files
2026-05-27 23:47:53 +01:00

2.4 KiB

parse

(no submodules)

Purpose

Runtime-safe entry points that turn untrusted JSON or objects into strongly typed, schema-validated SLSA artifacts. Every other module in the package treats its inputs as already valid — these two helpers (parseProvenance, parseSbom) are the boundary between "unvalidated wire input" and the rest of the codebase. Both throw structured SlsaError subclasses with a context.issues array of path-formatted Zod messages so callers can surface precise validation feedback without parsing Zod internals.

Features

  • Accepts either a JSON string or a pre-parsed object.
  • Validates against the canonical Zod schemas for in-toto/SLSA provenance and CycloneDX 1.5 SBOMs.
  • Structured error output: err.code === "SLSA.INVALID_PROVENANCE" / "SLSA.INVALID_SBOM".
  • Captures the JSON parse error as err.cause when input is a malformed string.

Usage: Basic Example

import { parseProvenance } from "@suaveplan/slsa";

const statement = parseProvenance(wireJson);
console.log(statement.predicate.runDetails.builder.id);

Usage: Advanced Example

import { parseSbom, SlsaError, SLSA_CODES } from "@suaveplan/slsa";

try {
  const sbom = parseSbom(await fs.readFile("sbom.json", "utf8"));
  audit.record({ serial: sbom.serialNumber, components: sbom.components.length });
} catch (err) {
  if (err instanceof SlsaError && err.code === SLSA_CODES.INVALID_SBOM) {
    log.warn({ issues: err.context?.issues }, "SBOM rejected");
    return Response.json({ error: "invalid sbom" }, { status: 400 });
  }
  throw err;
}

API Reference

  • parseProvenance(input: string | unknown): ProvenanceStatement — validates against ProvenanceStatementSchema. Throws InvalidProvenanceError on any failure (malformed JSON, wrong _type, missing digests, etc.).
  • parseSbom(input: string | unknown): Sbom — validates against SbomSchema. Throws InvalidSbomError.

Implementation Notes

JSON parsing and schema validation are kept distinct so that a malformed JSON string surfaces a separate error (with the SyntaxError attached as cause) from a structurally valid but schema-invalid document. Zod's safeParse is used — we never throw a ZodError out of the public API. Issues are flattened to path: message strings because consumers often log context.issues directly and a JSON-stringified Zod issue tree is unfriendly in log pipelines.