npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@octavelaventure/stix

v1.1.0

Published

STIX 2.1 types and validators

Downloads

5

Readme

STIX 2.1 TypeScript Library

TypeScript License

A comprehensive TypeScript library for STIX 2.1 (Structured Threat Information Expression) providing type-safe interfaces and runtime validation for threat intelligence sharing.

Features

  • Complete STIX 2.1 Coverage - All SDOs, SROs, SCOs, and Meta Objects
  • 🔒 Type Safety - Full TypeScript type definitions with strict mode
  • ✔️ Runtime Validation - Zod schemas for all STIX object types
  • 🎯 Spec Compliant - Strictly follows the STIX 2.1 specification
  • 🛠️ Utility Functions - Helpers for ID generation, validation, and serialization
  • 📦 Zero Dependencies (runtime) - Only Zod as a dependency
  • 🧪 Well Tested - 2600+ tests with comprehensive coverage

Installation

npm install stix

Quick Start

Basic Usage

import { 
  IndicatorSchema, 
  generateStixId, 
  getCurrentTimestamp 
} from 'stix';

// Create a STIX Indicator
const indicator = {
  type: 'indicator',
  spec_version: '2.1',
  id: generateStixId('indicator'),
  created: getCurrentTimestamp(),
  modified: getCurrentTimestamp(),
  name: 'Malicious File Hash',
  pattern: '[file:hashes.MD5 = "d41d8cd98f00b204e9800998ecf8427e"]',
  pattern_type: 'stix',
  pattern_version: '2.1',
  valid_from: getCurrentTimestamp(),
  indicator_types: ['malicious-activity']
};

// Validate the indicator
const validated = IndicatorSchema.parse(indicator);
console.log('Valid indicator:', validated.name);

Working with Bundles

import { BundleSchema, createBundle, addToBundle } from 'stix';

// Create a bundle
let bundle = createBundle();

// Add objects to the bundle
bundle = addToBundle(bundle, indicator);
bundle = addToBundle(bundle, malware);
bundle = addToBundle(bundle, relationship);

// Validate the entire bundle
const validatedBundle = BundleSchema.parse(bundle);
console.log(`Bundle contains ${validatedBundle.objects?.length || 0} objects`);

Validation with Error Handling

import { 
  validateStixObject, 
  formatErrorMessage 
} from 'stix';
import { z } from 'zod';

const result = validateStixObject(someObject);

if (result.success) {
  console.log('Valid STIX object:', result.data.type);
} else {
  console.error('Validation failed:', result.message);
}

// Or with direct schema validation
try {
  const malware = MalwareSchema.parse(data);
  console.log('Valid malware:', malware.name);
} catch (error) {
  if (error instanceof z.ZodError) {
    console.error(formatErrorMessage(error));
  }
}

STIX Object Types

STIX Domain Objects (SDOs)

All 18 STIX Domain Objects are fully supported:

  • attack-pattern - Attack patterns and tactics
  • campaign - Threat campaigns
  • course-of-action - Defensive actions
  • grouping - Object groupings
  • identity - Individuals, organizations, groups
  • indicator - Indicators of compromise
  • infrastructure - Infrastructure used by threat actors
  • intrusion-set - Intrusion campaigns
  • malware - Malware instances
  • malware-analysis - Malware analysis results
  • note - Annotations and notes
  • observed-data - Observed cyber data
  • opinion - Opinions about STIX objects
  • report - Threat reports
  • threat-actor - Threat actors
  • tool - Tools used by threat actors
  • vulnerability - Software vulnerabilities
  • location - Geographic locations (STIX 2.1)

STIX Relationship Objects (SROs)

  • relationship - Relationships between objects
  • sighting - Sightings of indicators/observables

STIX Cyber-observable Objects (SCOs)

