UNPKG

@kentcdodds/tmp-remix-utils

Version:

This package contains simple utility functions to use with [Remix.run](https://remix.run).

82 lines (81 loc) 2.63 kB
import type { Cookie } from "@remix-run/server-runtime"; export type CSRFErrorCode = | "missing_token_in_cookie" | "invalid_token_in_cookie" | "tampered_token_in_cookie" | "missing_token_in_body" | "mismatched_token"; export declare class CSRFError extends Error { code: CSRFErrorCode; constructor(code: CSRFErrorCode, message: string); } interface CSRFOptions { /** * The cookie object to use for serializing and parsing the CSRF token. */ cookie: Cookie; /** * The name of the form data key to use for the CSRF token. */ formDataKey?: string; /** * A secret to use for signing the CSRF token. */ secret?: string; } export declare class CSRF { private cookie; private formDataKey; private secret?; constructor(options: CSRFOptions); /** * Generates a random string in Base64URL to be used as an authenticity token * for CSRF protection. * @param bytes The number of bytes used to generate the token * @returns A random string in Base64URL */ generate(bytes?: number): string; /** * Generates a token and serialize it into the cookie. * @param bytes The number of bytes used to generate the token * @returns A tuple with the token and the string to send in Set-Cookie * If there's already a csrf value in the cookie then the token will * be the same and the cookie will be null. * @example * let [token, cookie] = await csrf.commitToken(request); * return json({ token }, { * headers: { "set-cookie": cookie } * }) */ commitToken( requestOrHeaders?: Request | Headers, bytes?: number ): Promise<readonly [string, string | null]>; /** * Verify if a request and cookie has a valid CSRF token. * @example * export async function action({ request }: ActionArgs) { * await csrf.validate(request); * // the request is authenticated and you can do anything here * } * @example * export async function action({ request }: ActionArgs) { * let formData = await request.formData() * await csrf.validate(formData, request.headers); * // the request is authenticated and you can do anything here * } * @example * export async function action({ request }: ActionArgs) { * let formData = await parseMultipartFormData(request); * await csrf.validate(formData, request.headers); * // the request is authenticated and you can do anything here * } */ validate(data: Request): Promise<void>; validate(data: FormData, headers: Headers): Promise<void>; private readBody; private parseCookie; private sign; private verifySignature; } export {};