Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow customizable error #58

Merged
merged 1 commit into from
Apr 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,29 @@ number;

<p>The size in bytes of the tokens that will be generated, if you plan on re-generating tokens consider dropping this to 32.</p>

<h3 id="configuration-error-config">errorConfig</h3>

```ts
statusCode?: number;
message?: string;
code?: string | undefined;
```

<p>
<b>Optional<br />
Default:</b>
</p>

```ts
{
statusCode: 403,
message: "invalid csrf token",
code: "EBADCSRFTOKEN"
}
```

Used to customise the error response <code>statusCode</code>, the contained error <code>message</code>, and it's <code>code</code>, the error is constructed via <code>createHttpError</code>. The default values match that of <code>csurf</code> for convenience.

<h2 id="utilities">Utilities</h2>

<p>Below is the documentation for what doubleCsrf returns.</p>
Expand Down Expand Up @@ -366,7 +389,7 @@ req.csrfToken(false, false); // same as generateToken(req, res, false, false);

<h3>invalidCsrfTokenError</h3>

<p>This is the error instance that gets passed as an error to the <code>next</code> call, by default this will be handled by the <a target="_blank" href="https://expressjs.com/en/guide/error-handling.html">default error handler</a>.</p>
<p>This is the error instance that gets passed as an error to the <code>next</code> call, by default this will be handled by the <a target="_blank" href="https://expressjs.com/en/guide/error-handling.html">default error handler</a>. This error is customizable via the <a href="#configuration-error-config">errorConfig</a>.</p>

<h3>validateToken</h3>

Expand Down
9 changes: 7 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ export function doubleCsrf({
size = 64,
ignoredMethods = ["GET", "HEAD", "OPTIONS"],
getTokenFromRequest = (req) => req.headers["x-csrf-token"],
errorConfig: {
statusCode = 403,
message = "invalid csrf token",
code = "EBADCSRFTOKEN",
} = {},
}: DoubleCsrfConfigOptions): DoubleCsrfUtilities {
const ignoredMethodsSet = new Set(ignoredMethods);
const cookieOptions = {
Expand All @@ -35,8 +40,8 @@ export function doubleCsrf({
...remainingCookieOptions,
};

const invalidCsrfTokenError = createHttpError(403, "invalid csrf token", {
code: "EBADCSRFTOKEN",
const invalidCsrfTokenError = createHttpError(statusCode, message, {
code: code,
});

const generateTokenAndHash = (
Expand Down
10 changes: 10 additions & 0 deletions src/tests/doublecsrf.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ createTestSuite("csrf-csrf unsigned, single secret", {
createTestSuite("csrf-csrf signed, single secret", {
cookieOptions: { signed: true },
getSecret: getSingleSecret,
errorConfig: {
statusCode: 400,
message: "NOT GOOD",
code: "BADTOKEN",
},
});
createTestSuite("csrf-csrf signed with custom options, single secret", {
getSecret: getSingleSecret,
Expand All @@ -37,6 +42,11 @@ createTestSuite("csrf-csrf signed with custom options, multiple secrets", {
cookieOptions: { signed: true, sameSite: "strict" },
size: 128,
cookieName: "__Host.test-the-thing.token",
errorConfig: {
statusCode: 401,
message: "GO AWAY",
code: "FAKE",
},
});

describe("csrf-csrf token-rotation", () => {
Expand Down
12 changes: 12 additions & 0 deletions src/tests/testsuite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ export const createTestSuite: CreateTestsuite = (name, doubleCsrfOptions) => {
secure = true,
sameSite = "lax",
} = {},
errorConfig = {
statusCode: 403,
message: "invalid csrf token",
code: "EBADCSRFTOKEN",
},
} = doubleCsrfOptions;

const generateMocksWithTokenIntenral = () =>
Expand All @@ -53,6 +58,13 @@ export const createTestSuite: CreateTestsuite = (name, doubleCsrfOptions) => {
validateRequest,
});

it("should initialize error via config options", () => {
console.log(invalidCsrfTokenError);
assert.equal(errorConfig.message, invalidCsrfTokenError.message);
assert.equal(errorConfig.statusCode, invalidCsrfTokenError.statusCode);
assert.equal(errorConfig.code, invalidCsrfTokenError.code);
});

describe("generateToken", () => {
it("should attach both a token and its hash to the response and return a token", () => {
const { mockRequest, decodedCookieValue, setCookie } =
Expand Down
12 changes: 12 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ export type CsrfTokenCreator = (
ovewrite?: boolean,
validateOnReuse?: boolean,
) => string;
export type CsrfErrorConfig = {
statusCode: number;
message: string;
code: string | undefined;
};
export type CsrfErrorConfigOptions = Partial<CsrfErrorConfig>;

export interface DoubleCsrfConfig {
/**
Expand Down Expand Up @@ -114,6 +120,12 @@ export interface DoubleCsrfConfig {
* ```
*/
getTokenFromRequest: TokenRetriever;

/**
* Configuration for the error that is thrown any time XSRF token validation fails.
* @default { statusCode: 403, message: "invalid csrf token", code: "EBADCSRFTOKEN" }
*/
errorConfig: CsrfErrorConfigOptions;
}

export interface DoubleCsrfUtilities {
Expand Down
Loading