Skip to content

@cshield/pdp

@cshield/pdp

The Policy Decision Point (PDP) is the core engine that evaluates requests against policies.

Installation

Terminal window
npm install @cshield/pdp

Functions

evaluate(policy, context, options?)

Evaluates a request context against a policy and returns a decision.

import { evaluate } from '@cshield/pdp';
const decision = await evaluate(policy, context, options);

Parameters:

NameTypeRequiredDescription
policyPolicySetYesPolicy configuration
contextRequestContextYesRequest context
optionsPdpOptionsNoEvaluation options

Returns: Promise<Decision>


Types

Decision

The result of policy evaluation.

interface Decision {
version: "0.1";
action: "ALLOW" | "BLOCK" | "MONITOR" | "CHALLENGE";
statusCode: number;
reason?: string;
ruleHits?: RuleHit[];
risk: {
score: number; // 0-100
level: "none" | "low" | "med" | "high" | "critical";
};
redactions?: RedactionDirective[];
metadata?: Record<string, unknown>;
}
interface RuleHit {
ruleId: string;
routeId: string;
severity: "none" | "low" | "med" | "high" | "critical";
message?: string;
metadata?: Record<string, unknown>;
}

RequestContext

The input context for evaluation.

interface RequestContext {
version: "0.1";
id?: string;
timestamp?: string;
request: {
method: string;
path: string;
routeId?: string;
headers?: Record<string, string>;
query?: Record<string, unknown>;
contentType?: string;
body?: unknown;
rawBody?: string; // For webhook signature verification
};
identity?: {
authenticated?: boolean;
subject?: string;
tenant?: string;
scopes?: string[];
claims?: Record<string, unknown>;
};
client?: {
ip?: string;
userAgent?: string;
};
runtime?: {
language?: string;
service?: string;
env?: string;
};
webhook?: {
provider?: string;
signatureValid?: boolean;
replayed?: boolean;
};
}

PolicySet

The policy configuration.

interface PolicySet {
policyVersion: "0.1";
defaults?: {
mode?: "monitor" | "enforce";
unmatchedRouteAction?: "allow" | "block" | "monitor";
response?: {
blockStatusCode?: number; // Default: 403
};
limits?: {
maxBodyBytes?: number;
maxJsonDepth?: number;
maxArrayLength?: number;
};
vulnerabilityChecks?: VulnerabilityChecksConfig;
};
routes: PolicyRoute[];
}
interface PolicyRoute {
id: string;
match: {
method: string | string[];
path: string; // Supports {param} placeholders
};
contract?: {
requestSchema?: JSONSchema;
requestSchemaRef?: string;
rejectUnknownFields?: boolean;
};
webhook?: WebhookConfig;
vulnerabilityChecks?: VulnerabilityChecksConfig;
rules?: Rule[];
}

PdpOptions

Options for the evaluate function.

interface PdpOptions {
getSecret?: (args: {
provider: string;
routeId: string;
ctx: RequestContext;
}) => string | undefined;
replayStore?: ReplayStore;
schemaLoader?: (ref: string) => Promise<JSONSchema> | JSONSchema;
celEvaluator?: CelEvaluator;
}

Replay Stores

MemoryReplayStore

In-memory store for development.

import { MemoryReplayStore } from '@cshield/pdp';
const store = new MemoryReplayStore();

createRedisReplayStore

Redis-backed store for production.

import { createRedisReplayStore } from '@cshield/pdp';
import Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_URL);
const store = createRedisReplayStore({
client: redis,
keyPrefix: 'cs:replay:',
defaultTtlSeconds: 86400 // 24 hours
});

Webhook Plugins

Built-in Plugins

import {
stripePlugin,
githubPlugin,
slackPlugin,
twilioPlugin,
listWebhookPlugins
} from '@cshield/pdp';
// List available plugins
const plugins = listWebhookPlugins();
// => ["stripe", "github", "slack", "twilio"]

Register Custom Plugin

import { registerWebhookPlugin } from '@cshield/pdp';
registerWebhookPlugin({
name: 'custom',
verifySignature: async (route, ctx, opts) => {
const secret = opts.getSecret({
provider: 'custom',
routeId: route.id,
ctx
});
// Your verification logic
const isValid = verify(ctx.request.rawBody, secret);
return { valid: isValid };
},
extractEventId: (ctx) => {
return ctx.request.headers['x-custom-event-id'];
}
});

Vulnerability Checks

checkVulnerabilities

Run vulnerability checks manually.

import { checkVulnerabilities } from '@cshield/pdp';
const hits = checkVulnerabilities(context, {
prototypePollution: true,
pathTraversal: true,
ssrfInternal: { fields: ['url', 'webhook_url'] },
commandInjection: { fields: ['command'] },
nosqlInjection: true
});
// hits: RuleHit[]

mergeVulnerabilityConfig

Merge default and route-specific configs.

import { mergeVulnerabilityConfig } from '@cshield/pdp';
const merged = mergeVulnerabilityConfig(
defaultConfig,
routeConfig
);

Error Handling

import { evaluate, PolicyValidationError, EvaluationError } from '@cshield/pdp';
try {
const decision = await evaluate(policy, context);
} catch (error) {
if (error instanceof PolicyValidationError) {
console.error('Invalid policy:', error.message);
} else if (error instanceof EvaluationError) {
console.error('Evaluation failed:', error.message);
}
}