All 18 cyber-observable types:

  • artifact - Binary artifacts
  • autonomous-system - Autonomous systems
  • directory - File directories
  • domain-name - Domain names
  • email-addr - Email addresses
  • email-message - Email messages
  • file - Files
  • ipv4-addr - IPv4 addresses
  • ipv6-addr - IPv6 addresses
  • mac-addr - MAC addresses
  • mutex - Mutual exclusion objects
  • network-traffic - Network traffic
  • process - System processes
  • software - Software applications
  • url - URLs
  • user-account - User accounts
  • windows-registry-key - Windows registry keys
  • x509-certificate - X.509 certificates

Meta Objects

  • bundle - Collections of STIX objects
  • language-content - Translations and alternate content
  • marking-definition - Data marking definitions (TLP, etc.)

Utility Functions

ID Generation

import { generateStixId, parseStixId } from 'stix';

// Generate valid STIX IDs
const id = generateStixId('indicator');
// 'indicator--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f'

// Parse STIX IDs
const parsed = parseStixId(id);
console.log(parsed?.type); // 'indicator'
console.log(parsed?.uuid); // '8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f'

Timestamp Creation

import { 
  getCurrentTimestamp, 
  createTimestampFromMillis,
  createTimestampFromISO 
} from 'stix';

const now = getCurrentTimestamp();
// '2024-01-15T10:30:45.123Z'

const fromMillis = createTimestampFromMillis(1704067200000);
// '2024-01-01T00:00:00.000Z'

const fromISO = createTimestampFromISO('2024-01-15');
// '2024-01-15T00:00:00.000Z'

Object Creation Helpers

import { createStixObjectProperties } from 'stix';

const props = createStixObjectProperties('malware', {
  labels: ['trojan'],
  confidence: 85,
  created_by_ref: 'identity--...'
});

const malware = {
  ...props,
  name: 'TrojanXYZ',
  malware_types: ['trojan'],
  is_family: false
};

Validation Utilities

import { 
  validateStixObject,
  isValidStixId,
  validateStixObjects 
} from 'stix';

// Validate single object
const result = validateStixObject(someObject);
if (result.success) {
  console.log('Valid!');
}

// Check if string is valid STIX ID
if (isValidStixId('indicator--123')) {
  console.log('Valid ID format');
}

// Validate multiple objects
const results = validateStixObjects([obj1, obj2, obj3]);
const allValid = results.every(r => r.success);

JSON Serialization

import { 
  toJSON, 
  fromJSON, 
  prettyPrint,
  toSortedJSON 
} from 'stix';

// Serialize to JSON
const json = toJSON(indicator, { indent: 2, sortKeys: true });

// Parse from JSON
const obj = fromJSON(jsonString);

// Pretty print
console.log(prettyPrint(indicator));

// Canonical representation
const canonical = toSortedJSON(indicator);

Error Formatting

import { 
  formatValidationError, 
  formatErrorMessage,
  getErrorSummary 
} from 'stix';
import { z } from 'zod';

try {
  IndicatorSchema.parse(invalidData);
} catch (error) {
  if (error instanceof z.ZodError) {
    // Structured format
    const formatted = formatValidationError(error);
    console.log(formatted.errors);
    
    // Multi-line message
    console.error(formatErrorMessage(error));
    
    // One-line summary
    console.log(getErrorSummary(error));
  }
}

Examples

Creating a Complete Threat Report

import {
  generateStixId,
  getCurrentTimestamp,
  createStixObjectProperties,
  createBundle,
  addToBundle
} from 'stix';

// Create an identity (analyst)
const identity = {
  ...createStixObjectProperties('identity', {
    labels: ['organization']
  }),
  name: 'ACME Threat Intelligence',
  identity_class: 'organization'
};

// Create a threat actor
const threatActor = {
  ...createStixObjectProperties('threat-actor', {
    created_by_ref: identity.id,
    labels: ['nation-state']
  }),
  name: 'APT-X',
  threat_actor_types: ['nation-state'],
  sophistication: 'advanced',
  resource_level: 'government',
  primary_motivation: 'organizational-gain'
};

