CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-ssri

Standard Subresource Integrity library that parses, serializes, generates, and verifies integrity metadata according to the SRI spec.

Pending
Overview
Eval results
Files

parsing-serialization.mddocs/

Parsing & Serialization

Core functionality for parsing SRI strings into structured objects and serializing them back to standard format. Essential for working with existing integrity metadata from browsers, package managers, and other systems.

Capabilities

Parse Function

Parses integrity strings or objects into structured Integrity instances for programmatic manipulation.

/**
 * Parses sri into an Integrity data structure
 * @param {string|object} sri - SRI string, Hash-like object, or Integrity-like object
 * @param {object} opts - Optional configuration
 * @param {boolean} opts.single - Return single Hash instead of Integrity
 * @param {boolean} opts.strict - Use strict SRI spec compliance
 * @returns {Integrity|Hash|null} Parsed integrity object or null if invalid
 */
function parse(sri, opts);

Usage Examples:

const ssri = require('ssri');

// Parse basic integrity string
const integrity = ssri.parse('sha512-9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==');
console.log(integrity.sha512[0].algorithm); // 'sha512'

// Parse with options
const hash = ssri.parse('sha256-abcd1234?foo', { single: true });
console.log(hash.options); // ['foo']

// Parse multiple algorithms
const multiAlgo = ssri.parse('sha256-abc sha512-def');
console.log(Object.keys(multiAlgo)); // ['sha256', 'sha512']

// Strict mode (browser compatibility)
const strict = ssri.parse('md5-invalid sha512-valid', { strict: true });
// Only includes sha512 hash (md5 not in SPEC_ALGORITHMS)

Stringify Function

Converts integrity-like objects to standard SRI string representation.

/**
 * Converts integrity object to string representation
 * @param {string|object} obj - Hash, Integrity, or string to stringify
 * @param {object} opts - Optional configuration
 * @param {string} opts.sep - Separator for multiple entries (default: ' ')
 * @param {boolean} opts.strict - Use strict parsing rules
 * @returns {string} SRI string representation
 */
function stringify(obj, opts);

Usage Examples:

const ssri = require('ssri');

// Stringify Hash-like object
const hashLike = {
  algorithm: 'sha512',
  digest: '9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==',
  options: ['foo']
};
console.log(ssri.stringify(hashLike));
// -> 'sha512-9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==?foo'

// Stringify Integrity-like object
const integrityLike = {
  'sha512': [{
    algorithm: 'sha512',
    digest: '9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==',
    options: []
  }]
};
console.log(ssri.stringify(integrityLike));

// Custom separator
console.log(ssri.stringify(multiIntegrity, { sep: '\n' }));
// Multi-line output

// Clean up malformed input
console.log(ssri.stringify('\n\rsha512-foo\n\t\tsha384-bar'));
// -> 'sha512-foo sha384-bar'

Hash Class Methods

Individual hash manipulation and serialization methods.

/**
 * Hash class representing a single integrity hash
 */
class Hash {
  /**
   * Creates a hash from string representation
   * @param {string} hash - Hash string to parse
   * @param {object} opts - Parsing options
   */
  constructor(hash, opts);

  /**
   * Returns hex representation of the digest
   * @returns {string} Hex-encoded digest
   */
  hexDigest();

  /**
   * Serializes hash to string format
   * @param {object} opts - Stringification options
   * @param {boolean} opts.strict - Use strict spec compliance
   * @returns {string} Hash string representation
   */
  toString(opts);

  /**
   * JSON serialization (calls toString)
   * @returns {string} String representation for JSON
   */
  toJSON();

  /**
   * Checks if this hash matches another integrity value
   * @param {string|object} integrity - Integrity to match against
   * @param {object} opts - Matching options
   * @returns {Hash|false} Matching hash or false
   */
  match(integrity, opts);
}

Integrity Class Methods

Multi-hash container manipulation and serialization methods.

/**
 * Integrity class representing multiple hashes organized by algorithm
 */
class Integrity {
  /**
   * Serializes integrity to string format
   * @param {object} opts - Stringification options
   * @param {string} opts.sep - Separator for multiple entries
   * @param {boolean} opts.strict - Use strict spec compliance
   * @returns {string} Integrity string representation
   */
  toString(opts);

  /**
   * JSON serialization (calls toString)
   * @returns {string} String representation for JSON
   */
  toJSON();

  /**
   * Checks if integrity object is empty
   * @returns {boolean} True if no hashes present
   */
  isEmpty();

  /**
   * Concatenates with another integrity value
   * @param {string|object} integrity - Integrity to concatenate
   * @param {object} opts - Concatenation options
   * @returns {Integrity} New combined integrity object
   */
  concat(integrity, opts);

  /**
   * Safely merges another integrity value
   * @param {string|object} integrity - Integrity to merge
   * @param {object} opts - Merge options
   * @throws {Error} If conflicting hashes for same algorithm
   */
  merge(integrity, opts);

  /**
   * Checks if integrity matches another value
   * @param {string|object} integrity - Integrity to match against
   * @param {object} opts - Matching options
   * @returns {Hash|false} Matching hash or false
   */
  match(integrity, opts);

  /**
   * Selects best algorithm from available hashes
   * @param {object} opts - Selection options
   * @param {function} opts.pickAlgorithm - Custom algorithm picker
   * @param {string[]} hashes - Limit to these algorithms
   * @returns {string|null} Selected algorithm or null
   */
  pickAlgorithm(opts, hashes);

  /**
   * Returns hex digest (assumes single-hash integrity)
   * @returns {string} Hex-encoded digest
   */
  hexDigest();
}

Data Structures

Parsed Integrity Structure

// Example parsed integrity object structure:
{
  'sha1': [{
    source: 'sha1-deadbeef',
    algorithm: 'sha1',
    digest: 'deadbeef',
    options: []
  }],
  'sha512': [
    {
      source: 'sha512-c0ffee',
      algorithm: 'sha512', 
      digest: 'c0ffee',
      options: []
    },
    {
      source: 'sha512-bad1dea?foo',
      algorithm: 'sha512',
      digest: 'bad1dea', 
      options: ['foo']
    }
  ]
}

Hash Properties

interface Hash {
  source: string;      // Original hash string
  algorithm: string;   // Hash algorithm name
  digest: string;      // Base64 digest value
  options: string[];   // Array of option strings
  get isHash(): true;  // Type discriminator getter
}

Integrity Properties

interface Integrity {
  [algorithm: string]: Hash[];  // Hashes grouped by algorithm
  get isIntegrity(): true;     // Type discriminator getter
}

Algorithm Support

Standard Algorithms (Strict Mode)

const SPEC_ALGORITHMS = ['sha512', 'sha384', 'sha256'];

Extended Algorithms (Permissive Mode)

Any algorithm supported by Node.js crypto module when not in strict mode, including:

  • sha1, sha224, sha256, sha384, sha512
  • sha3-256, sha3-384, sha3-512
  • md5 (not recommended for security)
  • And others available via crypto.getHashes()

Error Handling

Both parse() and stringify() are designed to be forgiving:

  • parse() returns null for completely invalid input
  • Invalid individual hashes within a string are silently skipped
  • stringify() handles malformed input by cleaning and normalizing
  • Strict mode filtering occurs without throwing errors

For more robust error handling, use verification functions which can throw detailed errors when configured with { error: true }.

Install with Tessl CLI

npx tessl i tessl/npm-ssri

docs

generation.md

index.md

parsing-serialization.md

verification.md

tile.json