Skip to content

@cshield/pep-express

@cshield/pep-express

Express.js middleware for ContractShield policy enforcement.

Installation

Terminal window
npm install @cshield/pep-express

Middleware

contractshield(options)

Creates the ContractShield middleware.

import express from 'express';
import { contractshield } from '@cshield/pep-express';
const app = express();
app.use(express.json());
app.use(contractshield(options));

Options:

interface ContractShieldOptions {
// Required: Policy configuration
policy: PolicySet | string; // Object or file path (.yaml/.json)
// PDP options
pdpOptions?: {
getSecret?: (args) => string | undefined;
replayStore?: ReplayStore;
schemaLoader?: (ref: string) => Promise<any>;
};
// Identity extraction
identityExtractor?: (req: Request) => Identity;
// Logging
logger?: (decision: Decision, req: Request) => void;
// Behavior
dryRun?: boolean; // Log only, don't enforce
// Response customization
blockResponse?: {
message?: string;
includeRuleHits?: boolean;
};
// Headers
decisionHeader?: string; // Default: "X-ContractShield-Decision"
}

Utilities

rawBodyCapture()

Middleware to capture raw request body for webhook signature verification.

import { rawBodyCapture } from '@cshield/pep-express';
// MUST come before express.json()
app.use(rawBodyCapture());
app.use(express.json());

Hot Reload

PolicyHotReloader

Watch policy files and reload on changes.

import { PolicyHotReloader } from '@cshield/pep-express';
const reloader = new PolicyHotReloader('./policy.yaml', {
enabled: true,
debounceMs: 500,
onReload: (policy) => {
console.log('Policy reloaded');
},
onError: (err) => {
console.error('Reload error:', err);
}
});
// Get current policy
const policy = reloader.getPolicy();
// Stop watching
reloader.stop();

createPolicyLoader

Create a policy loader with hot reload support.

import { createPolicyLoader } from '@cshield/pep-express';
const loader = createPolicyLoader('./policy.yaml', {
hotReload: process.env.NODE_ENV !== 'production'
});
app.use(contractshield({
policy: loader
}));

Accessing Decisions

The decision is available on the request object:

app.get('/api/resource', (req, res) => {
const { decision, context } = req.contractshield;
console.log(decision.action); // "ALLOW" | "BLOCK"
console.log(decision.risk.score); // 0-100
console.log(decision.ruleHits); // Array of triggered rules
// Context contains the evaluated request data
console.log(context.identity);
console.log(context.request);
});

TypeScript augmentation:

declare global {
namespace Express {
interface Request {
contractshield: {
decision: Decision;
context: RequestContext;
};
}
}
}

Examples

Basic Setup

import express from 'express';
import { contractshield } from '@cshield/pep-express';
const app = express();
app.use(express.json());
app.use(contractshield({
policy: './policy.yaml'
}));
app.listen(3000);

With Identity Extraction

import { contractshield } from '@cshield/pep-express';
import { verifyJwt } from './auth';
app.use(async (req, res, next) => {
try {
req.user = await verifyJwt(req.headers.authorization);
} catch {}
next();
});
app.use(contractshield({
policy: './policy.yaml',
identityExtractor: (req) => ({
authenticated: !!req.user,
subject: req.user?.sub,
tenant: req.user?.org_id,
scopes: req.user?.permissions || [],
claims: {
role: req.user?.role,
tier: req.user?.subscription_tier
}
})
}));

With Webhooks

import { contractshield, rawBodyCapture } from '@cshield/pep-express';
import { MemoryReplayStore } from '@cshield/pdp';
app.use(rawBodyCapture());
app.use(express.json());
app.use(contractshield({
policy: './policy.yaml',
pdpOptions: {
replayStore: new MemoryReplayStore(),
getSecret: ({ provider }) => {
if (provider === 'stripe') return process.env.STRIPE_WEBHOOK_SECRET;
if (provider === 'github') return process.env.GITHUB_WEBHOOK_SECRET;
}
}
}));

Dry Run Mode

app.use(contractshield({
policy: './policy.yaml',
dryRun: true, // Log but don't block
logger: (decision, req) => {
if (decision.action === 'BLOCK') {
console.warn('Would have blocked:', req.path, decision.ruleHits);
}
}
}));

Custom Block Response

app.use(contractshield({
policy: './policy.yaml',
blockResponse: {
message: 'Access denied',
includeRuleHits: process.env.NODE_ENV !== 'production'
}
}));