// Create malware
const malware = {
  ...createStixObjectProperties('malware', {
    created_by_ref: identity.id
  }),
  name: 'BadMalware',
  malware_types: ['trojan', 'remote-access-trojan'],
  is_family: false
};

// Create relationship
const relationship = {
  ...createStixObjectProperties('relationship'),
  relationship_type: 'uses',
  source_ref: threatActor.id,
  target_ref: malware.id
};

// Create indicator
const indicator = {
  ...createStixObjectProperties('indicator', {
    created_by_ref: identity.id,
    labels: ['malicious-activity']
  }),
  name: 'Malware File Hash',
  pattern: '[file:hashes.MD5 = "d41d8cd98f00b204e9800998ecf8427e"]',
  pattern_type: 'stix',
  pattern_version: '2.1',
  valid_from: getCurrentTimestamp(),
  indicator_types: ['malicious-activity']
};

// Bundle everything together
let bundle = createBundle();
bundle = addToBundle(bundle, identity);
bundle = addToBundle(bundle, threatActor);
bundle = addToBundle(bundle, malware);
bundle = addToBundle(bundle, relationship);
bundle = addToBundle(bundle, indicator);

// Validate and export
const validated = BundleSchema.parse(bundle);
console.log(`Created bundle with ${validated.objects?.length} objects`);

Filtering and Searching Bundles

import {
  getBundleById,
  filterBundleByType,
  getBundleRelationships,
  findRelatedObjects
} from 'stix';

// Get specific object by ID
const indicator = getBundleById(bundle, 'indicator--...');

// Filter by type
const allMalware = filterBundleByType(bundle, 'malware');
const allIndicators = filterBundleByType(bundle, 'indicator');

// Get all relationships
const relationships = getBundleRelationships(bundle);

// Find related objects
const related = findRelatedObjects(bundle, threatActor.id);
console.log(`Found ${related.length} related objects`);

TypeScript Integration

The library is built with TypeScript and provides full type safety:

import type {
  Indicator,
  Malware,
  ThreatActor,
  Relationship,
  Bundle,
  StixObject
} from 'stix';

function processIndicator(indicator: Indicator) {
  // TypeScript knows all properties
  console.log(indicator.pattern);
  console.log(indicator.pattern_type);
  console.log(indicator.valid_from);
}

function processBundleObjects(bundle: Bundle) {
  bundle.objects?.forEach(obj => {
    // obj is typed as StixObject (union of all types)
    console.log(obj.type, obj.id);
    
    // Type narrowing
    if (obj.type === 'indicator') {
      console.log(obj.pattern); // TypeScript knows this is an Indicator
    }
  });
}

Documentation

Development

Prerequisites

  • Node.js 18+
  • npm or yarn

Setup

# Install dependencies
npm install

# Run tests
npm test

# Run tests with UI
npm run test:ui

# Type check
npm run type-check

# Lint
npm run lint

# Format code
npm run format

# Run all checks
npm run check

Testing

The library has comprehensive test coverage with 2600+ tests:

npm run test:run  # Run all tests once
npm test          # Run tests in watch mode
npm run test:ui   # Open Vitest UI

Specification Compliance

This library strictly follows the STIX 2.1 specification published by OASIS. All object types, properties, and validation rules are implemented according to the specification.

Key compliance features:

  • ✅ All required properties enforced
  • ✅ Optional properties correctly typed
  • ✅ Enum values validated
  • ✅ Pattern validation for identifiers
  • ✅ Timestamp format (RFC 3339) validation
  • ✅ Relationship type constraints
  • ✅ Object reference validation

See SPEC_COMPLIANCE_VERIFICATION.md for detailed compliance notes.

Contributing

Contributions are welcome! Please:

  1. Follow the existing code style
  2. Write tests for new features
  3. Update documentation
  4. Ensure all checks pass (npm run check)

License

ISC License

Related Projects

Acknowledgments

This library is built according to the STIX 2.1 specification maintained by the OASIS Cyber Threat Intelligence (CTI) Technical Committee.