hono-ban 0.2.0 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +111 -16
- package/dist/cjs/formatters/rfc7807/index.js +364 -0
- package/dist/cjs/formatters/rfc7807/index.js.map +16 -0
- package/dist/cjs/index.js +85 -4221
- package/dist/cjs/index.js.map +16 -0
- package/dist/esm/formatters/rfc7807/index.js +333 -0
- package/dist/esm/formatters/rfc7807/index.js.map +16 -0
- package/dist/esm/index.js +145 -4209
- package/dist/esm/index.js.map +16 -0
- package/dist/types/formatters/rfc7807/formatter.d.ts +4 -4
- package/dist/types/formatters/rfc7807/hooks.d.ts +27 -2
- package/dist/types/formatters/rfc7807/index.d.ts +2 -2
- package/dist/types/formatters/rfc7807/schemas.d.ts +16 -16
- package/dist/types/types/rfc7807.d.ts +21 -38
- package/package.json +4 -4
- package/src/formatters/rfc7807/formatter.ts +16 -16
- package/src/formatters/rfc7807/hooks.ts +46 -20
- package/src/formatters/rfc7807/index.ts +7 -7
- package/src/formatters/rfc7807/schemas.ts +66 -35
- package/src/types/rfc7807.ts +31 -38
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/core/convert-error.ts", "../../src/core/format-error.ts", "../../src/utils/sanitize.ts", "../../src/formatters/default/index.ts", "../../src/factories/server-errors.ts", "../../src/middleware/ban-middleware.ts", "../../src/index.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"/**\n * Error conversion utilities\n * @module hono-ban/core/convert-error\n */\n\nimport type { BanError, BanOptions } from \"../types\";\nimport { createError } from \"./create-error\";\n\n/**\n * Type guard to check if a value is a BanError\n * @param err - Value to check\n * @param statusCode - Optional status code to match\n */\nexport function isBanError(err: unknown, statusCode?: number): err is BanError {\n return (\n typeof err === \"object\" &&\n err !== null &&\n \"isBan\" in err &&\n err.isBan === true &&\n (!statusCode || (err as BanError).status === statusCode)\n );\n}\n\n/**\n * Convert any error into a BanError\n * @param err - Error to convert\n * @param options - Additional options\n */\nexport function convertToBanError<T = unknown>(\n err: unknown,\n options: BanOptions<T> = {}\n): BanError<T> {\n // If already a BanError, merge options\n if (isBanError(err)) {\n const merged: BanError<T> = {\n status: options.statusCode ?? err.status,\n message: options.message ?? err.message,\n isBan: true,\n data: (options.data !== undefined ? options.data : err.data) as\n | T\n | undefined,\n headers: {\n ...err.headers,\n ...options.headers,\n },\n allow: options.allow\n ? Array.isArray(options.allow)\n ? [...options.allow]\n : [options.allow]\n : err.allow,\n cause: options.cause ?? err.cause,\n stack: err.stack,\n };\n\n return merged;\n }\n\n // Convert Error instance\n if (err instanceof Error) {\n return createError<T>({\n ...options,\n message: options.message ?? err.message,\n cause: err,\n });\n }\n\n // Handle unknown error types\n return createError<T>({\n ...options,\n message:\n options.message ?? (typeof err === \"string\" ? err : \"Unknown error\"),\n cause: err,\n });\n}\n",
|
|
6
|
+
"/**\n * Error formatting utilities\n * @module hono-ban/core/format-error\n */\n\nimport { STATUS_CODES } from \"../constants\";\nimport type { BanError, ErrorFormatter, FormatOptions } from \"../types\";\n\n/**\n * Format an error using the provided formatter\n * @param error - Error to format\n * @param formatter - Formatter to use\n * @param options - Formatting options\n */\nexport function formatError(\n error: BanError,\n formatter: ErrorFormatter,\n options: FormatOptions = {}\n): unknown {\n // Directly format the error without caching\n return formatter.format(\n error,\n options.headers,\n options.sanitize,\n options.includeStackTrace\n );\n}\n\n/**\n * Create a Response object from a formatted error\n * @param error - Error to create response from\n * @param formatted - Formatted error output\n */\nexport function createErrorResponse(\n error: BanError,\n formatted: unknown\n): Response {\n const headers = new Headers({\n \"Content-Type\": \"application/json\",\n ...error.headers,\n });\n\n if (error.allow?.length) {\n headers.set(\"Allow\", error.allow.join(\", \"));\n }\n\n // Check if this is a developer error in production\n const isDeveloperError =\n error.data &&\n typeof error.data === \"object\" &&\n \"isDeveloperError\" in error.data &&\n error.data.isDeveloperError === true;\n\n // Sanitize developer errors in production\n if (isDeveloperError && process.env.NODE_ENV === \"production\") {\n // Create a sanitized version without sensitive data\n const sanitizedFormatted = {\n statusCode: error.status,\n payload: {\n statusCode: error.status,\n error: STATUS_CODES[error.status],\n message: \"An internal server error occurred\",\n },\n };\n\n return new Response(JSON.stringify(sanitizedFormatted), {\n status: error.status,\n headers,\n });\n }\n\n return new Response(JSON.stringify(formatted), {\n status: error.status,\n headers,\n });\n}\n",
|
|
7
|
+
"/**\n * Sanitization utilities\n * @module hono-ban/utils/sanitize\n */\n\n/**\n * Recursively sanitize an object by removing specified keys\n * @param obj - Object to sanitize\n * @param keysToRemove - Keys to remove from object\n */\nexport function sanitizeObject(\n obj: unknown,\n keysToRemove: readonly string[]\n): unknown {\n if (!keysToRemove.length) {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => sanitizeObject(item, keysToRemove));\n }\n\n if (obj !== null && typeof obj === \"object\") {\n return Object.entries(obj).reduce((acc, [key, value]) => {\n if (keysToRemove.includes(key)) {\n return acc;\n }\n acc[key] = sanitizeObject(value, keysToRemove);\n return acc;\n }, {} as Record<string, unknown>);\n }\n\n return obj;\n}\n",
|
|
8
|
+
"/**\n * Default error formatter implementation\n * @module hono-ban/formatters/default\n */\n\nimport { STATUS_CODES } from \"../../constants\";\nimport type { BanError, DefaultErrorOutput, Headers } from \"../../types\";\nimport { sanitizeObject } from \"../../utils\";\n\n/**\n * Default JSON formatter maintaining backward compatibility\n */\nexport const defaultFormatter = {\n contentType: \"application/json\",\n\n /**\n * Format an error into a standardized output structure\n * @param error - Error to format\n * @param headers - Headers for HTTP response (not included in response body)\n * @param sanitize - Fields to remove from output\n * @param includeStackTrace - Whether to include stack traces\n */\n format(\n error: BanError,\n headers: Headers = {}, // Headers are used for HTTP headers, not included in response body\n sanitize: readonly string[] = [],\n includeStackTrace = false\n ): DefaultErrorOutput {\n const { status, message, data } = error;\n\n // Build base payload\n const payload: DefaultErrorOutput[\"payload\"] = {\n statusCode: status,\n error: STATUS_CODES[status] || \"Unknown Error\",\n };\n\n // Add optional fields\n if (typeof message === \"string\") {\n payload.message = message;\n }\n\n const isDeveloperError =\n data &&\n typeof data === \"object\" &&\n \"isDeveloperError\" in data &&\n data.isDeveloperError === true;\n\n if (includeStackTrace || isDeveloperError) {\n if (error.stack) {\n payload.stack = error.stack;\n }\n if (error.causeStack) {\n payload.causeStack = error.causeStack;\n }\n }\n\n if (data !== undefined) {\n payload.data = data;\n }\n\n // Create output structure\n const output: DefaultErrorOutput = {\n statusCode: status,\n payload: sanitizeObject(\n payload,\n sanitize\n ) as DefaultErrorOutput[\"payload\"],\n };\n\n return output;\n },\n};\n",
|
|
9
|
+
"/**\n * Server error factory functions (5xx)\n * @module hono-ban/factories/server-errors\n */\n\nimport type { BanError, BanOptions, ErrorStatusCode } from \"../types\";\nimport { createError } from \"../core\";\n\n/**\n * Helper function to reduce duplication\n * @param statusCode - HTTP status code\n * @param messageOrOptions - Error message or options\n * @param options - Additional options\n */\nfunction createErrorWithStatus<T>(\n statusCode: ErrorStatusCode,\n messageOrOptions?: string | Partial<BanOptions<T>>,\n options?: Partial<BanOptions<T>>\n): BanError<T> {\n if (typeof messageOrOptions === \"string\") {\n return createError<T>({\n ...options,\n statusCode,\n message: messageOrOptions,\n });\n }\n return createError<T>({ ...messageOrOptions, ...options, statusCode });\n}\n\n/**\n * Create a 500 Internal Server Error\n * @param messageOrOptions - Error message or options\n * @param options - Additional options\n */\nexport function internal<T = unknown>(\n messageOrOptions?: string | Partial<BanOptions<T>>,\n options?: Partial<BanOptions<T>>\n): BanError<T> {\n return createErrorWithStatus(\n 500 as ErrorStatusCode,\n messageOrOptions,\n options\n );\n}\n\n/**\n * Create a 501 Not Implemented error\n * @param messageOrOptions - Error message or options\n * @param options - Additional options\n */\nexport function notImplemented<T = unknown>(\n messageOrOptions?: string | Partial<BanOptions<T>>,\n options?: Partial<BanOptions<T>>\n): BanError<T> {\n return createErrorWithStatus(\n 501 as ErrorStatusCode,\n messageOrOptions,\n options\n );\n}\n\n/**\n * Create a 502 Bad Gateway error\n * @param messageOrOptions - Error message or options\n * @param options - Additional options\n */\nexport function badGateway<T = unknown>(\n messageOrOptions?: string | Partial<BanOptions<T>>,\n options?: Partial<BanOptions<T>>\n): BanError<T> {\n return createErrorWithStatus(\n 502 as ErrorStatusCode,\n messageOrOptions,\n options\n );\n}\n\n/**\n * Create a 503 Service Unavailable error\n * @param messageOrOptions - Error message or options\n * @param options - Additional options\n */\nexport function serverUnavailable<T = unknown>(\n messageOrOptions?: string | Partial<BanOptions<T>>,\n options?: Partial<BanOptions<T>>\n): BanError<T> {\n return createErrorWithStatus(\n 503 as ErrorStatusCode,\n messageOrOptions,\n options\n );\n}\n\n/**\n * Create a 504 Gateway Timeout error\n * @param messageOrOptions - Error message or options\n * @param options - Additional options\n */\nexport function gatewayTimeout<T = unknown>(\n messageOrOptions?: string | Partial<BanOptions<T>>,\n options?: Partial<BanOptions<T>>\n): BanError<T> {\n return createErrorWithStatus(\n 504 as ErrorStatusCode,\n messageOrOptions,\n options\n );\n}\n\n/**\n * Create a 505 HTTP Version Not Supported error\n * @param messageOrOptions - Error message or options\n * @param options - Additional options\n */\nexport function httpVersionNotSupported<T = unknown>(\n messageOrOptions?: string | Partial<BanOptions<T>>,\n options?: Partial<BanOptions<T>>\n): BanError<T> {\n return createErrorWithStatus(\n 505 as ErrorStatusCode,\n messageOrOptions,\n options\n );\n}\n\n/**\n * Create a 506 Variant Also Negotiates error\n * @param messageOrOptions - Error message or options\n * @param options - Additional options\n */\nexport function variantAlsoNegotiates<T = unknown>(\n messageOrOptions?: string | Partial<BanOptions<T>>,\n options?: Partial<BanOptions<T>>\n): BanError<T> {\n return createErrorWithStatus(\n 506 as ErrorStatusCode,\n messageOrOptions,\n options\n );\n}\n\n/**\n * Create a 507 Insufficient Storage error\n * @param messageOrOptions - Error message or options\n * @param options - Additional options\n */\nexport function insufficientStorage<T = unknown>(\n messageOrOptions?: string | Partial<BanOptions<T>>,\n options?: Partial<BanOptions<T>>\n): BanError<T> {\n return createErrorWithStatus(\n 507 as ErrorStatusCode,\n messageOrOptions,\n options\n );\n}\n\n/**\n * Create a 508 Loop Detected error\n * @param messageOrOptions - Error message or options\n * @param options - Additional options\n */\nexport function loopDetected<T = unknown>(\n messageOrOptions?: string | Partial<BanOptions<T>>,\n options?: Partial<BanOptions<T>>\n): BanError<T> {\n return createErrorWithStatus(\n 508 as ErrorStatusCode,\n messageOrOptions,\n options\n );\n}\n\n/**\n * Create a 510 Not Extended error\n * @param messageOrOptions - Error message or options\n * @param options - Additional options\n */\nexport function notExtended<T = unknown>(\n messageOrOptions?: string | Partial<BanOptions<T>>,\n options?: Partial<BanOptions<T>>\n): BanError<T> {\n return createErrorWithStatus(\n 510 as ErrorStatusCode,\n messageOrOptions,\n options\n );\n}\n\n/**\n * Create a 511 Network Authentication Required error\n * @param messageOrOptions - Error message or options\n * @param options - Additional options\n */\nexport function networkAuthRequired<T = unknown>(\n messageOrOptions?: string | Partial<BanOptions<T>>,\n options?: Partial<BanOptions<T>>\n): BanError<T> {\n return createErrorWithStatus(\n 511 as ErrorStatusCode,\n messageOrOptions,\n options\n );\n}\n\n/**\n * Create a 500 Internal Server Error marked as a developer error\n * @param messageOrOptions - Error message or options\n * @param options - Additional options\n */\nexport function badImplementation<T = unknown>(\n messageOrOptions?: string | Partial<BanOptions<T>>,\n options?: Partial<BanOptions<T>>\n): BanError<T> {\n const mergedOptions =\n typeof messageOrOptions === \"string\"\n ? { ...options, message: messageOrOptions }\n : { ...messageOrOptions, ...options };\n\n const mergedData = {\n isDeveloperError: true,\n ...((mergedOptions.data as Record<string, unknown>) || {}),\n } as unknown as T;\n\n return createError<T>({\n ...mergedOptions,\n statusCode: 500 as ErrorStatusCode,\n data: mergedData,\n });\n}\n",
|
|
10
|
+
"/**\n * Error handling middleware\n * @module hono-ban/middleware/ban-middleware\n */\n\nimport type { MiddlewareHandler } from \"hono\";\nimport { convertToBanError, formatError, createErrorResponse } from \"../core\";\nimport { defaultFormatter } from \"../formatters\";\nimport type { BanMiddlewareOptions } from \"../types\";\n\n/**\n * Default middleware options\n */\nconst DEFAULT_OPTIONS: Required<BanMiddlewareOptions> = {\n formatter: defaultFormatter,\n sanitize: [],\n includeStackTrace: false,\n headers: {},\n};\n\n/**\n * Create error handling middleware\n * @param options - Middleware configuration options\n *\n * @example\n * // Simple usage\n * app.use(ban());\n *\n * @example\n * // Advanced usage\n * app.use(ban({\n * formatter: customFormatter,\n * sanitize: ['password', 'token'],\n * includeStackTrace: process.env.NODE_ENV !== 'production'\n * }));\n */\nexport function ban(options: BanMiddlewareOptions = {}): MiddlewareHandler {\n const resolvedOptions: Required<BanMiddlewareOptions> = {\n ...DEFAULT_OPTIONS,\n ...options,\n formatter: options.formatter\n ? options.formatter\n : DEFAULT_OPTIONS.formatter,\n headers: {\n ...DEFAULT_OPTIONS.headers,\n ...options.headers,\n },\n sanitize: [...DEFAULT_OPTIONS.sanitize, ...(options.sanitize || [])],\n };\n\n // Return the middleware function that uses the pre-merged options\n return async (_, next) => {\n try {\n await next();\n } catch (err) {\n // Get the pre-resolved formatter instance\n const formatter = resolvedOptions.formatter;\n\n const error = convertToBanError(err, {\n formatter,\n headers: resolvedOptions.headers,\n sanitize: resolvedOptions.sanitize,\n includeStackTrace: resolvedOptions.includeStackTrace,\n });\n\n // Format the error using pre-resolved options\n const formatted = formatError(error, formatter, {\n headers: resolvedOptions.headers,\n sanitize: resolvedOptions.sanitize,\n includeStackTrace: resolvedOptions.includeStackTrace,\n });\n\n // Create and return response\n return createErrorResponse(error, formatted);\n }\n };\n}\n",
|
|
11
|
+
"/**\n * Main entry point for hono-ban\n * @module hono-ban\n */\n\n// Export core functionality\nexport * from \"./core\";\n\n// Export formatters\nexport * from \"./formatters\";\n\n// Export error factories\nexport * from \"./factories\";\n\n// Export constants\nexport * from \"./constants\";\n\n// Export types\nexport * from \"./types\";\n\n// Export middleware as default\nimport { ban } from \"./middleware\";\nexport default ban;\n"
|
|
12
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AAA,MACF,MAAM,KAAK;AAAA,MACX,OAAO,KAAK;AAAA,MAEZ,MAAM,YAAY,gBAAgB;AAAA,MAElC,MAAM,QAAQ,kBAAkB,KAAK;AAAA,QACnC;AAAA,QACA,SAAS,gBAAgB;AAAA,QACzB,UAAU,gBAAgB;AAAA,QAC1B,mBAAmB,gBAAgB;AAAA,MACrC,CAAC;AAAA,MAGD,MAAM,YAAY,YAAY,OAAO,WAAW;AAAA,QAC9C,SAAS,gBAAgB;AAAA,QACzB,UAAU,gBAAgB;AAAA,QAC1B,mBAAmB,gBAAgB;AAAA,MACrC,CAAC;AAAA,MAGD,OAAO,oBAAoB,OAAO,SAAS;AAAA;AAAA;AAAA;;ACnDjD,IAAe;",
|
|
14
|
+
"debugId": "4A7C3F0FCA1780B264756E2164756E21",
|
|
15
|
+
"names": []
|
|
16
|
+
}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import { z } from "@hono/zod-openapi";
|
|
6
6
|
import type { ErrorFormatter } from "../../types";
|
|
7
|
-
import type {
|
|
7
|
+
import type { RFC7807ValidationParam, RFC7807FormatterOptions as RFC7807Options } from "../../types";
|
|
8
8
|
/**
|
|
9
9
|
* Create an RFC 7807 Problem Details formatter
|
|
10
10
|
*/
|
|
@@ -12,7 +12,7 @@ export declare function createRFC7807Formatter(options?: RFC7807Options): ErrorF
|
|
|
12
12
|
/**
|
|
13
13
|
* Create validation error data in RFC 7807 format
|
|
14
14
|
*/
|
|
15
|
-
export declare function
|
|
15
|
+
export declare function createRFC7807ValidationError(params: RFC7807ValidationParam[]): {
|
|
16
16
|
"invalid-params": {
|
|
17
17
|
name: string;
|
|
18
18
|
reason: string;
|
|
@@ -21,7 +21,7 @@ export declare function createValidationError(params: ValidationParam[]): {
|
|
|
21
21
|
/**
|
|
22
22
|
* Convert Zod validation errors to RFC 7807 format
|
|
23
23
|
*/
|
|
24
|
-
export declare function
|
|
24
|
+
export declare function createRFC7807ZodValidationError(error: z.ZodError): {
|
|
25
25
|
"invalid-params": {
|
|
26
26
|
name: string;
|
|
27
27
|
reason: string;
|
|
@@ -30,7 +30,7 @@ export declare function createZodValidationError(error: z.ZodError): {
|
|
|
30
30
|
/**
|
|
31
31
|
* Create constraint violation data in RFC 7807 format
|
|
32
32
|
*/
|
|
33
|
-
export declare function
|
|
33
|
+
export declare function createRFC7807ConstraintViolation(name: string, reason: string, resource: string, constraint?: string): {
|
|
34
34
|
violations: {
|
|
35
35
|
name: string;
|
|
36
36
|
reason: string;
|
|
@@ -4,12 +4,37 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import { Hook } from "@hono/zod-openapi";
|
|
6
6
|
import { Env } from "hono";
|
|
7
|
-
import type { RFC7807FormatterOptions as RFC7807Options } from "../../types";
|
|
7
|
+
import type { RFC7807FormatterOptions as RFC7807Options, BanOptions } from "../../types";
|
|
8
8
|
/**
|
|
9
9
|
* Create a Hono hook that formats validation errors using RFC 7807
|
|
10
|
+
*
|
|
11
|
+
* This hook throws a badRequest error that will be caught and processed by the ban middleware.
|
|
12
|
+
* You can provide options to override the default behavior of the middleware.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* // Basic usage - inherits all settings from middleware
|
|
16
|
+
* app.openapi(route, handler, { onError: createRFC7807Hook() });
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* // With custom message
|
|
20
|
+
* app.openapi(route, handler, {
|
|
21
|
+
* onError: createRFC7807Hook({ message: "Custom validation error" })
|
|
22
|
+
* });
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* // With custom formatter and sanitization
|
|
26
|
+
* app.openapi(route, handler, {
|
|
27
|
+
* onError: createRFC7807Hook({
|
|
28
|
+
* formatter: customFormatter,
|
|
29
|
+
* sanitize: ['password', 'token']
|
|
30
|
+
* })
|
|
31
|
+
* });
|
|
10
32
|
*/
|
|
11
|
-
export declare function createRFC7807Hook(options?: RFC7807Options): Hook<any,
|
|
33
|
+
export declare function createRFC7807Hook<E extends Env = Env>(options?: RFC7807Options & Partial<BanOptions>): Hook<any, E, any, any>;
|
|
12
34
|
/**
|
|
13
35
|
* Pre-configured RFC 7807 hook with default options
|
|
36
|
+
*
|
|
37
|
+
* This is a convenience export that uses the default options.
|
|
38
|
+
* It will throw a badRequest error that will be caught and processed by the ban middleware.
|
|
14
39
|
*/
|
|
15
40
|
export declare const rfc7807Hook: Hook<any, Env, any, any>;
|
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
* RFC 7807 Problem Details implementation for Hono Ban
|
|
3
3
|
* @module hono-ban/formatters/rfc7807
|
|
4
4
|
*/
|
|
5
|
-
export { createRFC7807Formatter,
|
|
5
|
+
export { createRFC7807Formatter, createRFC7807ValidationError, createRFC7807ZodValidationError, createRFC7807ConstraintViolation, } from "./formatter";
|
|
6
6
|
export { createRFC7807Hook, rfc7807Hook } from "./hooks";
|
|
7
|
-
export {
|
|
7
|
+
export { RFC7807ValidationParamSchema, RFC7807ConstraintViolationSchema, RFC7807ErrorDataSchema, RFC7807DetailsSchema, } from "./schemas";
|
|
@@ -4,9 +4,9 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import { z } from "@hono/zod-openapi";
|
|
6
6
|
/**
|
|
7
|
-
* Schema for validation error parameters
|
|
7
|
+
* Schema for RFC 7807 validation error parameters
|
|
8
8
|
*/
|
|
9
|
-
export declare const
|
|
9
|
+
export declare const RFC7807ValidationParamSchema: z.ZodObject<{
|
|
10
10
|
name: z.ZodString;
|
|
11
11
|
reason: z.ZodString;
|
|
12
12
|
}, "strip", z.ZodTypeAny, {
|
|
@@ -17,9 +17,9 @@ export declare const ValidationParamSchema: z.ZodObject<{
|
|
|
17
17
|
reason: string;
|
|
18
18
|
}>;
|
|
19
19
|
/**
|
|
20
|
-
* Schema for constraint violations
|
|
20
|
+
* Schema for RFC 7807 constraint violations
|
|
21
21
|
*/
|
|
22
|
-
export declare const
|
|
22
|
+
export declare const RFC7807ConstraintViolationSchema: z.ZodObject<{
|
|
23
23
|
name: z.ZodString;
|
|
24
24
|
reason: z.ZodString;
|
|
25
25
|
resource: z.ZodString;
|
|
@@ -36,9 +36,9 @@ export declare const ConstraintViolationSchema: z.ZodObject<{
|
|
|
36
36
|
constraint: string;
|
|
37
37
|
}>;
|
|
38
38
|
/**
|
|
39
|
-
* Schema for additional error data in problem details
|
|
39
|
+
* Schema for additional error data in RFC 7807 problem details
|
|
40
40
|
*/
|
|
41
|
-
export declare const
|
|
41
|
+
export declare const RFC7807ErrorDataSchema: z.ZodObject<{
|
|
42
42
|
"invalid-params": z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
43
43
|
name: z.ZodString;
|
|
44
44
|
reason: z.ZodString;
|
|
@@ -91,13 +91,13 @@ export declare const ProblemErrorDataSchema: z.ZodObject<{
|
|
|
91
91
|
/**
|
|
92
92
|
* Schema for complete RFC 7807 problem details
|
|
93
93
|
*/
|
|
94
|
-
export declare const
|
|
94
|
+
export declare const RFC7807DetailsSchema: z.ZodObject<z.objectUtil.extendShape<{
|
|
95
95
|
type: z.ZodString;
|
|
96
96
|
title: z.ZodString;
|
|
97
97
|
status: z.ZodNumber;
|
|
98
|
-
detail: z.ZodString
|
|
99
|
-
instance: z.ZodString
|
|
100
|
-
timestamp: z.ZodString
|
|
98
|
+
detail: z.ZodOptional<z.ZodString>;
|
|
99
|
+
instance: z.ZodOptional<z.ZodString>;
|
|
100
|
+
timestamp: z.ZodOptional<z.ZodString>;
|
|
101
101
|
}, {
|
|
102
102
|
"invalid-params": z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
103
103
|
name: z.ZodString;
|
|
@@ -129,9 +129,6 @@ export declare const ProblemDetailsSchema: z.ZodObject<z.objectUtil.extendShape<
|
|
|
129
129
|
type: string;
|
|
130
130
|
title: string;
|
|
131
131
|
status: number;
|
|
132
|
-
detail: string;
|
|
133
|
-
instance: string;
|
|
134
|
-
timestamp: string;
|
|
135
132
|
"invalid-params"?: {
|
|
136
133
|
name: string;
|
|
137
134
|
reason: string;
|
|
@@ -142,13 +139,13 @@ export declare const ProblemDetailsSchema: z.ZodObject<z.objectUtil.extendShape<
|
|
|
142
139
|
resource: string;
|
|
143
140
|
constraint: string;
|
|
144
141
|
}[] | undefined;
|
|
142
|
+
detail?: string | undefined;
|
|
143
|
+
instance?: string | undefined;
|
|
144
|
+
timestamp?: string | undefined;
|
|
145
145
|
}, {
|
|
146
146
|
type: string;
|
|
147
147
|
title: string;
|
|
148
148
|
status: number;
|
|
149
|
-
detail: string;
|
|
150
|
-
instance: string;
|
|
151
|
-
timestamp: string;
|
|
152
149
|
"invalid-params"?: {
|
|
153
150
|
name: string;
|
|
154
151
|
reason: string;
|
|
@@ -159,4 +156,7 @@ export declare const ProblemDetailsSchema: z.ZodObject<z.objectUtil.extendShape<
|
|
|
159
156
|
resource: string;
|
|
160
157
|
constraint: string;
|
|
161
158
|
}[] | undefined;
|
|
159
|
+
detail?: string | undefined;
|
|
160
|
+
instance?: string | undefined;
|
|
161
|
+
timestamp?: string | undefined;
|
|
162
162
|
}>;
|
|
@@ -8,87 +8,70 @@
|
|
|
8
8
|
* @module hono-ban/types/rfc7807
|
|
9
9
|
* @see {@link https://datatracker.ietf.org/doc/html/rfc7807} RFC 7807 Problem Details
|
|
10
10
|
*/
|
|
11
|
+
import { z } from "@hono/zod-openapi";
|
|
12
|
+
import { RFC7807ValidationParamSchema, RFC7807ConstraintViolationSchema, RFC7807ErrorDataSchema, RFC7807DetailsSchema } from "../formatters/rfc7807/schemas";
|
|
11
13
|
/**
|
|
12
14
|
* Represents a validation error parameter in an RFC 7807 problem details object.
|
|
13
15
|
* Used to indicate specific validation failures in request parameters.
|
|
14
16
|
*
|
|
15
|
-
* @
|
|
17
|
+
* @type RFC7807ValidationParam
|
|
16
18
|
* @property {string} name - The name of the parameter that failed validation
|
|
17
19
|
* @property {string} reason - The reason why the parameter failed validation
|
|
18
20
|
*/
|
|
19
|
-
export
|
|
20
|
-
name: string;
|
|
21
|
-
reason: string;
|
|
22
|
-
}
|
|
21
|
+
export type RFC7807ValidationParam = z.infer<typeof RFC7807ValidationParamSchema>;
|
|
23
22
|
/**
|
|
24
23
|
* Represents a constraint violation in an RFC 7807 problem details object.
|
|
25
24
|
* Used to indicate violations of business rules or data constraints.
|
|
26
25
|
*
|
|
27
|
-
* @
|
|
26
|
+
* @type RFC7807ConstraintViolation
|
|
28
27
|
* @property {string} name - The name of the violated constraint
|
|
29
28
|
* @property {string} reason - The reason why the constraint was violated
|
|
30
29
|
* @property {string} resource - The resource or entity where the violation occurred
|
|
31
30
|
* @property {string} constraint - The specific constraint that was violated
|
|
32
31
|
*/
|
|
33
|
-
export
|
|
34
|
-
name: string;
|
|
35
|
-
reason: string;
|
|
36
|
-
resource: string;
|
|
37
|
-
constraint: string;
|
|
38
|
-
}
|
|
32
|
+
export type RFC7807ConstraintViolation = z.infer<typeof RFC7807ConstraintViolationSchema>;
|
|
39
33
|
/**
|
|
40
34
|
* Additional error data that can be included in an RFC 7807 problem details object.
|
|
41
35
|
* This interface extends the standard problem details with validation and constraint information.
|
|
42
36
|
*
|
|
43
|
-
* @
|
|
44
|
-
* @property {
|
|
45
|
-
* @property {
|
|
37
|
+
* @type RFC7807ErrorData
|
|
38
|
+
* @property {RFC7807ValidationParam[]} [invalid-params] - Array of validation errors
|
|
39
|
+
* @property {RFC7807ConstraintViolation[]} [violations] - Array of constraint violations
|
|
46
40
|
*/
|
|
47
|
-
export
|
|
48
|
-
"invalid-params"?: ValidationParam[];
|
|
49
|
-
violations?: ConstraintViolation[];
|
|
50
|
-
}
|
|
41
|
+
export type RFC7807ErrorData = z.infer<typeof RFC7807ErrorDataSchema>;
|
|
51
42
|
/**
|
|
52
43
|
* Complete RFC 7807 problem details object structure.
|
|
53
44
|
* This interface represents the full problem details format as defined in RFC 7807,
|
|
54
45
|
* with additional properties for validation and constraint violation data.
|
|
55
46
|
*
|
|
56
|
-
* @
|
|
57
|
-
* @extends ProblemErrorData
|
|
47
|
+
* @type RFC7807Details
|
|
58
48
|
* @property {string} type - URI reference that identifies the problem type
|
|
59
49
|
* @property {string} title - Short, human-readable summary of the problem
|
|
60
50
|
* @property {number} status - HTTP status code (400-599)
|
|
61
|
-
* @property {string} detail - Human-readable explanation specific to this occurrence
|
|
62
|
-
* @property {string} instance - URI reference that identifies the specific occurrence
|
|
63
|
-
* @property {string} timestamp - ISO 8601 datetime when the error occurred
|
|
51
|
+
* @property {string} [detail] - Human-readable explanation specific to this occurrence
|
|
52
|
+
* @property {string} [instance] - URI reference that identifies the specific occurrence
|
|
53
|
+
* @property {string} [timestamp] - ISO 8601 datetime when the error occurred
|
|
64
54
|
*/
|
|
65
|
-
export
|
|
66
|
-
type: string;
|
|
67
|
-
title: string;
|
|
68
|
-
status: number;
|
|
69
|
-
detail: string;
|
|
70
|
-
instance: string;
|
|
71
|
-
timestamp: string;
|
|
72
|
-
}
|
|
55
|
+
export type RFC7807Details = z.infer<typeof RFC7807DetailsSchema>;
|
|
73
56
|
/**
|
|
74
57
|
* Hook function for customizing RFC 7807 problem details before formatting.
|
|
75
58
|
* This type represents a function that can modify the problem details object
|
|
76
59
|
* before it is serialized into the final response.
|
|
77
60
|
*
|
|
78
|
-
* @callback
|
|
79
|
-
* @param {
|
|
80
|
-
* @returns {
|
|
61
|
+
* @callback RFC7807DetailsHook
|
|
62
|
+
* @param {RFC7807Details} details - The problem details object to modify
|
|
63
|
+
* @returns {RFC7807Details} The modified problem details object
|
|
81
64
|
*/
|
|
82
|
-
export type
|
|
65
|
+
export type RFC7807DetailsHook = (details: RFC7807Details) => RFC7807Details;
|
|
83
66
|
/**
|
|
84
67
|
* Configuration options for the RFC 7807 formatter.
|
|
85
68
|
* These options control how problem details are generated and formatted.
|
|
86
69
|
*
|
|
87
70
|
* @interface RFC7807FormatterOptions
|
|
88
71
|
* @property {string} [baseUrl="https://api.example.com/problems"] - Base URL for problem type URIs
|
|
89
|
-
* @property {
|
|
72
|
+
* @property {RFC7807DetailsHook[]} [hooks=[]] - Array of hooks for customizing problem details
|
|
90
73
|
*/
|
|
91
74
|
export interface RFC7807FormatterOptions {
|
|
92
75
|
baseUrl?: string;
|
|
93
|
-
hooks?:
|
|
76
|
+
hooks?: RFC7807DetailsHook[];
|
|
94
77
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "hono-ban",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.4",
|
|
4
4
|
"description": "HTTP-friendly error objects for Hono, inspired by Boom",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/cjs/index.js",
|
|
@@ -37,11 +37,11 @@
|
|
|
37
37
|
"sideEffects": false,
|
|
38
38
|
"scripts": {
|
|
39
39
|
"build": "bun run build:esm && bun run build:cjs && bun run build:declaration",
|
|
40
|
-
"build:esm": "bun build --target=node
|
|
41
|
-
"build:cjs": "bun build --target=node
|
|
40
|
+
"build:esm": "bun build --target=node --format=esm --packages=external --outdir=dist/esm --sourcemap=linked --splitting ./src/index.ts ./src/formatters/rfc7807/index.ts",
|
|
41
|
+
"build:cjs": "bun build --target=node --format=cjs --packages=external --outdir=dist/cjs --sourcemap=linked --splitting ./src/index.ts ./src/formatters/rfc7807/index.ts",
|
|
42
42
|
"build:declaration": "tsc --emitDeclarationOnly --project tsconfig.types.json",
|
|
43
43
|
"postbuild": "rimraf tsconfig.types.tsbuildinfo",
|
|
44
|
-
"dev": "bun build
|
|
44
|
+
"dev": "bun build --target=node --packages=external --outdir=dist --watch ./src/index.ts ./src/formatters/rfc7807/index.ts",
|
|
45
45
|
"test": "bun test",
|
|
46
46
|
"test:watch": "bun test --watch",
|
|
47
47
|
"test:coverage": "bun test --coverage",
|
|
@@ -7,15 +7,15 @@ import { z } from "@hono/zod-openapi";
|
|
|
7
7
|
import { STATUS_CODES } from "../../constants";
|
|
8
8
|
import type { BanError, ErrorFormatter } from "../../types";
|
|
9
9
|
import type {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
10
|
+
RFC7807Details,
|
|
11
|
+
RFC7807ErrorData,
|
|
12
|
+
RFC7807ValidationParam,
|
|
13
13
|
RFC7807FormatterOptions as RFC7807Options,
|
|
14
14
|
} from "../../types";
|
|
15
15
|
import {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
16
|
+
RFC7807ConstraintViolationSchema,
|
|
17
|
+
RFC7807DetailsSchema,
|
|
18
|
+
RFC7807ValidationParamSchema,
|
|
19
19
|
} from "./schemas";
|
|
20
20
|
|
|
21
21
|
/**
|
|
@@ -29,7 +29,7 @@ export function createRFC7807Formatter(
|
|
|
29
29
|
return {
|
|
30
30
|
contentType: "application/problem+json",
|
|
31
31
|
|
|
32
|
-
format<T extends
|
|
32
|
+
format<T extends RFC7807ErrorData>(error: BanError<T>): RFC7807Details {
|
|
33
33
|
const base = {
|
|
34
34
|
type: `${baseUrl}/${error.status}`,
|
|
35
35
|
title: STATUS_CODES[error.status] || "Unknown Error",
|
|
@@ -41,7 +41,7 @@ export function createRFC7807Formatter(
|
|
|
41
41
|
|
|
42
42
|
// Handle validation errors
|
|
43
43
|
if (error.data?.["invalid-params"]) {
|
|
44
|
-
return
|
|
44
|
+
return RFC7807DetailsSchema.parse({
|
|
45
45
|
...base,
|
|
46
46
|
"invalid-params": error.data["invalid-params"],
|
|
47
47
|
});
|
|
@@ -49,13 +49,13 @@ export function createRFC7807Formatter(
|
|
|
49
49
|
|
|
50
50
|
// Handle constraint violations
|
|
51
51
|
if (error.data?.violations) {
|
|
52
|
-
return
|
|
52
|
+
return RFC7807DetailsSchema.parse({
|
|
53
53
|
...base,
|
|
54
54
|
violations: error.data.violations,
|
|
55
55
|
});
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
-
return
|
|
58
|
+
return RFC7807DetailsSchema.parse(base);
|
|
59
59
|
},
|
|
60
60
|
};
|
|
61
61
|
}
|
|
@@ -63,18 +63,18 @@ export function createRFC7807Formatter(
|
|
|
63
63
|
/**
|
|
64
64
|
* Create validation error data in RFC 7807 format
|
|
65
65
|
*/
|
|
66
|
-
export function
|
|
66
|
+
export function createRFC7807ValidationError(params: RFC7807ValidationParam[]) {
|
|
67
67
|
return {
|
|
68
|
-
"invalid-params":
|
|
68
|
+
"invalid-params": RFC7807ValidationParamSchema.array().parse(params),
|
|
69
69
|
};
|
|
70
70
|
}
|
|
71
71
|
|
|
72
72
|
/**
|
|
73
73
|
* Convert Zod validation errors to RFC 7807 format
|
|
74
74
|
*/
|
|
75
|
-
export function
|
|
75
|
+
export function createRFC7807ZodValidationError(error: z.ZodError) {
|
|
76
76
|
return {
|
|
77
|
-
"invalid-params":
|
|
77
|
+
"invalid-params": RFC7807ValidationParamSchema.array().parse(
|
|
78
78
|
error.errors.map((e) => ({
|
|
79
79
|
name: e.path.join("."),
|
|
80
80
|
reason: e.message,
|
|
@@ -86,14 +86,14 @@ export function createZodValidationError(error: z.ZodError) {
|
|
|
86
86
|
/**
|
|
87
87
|
* Create constraint violation data in RFC 7807 format
|
|
88
88
|
*/
|
|
89
|
-
export function
|
|
89
|
+
export function createRFC7807ConstraintViolation(
|
|
90
90
|
name: string,
|
|
91
91
|
reason: string,
|
|
92
92
|
resource: string,
|
|
93
93
|
constraint: string = "unique"
|
|
94
94
|
) {
|
|
95
95
|
return {
|
|
96
|
-
violations:
|
|
96
|
+
violations: RFC7807ConstraintViolationSchema.array().parse([
|
|
97
97
|
{
|
|
98
98
|
name,
|
|
99
99
|
reason,
|
|
@@ -7,41 +7,67 @@ import { ZodError } from "zod";
|
|
|
7
7
|
import { Hook } from "@hono/zod-openapi";
|
|
8
8
|
import { Env } from "hono";
|
|
9
9
|
import { badRequest } from "../../factories";
|
|
10
|
-
import {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
import {
|
|
10
|
+
import type {
|
|
11
|
+
RFC7807FormatterOptions as RFC7807Options,
|
|
12
|
+
BanOptions,
|
|
13
|
+
} from "../../types";
|
|
14
|
+
import { createRFC7807ZodValidationError } from "./formatter";
|
|
15
15
|
|
|
16
16
|
/**
|
|
17
17
|
* Create a Hono hook that formats validation errors using RFC 7807
|
|
18
|
+
*
|
|
19
|
+
* This hook throws a badRequest error that will be caught and processed by the ban middleware.
|
|
20
|
+
* You can provide options to override the default behavior of the middleware.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* // Basic usage - inherits all settings from middleware
|
|
24
|
+
* app.openapi(route, handler, { onError: createRFC7807Hook() });
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* // With custom message
|
|
28
|
+
* app.openapi(route, handler, {
|
|
29
|
+
* onError: createRFC7807Hook({ message: "Custom validation error" })
|
|
30
|
+
* });
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* // With custom formatter and sanitization
|
|
34
|
+
* app.openapi(route, handler, {
|
|
35
|
+
* onError: createRFC7807Hook({
|
|
36
|
+
* formatter: customFormatter,
|
|
37
|
+
* sanitize: ['password', 'token']
|
|
38
|
+
* })
|
|
39
|
+
* });
|
|
18
40
|
*/
|
|
19
|
-
export function createRFC7807Hook(
|
|
20
|
-
options?: RFC7807Options
|
|
21
|
-
): Hook<any,
|
|
22
|
-
const formatter = createRFC7807Formatter(options);
|
|
23
|
-
|
|
41
|
+
export function createRFC7807Hook<E extends Env = Env>(
|
|
42
|
+
options?: RFC7807Options & Partial<BanOptions>
|
|
43
|
+
): Hook<any, E, any, any> {
|
|
24
44
|
return (result, c) => {
|
|
25
45
|
if (
|
|
26
46
|
!result.success &&
|
|
27
47
|
"error" in result &&
|
|
28
48
|
result.error instanceof ZodError
|
|
29
49
|
) {
|
|
30
|
-
// Create the error
|
|
31
|
-
const
|
|
32
|
-
data: createZodValidationError(result.error),
|
|
33
|
-
});
|
|
50
|
+
// Create the validation error data
|
|
51
|
+
const validationData = createRFC7807ZodValidationError(result.error);
|
|
34
52
|
|
|
35
|
-
//
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
53
|
+
// Throw badRequest with both the validation data and any override options
|
|
54
|
+
throw badRequest({
|
|
55
|
+
message: options?.message || "Validation Error",
|
|
56
|
+
data: validationData,
|
|
57
|
+
// Pass through any override options
|
|
58
|
+
formatter: options?.formatter,
|
|
59
|
+
headers: options?.headers,
|
|
60
|
+
sanitize: options?.sanitize,
|
|
61
|
+
includeStackTrace: options?.includeStackTrace,
|
|
62
|
+
});
|
|
40
63
|
}
|
|
41
64
|
};
|
|
42
65
|
}
|
|
43
66
|
|
|
44
67
|
/**
|
|
45
68
|
* Pre-configured RFC 7807 hook with default options
|
|
69
|
+
*
|
|
70
|
+
* This is a convenience export that uses the default options.
|
|
71
|
+
* It will throw a badRequest error that will be caught and processed by the ban middleware.
|
|
46
72
|
*/
|
|
47
|
-
export const rfc7807Hook = createRFC7807Hook();
|
|
73
|
+
export const rfc7807Hook = createRFC7807Hook<Env>();
|
|
@@ -5,16 +5,16 @@
|
|
|
5
5
|
|
|
6
6
|
export {
|
|
7
7
|
createRFC7807Formatter,
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
createRFC7807ValidationError,
|
|
9
|
+
createRFC7807ZodValidationError,
|
|
10
|
+
createRFC7807ConstraintViolation,
|
|
11
11
|
} from "./formatter";
|
|
12
12
|
|
|
13
13
|
export { createRFC7807Hook, rfc7807Hook } from "./hooks";
|
|
14
14
|
|
|
15
15
|
export {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
16
|
+
RFC7807ValidationParamSchema,
|
|
17
|
+
RFC7807ConstraintViolationSchema,
|
|
18
|
+
RFC7807ErrorDataSchema,
|
|
19
|
+
RFC7807DetailsSchema,
|
|
20
20
|
} from "./schemas";
|