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 🙏

© 2025 – Pkg Stats / Ryan Hefner

test-kw

v0.1.2

Published

[![Sandbox](https://img.shields.io/badge/status-sandbox-red?style=for-the-badge)](https://github.com/kubewarden/community/blob/main/REPOSITORIES.md#sandbox) [![License: Apache 2.0](https://img.shields.io/badge/License-Apache2.0-brightgreen.svg)](https://o

Readme

Sandbox License: Apache 2.0 npm version

Kubewarden Policy SDK for JavaScript/TypeScript

[!WARNING] The SDK is experimental and under active development.

The official JavaScript/TypeScript SDK for writing Kubewarden policies. This SDK allows you to write Kubernetes admission policies using TypeScript/JavaScript that compile to WebAssembly modules.

Installation

npm install kubewarden-policy-sdk

Quick Start

Basic Policy Structure

import { Validation, writeOutput } from 'kubewarden-policy-sdk';

function validate() {
  // Read the admission request
  const validationRequest = Validation.readValidationRequest();
  const settings = validationRequest.settings;

  // Your policy logic here
  const isValid = yourValidationLogic(validationRequest.request);

  // Create response
  const response = new Validation.ValidationResponse(
    isValid,
    isValid ? undefined : 'Request rejected by policy',
    undefined, // mutated_object (for mutating policies)
    undefined, // warnings
    { customData: 'example' }, // annotations
  );

  // Write the response
  writeOutput(response);
}

// Export the validate function
(globalThis as any).validate = validate;

Using Host Capabilities

[!IMPORTANT]
Logging to stdout will break your policy. Always use console.error() for logging instead of console.log() to avoid policy failures.

The SDK provides access to Kubewarden's host capabilities:

Network Operations

import { hostCapabilities } from 'kubewarden-policy-sdk';

// DNS lookup
const dnsResult = hostCapabilities.Net.lookupHost('example.com');
console.error('IPs:', dnsResult.ips);

OCI Registry Operations

import { hostCapabilities } from 'kubewarden-policy-sdk';

// Get OCI manifest
const manifest = hostCapabilities.OciManifest.getManifest('registry.io/image:tag');
console.error('Manifest:', manifest);

// Verify image signatures
const verificationResult = hostCapabilities.OciSignatureVerifier.verifyPubKeysImage(
  'registry.io/image:tag',
  ['-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----'],
);

Kubernetes API Access

import { hostCapabilities } from 'kubewarden-policy-sdk';

// Get a Kubernetes resource
const resource = hostCapabilities.Kubernetes.getResource({
  apiVersion: 'v1',
  kind: 'Pod',
  name: 'my-pod',
  namespace: 'default',
});

// List resources
const pods = hostCapabilities.Kubernetes.listResourcesByNamespace({
  apiVersion: 'v1',
  kind: 'Pod',
  namespace: 'default',
});

Cryptographic Operations

import { hostCapabilities } from 'kubewarden-policy-sdk';

// Verify certificate
const cert = hostCapabilities.Crypto.CertificateUtils.fromString(
  '-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----',
  'Pem',
);

const verificationResult = hostCapabilities.Crypto.verifyCert(
  cert,
  [], // certificate chain
  '2025-12-31T23:59:59Z', // not_after
);

Complete Example Policy

import { Validation, writeOutput } from 'kubewarden-policy-sdk';
import type { Pod } from 'kubernetes-types/core/v1';

interface PolicySettings {
  ignoredNamespaces?: string[];
  allowPrivileged?: boolean;
}

function validate() {
  const validationRequest = Validation.readValidationRequest();
  const settings = validationRequest.settings as PolicySettings;
  const pod = validationRequest.request.object as Pod;

  // Skip validation for ignored namespaces
  if (settings.ignoredNamespaces?.includes(pod.metadata?.namespace || '')) {
    writeOutput(new Validation.ValidationResponse(true));
    return;
  }

  // Check for privileged containers
  const hasPrivilegedContainers =
    pod.spec?.containers?.some(container => container.securityContext?.privileged === true) ||
    false;

  if (hasPrivilegedContainers && !settings.allowPrivileged) {
    writeOutput(
      new Validation.ValidationResponse(
        false,
        'Privileged containers are not allowed',
        undefined,
        undefined,
        { violationType: 'privileged-container' },
      ),
    );
    return;
  }

  writeOutput(new Validation.ValidationResponse(true));
}

(globalThis as any).validate = validate;

API Reference

Core Classes

Validation.ValidationResponse

new ValidationResponse(
  accepted: boolean,           // Whether the request is accepted
  message?: string,           // Optional rejection message
  mutated_object?: any,       // For mutating admission controllers
  warnings?: string[],        // Optional warnings
  annotations?: Record<string, string> // Custom annotations
)

Validation.readValidationRequest()

Reads and parses the incoming Kubernetes admission request.

Host Capabilities

Network

  • lookupHost(hostname: string): DNS resolution

Container Registry

  • getManifest(image: string): Get OCI manifest
  • getManifestConfig(image: string): Get manifest configuration
  • getManifestDigest(image: string): Get manifest digest

Signature Verifier

  • verifyPubKeysImage(image: string, pubKeys: string[]): Verify with public keys
  • verifyKeylessExactMatch(image: string, keyless: KeylessInfo[]): Keyless verification
  • verifyKeylessPrefix(image: string, keyless: KeylessPrefixInfo[]): Prefix-based keyless verification
  • verifyGithubActions(image: string, owner: string): GitHub Actions verification

Kubernetes

  • getResource(request: GetResourceRequest): Get a specific resource
  • listResourcesByNamespace(request: ListResourcesRequest): List resources in namespace
  • listAllResources(request: ListResourcesRequest): List all resources
  • canI(request: CanIRequest): Check permissions using the Kubernetes authorization API

Cryptographic

  • verifyCert(cert: Certificate, certChain: Certificate[], notAfter?: string): Verify certificates
  • CertificateUtils.fromString(certString: string, encoding: CertificateEncoding): Create certificate from string
  • CertificateUtils.toString(cert: Certificate): Convert certificate to string

For complete documentation of all available host capabilities, see the Kubewarden Host Capabilities Reference.

Building Policies

Prerequisites

  • Node.js and npm
  • Javy - JavaScript to WebAssembly compiler
  • kwctl - Kubewarden CLI tool

Build Process

  1. Install the SDK:

    npm install kubewarden-policy-sdk
  2. Write your policy (e.g., main.ts)

  3. Set up your project structure with appropriate package.json, tsconfig.json, and webpack.config.js

  4. Build the policy:

    make build           # Compile TypeScript and bundle JavaScript
    make annotated-policy.wasm  # Compile to WebAssembly and annotate
  5. Test your policy:

    kwctl run annotated-policy.wasm -r request.json

Plugin Location

The Javy plugin required for compilation is included in the package at:

node_modules/kubewarden-policy-sdk/plugin/javy-plugin-kubewarden.wasm

Testing

The SDK includes comprehensive testing utilities. See the demo policy for examples of:

  • Unit testing with Jest
  • End-to-end testing with BATS
  • Mock host capabilities for testing

Examples

The best way to get started is with the JavaScript Policy Template which provides a ready-to-use project structure and examples.

You can also check out the demo policy in this repository for a complete working example that demonstrates:

  • Basic admission control logic
  • Host capabilities usage
  • Configuration handling
  • Testing strategies

Contributing

We welcome contributions! Please see the contributing guidelines for more information.

Development Setup

git clone https://github.com/kubewarden/policy-sdk-js.git
cd policy-sdk-js/js
npm install
npm test

License

This project is licensed under the Apache 2.0 License - see the LICENSE file for details.

Support