malibu
Version:
Framework-agnostic CSRF middleware
53 lines (52 loc) • 1.77 kB
TypeScript
/// <reference types="node" />
/// <reference types="node" />
import { IncomingMessage, ServerResponse } from 'http';
import { ParsedUrlQuery } from 'querystring';
import { SerializeOptions } from '@tinyhttp/cookie';
export interface CSRFRequest extends IncomingMessage {
csrfToken(): string;
secret?: string | string[];
signedCookies?: any;
cookies?: any;
query?: ParsedUrlQuery;
body?: any;
}
type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS' | 'HEAD' | 'TRACE';
type MiddlewareOptions = 'session' | 'cookie';
/**
* Options for CSRF constructor.
* Refer to README for more information.
*/
export interface CSRFOptions {
middleware?: MiddlewareOptions;
cookie?: CookieOptions;
sessionKey?: string;
value?: (req: CSRFRequest | IncomingMessage) => any;
ignoreMethod?: HTTPMethod[];
saltLength?: number;
secretLength?: number;
}
/**
* Options for cookie value.
* Extends SerializeOptions from @tinyhttp/cookie.
*/
export type CookieOptions = SerializeOptions & {
signed?: boolean;
key?: string;
path?: string;
};
/**
* Initiate CSRF (Cross-Site Request Forgery) Protection middleware.
* @function csrf
* @param {CSRFOptions} opts Given configuration options
* @returns {(req: CSRFRequest, res: ServerResponse, next: () => void) => void} CSRF Protection Middleware
* @example
* const csrfProtection = csrf()
* app.use(cookieParser()) // or a session middleware, if you prefer
*
* app.get("/", csrfProtection, (req, res) => {
* res.status(200).json({ token: req.csrfToken() });
* });
*/
export declare function csrf(opts?: CSRFOptions): (req: CSRFRequest, res: ServerResponse, next: () => void) => void;
export {};