Languages: English · 日本語
CDN Security Framework is a security design and implementation framework that can be used across major CDN edge execution environments such as CloudFront, CloudFront Functions, Lambda@Edge, and Cloudflare Workers.
The goal is simple.
"Make CDN security reusable as a design philosophy, so anyone in the world can build a secure initial setup in a short time."
Recommended first path: start with npx cdn-security init --platform aws --archetype spa-static-site --force, build the generated policy, then wire the AWS CloudFront Function and WAF Terraform outputs into your existing infrastructure. Cloudflare Workers is also supported, but the AWS + Terraform path is the most complete first deployment path today.
Many CDN security setups suffer from issues such as:
- Repeatedly hand-writing similar Edge rules for each project
- Fragmented design across CloudFront vs Cloudflare
- Unclear separation of responsibilities between WAF and Edge Functions
- Inconsistent initial security quality depending on who implements it
This framework addresses these with "policy-driven" + "runtime separation".
- Reduce the attack surface before traffic reaches Origin or the app
- Block obvious anomalies immediately
- Prevent accidents through normalization and removal of unnecessary elements
- Do not edit CDN-specific code directly
- First write human-readable policy
- Then compile it into each CDN runtime
- Functions / Workers
- Normalization, lightweight blocking, header injection
- WAF
- Rate limiting, OWASP, Bot, CAPTCHA
Edge Functions are the "upstream filter"; WAF is the "main defense"
| Platform | Support |
|---|---|
| AWS CloudFront | Behavior / Policy design |
| CloudFront Functions | Viewer Request / Response |
| AWS Lambda@Edge | Origin Request / Response |
| Cloudflare | CDN / Security Rules |
| Cloudflare Workers | Fetch Handler |
README.md
src/
bin/cli.ts # TypeScript source for the CLI
scripts/ # TypeScript source for compilers, tests, and tools
lib/ # TypeScript source for public library APIs
bin/
cli.js # Compiled package artifact: CLI entry (npx cdn-security)
docs/
architecture.md
quickstart.md
policy-runtime-sync.md
policy/
security.yml / base.yml
profiles/
scripts/
compile.js # Compiled from src/scripts/*.ts
compile-cloudflare.js
compile-infra.js
policy-lint.js
runtime-tests.js
cloudflare-runtime-tests.js
compile-unit-tests.js
infra-unit-tests.js
check-drift.js
templates/ # Internal: used by build to generate dist/edge/
aws/
dist/
edge/ # Generated: deploy this (viewer-request.js, viewer-response.js, origin-request.js)
infra/ # Generated WAF IaC: Terraform JSON and optional CloudFormation
runtimes/ # Legacy / reference; deploy from dist/edge/
examples/
The authoritative source for package code lives under src/**/*.ts. Root-level JavaScript and .d.ts files are committed package artifacts generated by npm run build:ts so npm consumers can run the CLI without a TypeScript build step. Runtime templates under templates/ are hand-written and are used to generate deployable dist/edge/ output.
See IaC integration for Terraform / CloudFormation / CDK / WAF usage.
- CLI reference —
init/build/emit-waf/doctor/readiness/capabilities/explain/diff/migrate - Programmatic API —
require('cdn-security-framework')for CI / IaC integration - Compiler strictness — phase contracts, strict checks, and remaining dynamic areas
- Archetypes — app-shaped policy presets (SPA, REST API, admin, microservice)
- Policy recipes — copyable snippets for Cognito APIs, SPAs, admin panels, signed downloads, and Cloudflare GraphQL
- Response DLP — Cloudflare Workers response masking/blocking for high-confidence data leaks
- Secret rotation runbook — JWT / JWKS / signed URL / admin token / origin secret
- Schema migration — how
policy/schema.jsonevolves and themigrateCLI - Supply chain — SLSA v1 provenance and
npm audit signatures - Template injection contract — marker-safe, parse-checked runtime config injection
- Test strategy — Vitest migration policy and release-gate test workflow
- ADR 0001: Plugin-safe emitter path — bundler-backed prototype and migration criteria
- Policy (
policy/security.ymlorpolicy/base.yml) is the single source of truth. Edit the policy to change blocking rules, headers, or route protection. - Build runs the CLI compiler:
npx cdn-security buildreads the policy, validates it, and generates Edge Runtime code intodist/edge/*.js. No manual sync ofCFGor runtime config. - See Policy and runtime sync for details and IaC usage.
npm install --save-dev cdn-security-frameworknpx cdn-security initAnswer the prompts. You can use the guided setup, start from a profile (strict / balanced / permissive), or choose an archetype (spa-static-site, rest-api, admin-panel, microservice-origin). Guided setup asks about app shape, CDN target, auth mode, CORS, WAF posture, and deployment intent.
Or non-interactive: npx cdn-security init --platform aws --profile balanced --force
Or with an archetype: npx cdn-security init --platform aws --archetype rest-api --force
Or guided: npx cdn-security init --guided --platform cloudflare --app-shape rest-api --auth jwt --cors-origins https://app.example.com --force
Edit policy/security.yml as needed, then:
# If your policy has a static_token auth gate, set the referenced build-time
# secret first. The built-in base/admin examples use EDGE_ADMIN_TOKEN.
export EDGE_ADMIN_TOKEN=replace-with-a-deploy-secret
# AWS (default): generates viewer-request.js, viewer-response.js, origin-request.js
npx cdn-security build
# Cloudflare Workers: generates index.ts for Wrangler
npx cdn-security build --target cloudflare
# AWS + existing Terraform-managed Web ACL:
# generate only rule groups (skip aws_wafv2_web_acl output)
npx cdn-security build --rule-group-onlyThis validates the policy and generates Edge Runtime code into dist/edge/.
For non-production fixture builds, you can use
npx cdn-security build --allow-placeholder-token, but never deploy artifacts
that contain the placeholder token.
export EDGE_ADMIN_TOKEN=ci-build-token-not-for-deploy
export ORIGIN_SECRET=ci-origin-secret-not-for-deploy
npm run test:ciRuns the single-Node CI quality gate, including audit, policy lint, build,
runtime, unit, fuzz, integration, drift, security-baseline, coverage, and
package smoke checks. It intentionally does not reproduce the GitHub Actions
Node-version matrix; CI still runs package smoke on Node 20.17.0, 22, and 24.
If you have a local policy/security.yml, test:ci lints and builds it first,
then regenerates policy/base.yml fixtures for runtime and coverage tests.
For focused local checks:
npm run test:runtime
npm run test:unit
npm run test:drift
npm run test:security-baselineEDGE_ADMIN_TOKEN is required by generated artifacts that include the built-in
admin static_token gate. ORIGIN_SECRET is required by origin-auth fixture
policies used by the broader drift/release checks.
npx cdn-security doctor
npx cdn-security capabilities --policy policy/security.yml --target aws
npx cdn-security explainOne-shot pass/fail report: Node version, policy parseability / schema version, every env var referenced by auth gates (EDGE_ADMIN_TOKEN, JWT_SECRET, ORIGIN_SECRET, ...), dist/edge/ writability, and npm ls cleanliness. Writes doctor-report.json for CI capture. See CLI reference for details.
Run it with the same env vars you will use for build, because CloudFront
Functions bake static token gates into the generated artifact.
explain prints a read-only policy posture summary for review and onboarding.
capabilities prints the target support matrix and, with --policy, reports configured controls that are partial, unsupported, or warning-only for aws or cloudflare. Use --json for automation.
Use the generated files in dist/edge/ with Terraform, CDK, or your CDN console. Set EDGE_ADMIN_TOKEN in your environment or secrets for admin routes.
- Block unwanted HTTP methods
- Early Path Traversal blocking
- UA / query anomaly detection
- Auth gates: static token, Basic auth, JWT (RS256/HS256), Signed URL
- Enforced security headers (HSTS, CSP, Referrer-Policy, Permissions-Policy)
- CORS and Cookie attribute management
- Cache poisoning mitigation
- Monitor mode for non-blocking observation
- Design that does not conflict with WAF
- Advanced bot behavior analysis (WAF / Bot Management responsibility)
- Internal DB abuse
- Business logic tampering
- Initial security for new Web / API services
- Global services using multiple CDNs
- OSS / SaaS "secure template" offerings
- Standardizing in-house security baselines
- package-lock.json: Commit it so CI can run
npm ci. - dist/: Ignored via
.gitignore. Users runnpm run buildto generatedist/edge/anddist/infra/. For CI drift checks, runnpm run buildin CI and compare with policy (do not commitdist/). - CI workflows:
.github/workflows/policy-lint.yml: push/PR quality gate (lint/build/runtime/unit/drift/security-baseline + package smoke tests).github/workflows/release-npm.yml: tag-driven publish workflow
- Release by tag:
- Bump
package.jsonversion (example:1.0.1) - Commit and push to
main - Create and push tag
v1.0.1 - GitHub Actions runs release checks, then publishes to npm if all checks pass
- Bump
- npm auth for release:
- Preferred: npm Trusted Publishing (OIDC) with
npm publish --provenance - Fallback: set repository secret
NPM_TOKENand workflow uses token publish
- Preferred: npm Trusted Publishing (OIDC) with
MIT License