chai-guard
v1.2.3
Published
Security-focused Chai assertions
Maintainers
Readme
chai-guard
A Chai plugin that adds security-focused assertions for testing unsafe inputs, authentication tokens, and data validation rules.
It helps you guard application logic by making security checks readable and testable.
expect(token).to.be.validJWT();
expect(input).to.be.safeString();Features
- JWT validation
- Strong password checks
- API key format validation
- Email / URL safety checks
- UUID validation
- JSON validation
- Input safety checks (basic XSS / SQL injection patterns)
- Ethereum address validation (optional Web3-style checks)
Installation
npm install chai chai-guardUsage
const chai = require("chai");
const chaiGuard = require("chai-guard");
chai.use(chaiGuard);
const expect = chai.expect;Assertions
JWT
expect(token).to.be.validJWT();Strong password
expect("Str0ngP@ssword!").to.be.strongPassword();Safe string (XSS / SQL injection heuristics)
expect(userInput).to.be.safeString();Detects patterns such as:
<script>/ script-like fragments- SQL keywords (
SELECT,DROP,--, …) - Common injection-style substrings (heuristic, not a guarantee)
API key shape
expect(apiKey).to.be.validApiKey();expect("[email protected]").to.be.safeEmail();URL
expect("https://example.com").to.be.safeURL();UUID
expect(id).to.be.validUUID();JSON string
expect(raw).to.be.validJSON();Nested safe input
expect(payload).to.be.safeInput();Ethereum address
expect(address).to.be.validEthereumAddress();Example (Mocha)
describe("Security guard tests", () => {
it("should validate JWT shape", () => {
expect(token).to.be.validJWT();
});
it("should reject unsafe input", () => {
expect("<script>alert(1)</script>").to.not.be.safeString();
});
});What chai-guard focuses on
Unlike general-purpose validation libraries, chai-guard is aimed at:
- Security-oriented tests
- Input safety checks
- Authentication-related shapes in tests
- Defensive backend testing
- OWASP-style validation patterns (heuristic)
Plugin structure
Built with the Chai plugin API:
module.exports = function chaiGuard(chai /*, utils */) {
const Assertion = chai.Assertion;
Assertion.addMethod("validJWT", function validJWT() {
const obj = this._obj;
const parts = typeof obj === "string" ? obj.split(".") : [];
this.assert(
parts.length === 3 && parts.every(Boolean),
"expected #{this} to be a valid JWT",
"expected #{this} not to be a valid JWT"
);
});
};Roadmap
- OWASP Top 10–style rule presets
- Richer SQL injection detection
- XSS heuristic improvements
- Optional Zod / Joi helpers
- More Web3-related assertions
- Optional Express middleware
- CLI security checker
License
MIT
Motivation
Most backend issues come from unsafe input, not from broken business logic alone. chai-guard makes security assumptions visible, testable, and easier to enforce in your test suite.
