or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

generation.mdindex.mdparsing-serialization.mdverification.md
tile.json

tessl/npm-ssri

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

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/ssri@12.0.x

To install, run

npx @tessl/cli install tessl/npm-ssri@12.0.0

index.mddocs/

SSRI

SSRI (Standard Subresource Integrity) is a Node.js utility for parsing, manipulating, serializing, generating, and verifying Subresource Integrity hashes according to the W3C specification. It provides comprehensive functionality for cryptographic integrity validation of external resources in web applications.

Package Information

  • Package Name: ssri
  • Package Type: npm
  • Language: JavaScript (Node.js)
  • Installation: npm install ssri

Core Imports

const ssri = require('ssri');

Or with destructuring:

const { parse, stringify, fromData, checkData } = require('ssri');

Basic Usage

const ssri = require('ssri');
const fs = require('fs');

// Generate integrity from data
const integrity = ssri.fromData(fs.readFileSync('./my-file.js'));
console.log(integrity.toString());
// -> 'sha512-9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A=='

// Verify data integrity
const isValid = ssri.checkData(fs.readFileSync('./my-file.js'), integrity);
if (isValid) {
  console.log('Data integrity verified!');
}

// Stream processing with integrity verification
const stream = fs.createReadStream('./my-file.js');
ssri.checkStream(stream, integrity)
  .then(hash => console.log('Stream verified:', hash.algorithm))
  .catch(err => console.error('Verification failed:', err.message));

Architecture

SSRI is built around several core components:

  • Hash Class: Represents individual integrity hashes with algorithm, digest, and options
  • Integrity Class: Container for multiple hashes organized by algorithm for comprehensive integrity checking
  • IntegrityStream: Transform stream for real-time integrity generation and verification during data processing
  • Parser/Serializer: Standards-compliant parsing and stringification of SRI metadata
  • Generation Engine: Multiple methods for creating integrity hashes from various data sources
  • Verification Engine: Robust validation system supporting both sync and async verification patterns

Capabilities

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.

function parse(sri, opts): Integrity | Hash | null;
function stringify(obj, opts): string;

Parsing & Serialization

Integrity Generation

Generate SRI hashes from various data sources including raw data, streams, and hex values. Supports multiple algorithms and custom options for flexible hash creation.

function fromData(data, opts): Integrity;
function fromStream(stream, opts): Promise<Integrity>;
function fromHex(hexDigest, algorithm, opts): Integrity | Hash;
function create(opts): HashBuilder;

Integrity Generation

Integrity Verification

Verify data integrity against existing SRI hashes with comprehensive error reporting. Supports both synchronous data verification and asynchronous stream verification.

function checkData(data, sri, opts): Hash | false;
function checkStream(stream, sri, opts): Promise<Hash>;
function integrityStream(opts): IntegrityStream;

Integrity Verification

Core Types

class Hash {
  constructor(hash, opts);
  get isHash(): true;
  hexDigest(): string;
  toString(opts): string;
  toJSON(): string;
  match(integrity, opts): Hash | false;
  
  // Properties
  source: string;      // Original hash string
  algorithm: string;   // Hash algorithm name
  digest: string;      // Base64 digest value
  options: string[];   // Array of option strings
}

class Integrity {
  get isIntegrity(): true;
  toString(opts): string;
  toJSON(): string;
  isEmpty(): boolean;
  concat(integrity, opts): Integrity;
  merge(integrity, opts): void;
  match(integrity, opts): Hash | false;
  pickAlgorithm(opts, hashes): string | null;
  hexDigest(): string;
  
  // Properties (dynamic)
  [algorithm: string]: Hash[];  // Hashes grouped by algorithm
}

class IntegrityStream extends Minipass {
  constructor(opts);
  // Emits: 'size', 'integrity', 'verified', 'error'
}

interface HashBuilder {
  update(chunk, enc): HashBuilder;
  digest(): Integrity;
}

Constants

// W3C SRI specification compliant algorithms
const SPEC_ALGORITHMS = ['sha512', 'sha384', 'sha256'];

// Default algorithm used when none specified
const DEFAULT_ALGORITHMS = ['sha512'];

// Algorithm priority for pickAlgorithm (index-based, higher = stronger)
const DEFAULT_PRIORITY = [
  'md5', 'whirlpool', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512',
  'sha3', 'sha3-256', 'sha3-384', 'sha3-512', 'sha3_256', 'sha3_384', 'sha3_512'
];

// Internal validation patterns (for parsing and validation)
const BASE64_REGEX = /^[a-z0-9+/]+(?:=?=?)$/i;          // Base64 format validation
const SRI_REGEX = /^([a-z0-9]+)-([^?]+)([?\S*]*)$/;      // General SRI format
const STRICT_SRI_REGEX = /^([a-z0-9]+)-([A-Za-z0-9+/=]{44,88})(\?[\x21-\x7E]*)?$/; // Strict SRI
const VCHAR_REGEX = /^[\x21-\x7E]+$/;                    // Visible character validation

Error Codes

  • EINTEGRITY: Integrity verification failed
  • EBADSIZE: Size verification failed (when size option is provided)

Options Reference

interface ParseOptions {
  single?: boolean;  // Return single Hash instead of Integrity
  strict?: boolean;  // Use strict SRI spec compliance
}

interface GenerationOptions {
  algorithms?: string[];    // Algorithms to use (default: ['sha512'])
  options?: string[];       // Option strings to add to hashes
  strict?: boolean;         // Use strict mode
}

interface VerificationOptions {
  error?: boolean;          // Throw error on mismatch
  size?: number;           // Expected data size
  pickAlgorithm?: function; // Custom algorithm selection
}

interface StringifyOptions {
  sep?: string;    // Separator for multiple entries (default: ' ')
  strict?: boolean; // Use strict parsing rules
}