import { RateLimitPluginOptions } from "@fastify/rate-limit"; import { FastifyInstance, FastifyRequest } from "fastify"; import { Hookified, HookifiedOptions } from "hookified"; import Keyv from "keyv"; type BinStoreErrorInfo = { name: string; message: string; code: string | number | null; }; type BinHealth = { status: "ok"; bins: { store: "mongo" | "memory"; connected: true; latencyMs: number; uriPresent: boolean; uri?: UriDiagnostics; }; } | { status: "error"; bins: { store: "mongo" | "memory"; connected: false; uriPresent: boolean; uri?: UriDiagnostics; error: BinStoreErrorInfo; }; }; /** Redacted URI facts for `GET /healthz`. No password and no full URI. */ type UriDiagnostics = { length: number; leadingWhitespace: boolean; trailingWhitespace: boolean; newline: boolean; wrappedQuotes: boolean; atCount: number; passwordReserved: string[]; passwordHasPercent: boolean; }; type CertificateOptions = { /** * Common Name for the certificate subject. Defaults to 'localhost'. */ commonName?: string; /** * Subject Alternative Names. Defaults to [dns:localhost, ip:127.0.0.1, ip:::1]. */ altNames?: Array<{ type: "dns"; value: string; } | { type: "ip"; value: string; }>; /** * Number of days the certificate is valid. Defaults to 365. */ validityDays?: number; /** * RSA key size in bits. Defaults to 2048. */ keySize?: number; }; type CertificateResult = { /** * PEM-encoded X.509 certificate. */ cert: string; /** * PEM-encoded PKCS#8 private key. */ key: string; }; type CertificateFileOptions = CertificateOptions & { /** * File path to write the certificate PEM. */ certPath: string; /** * File path to write the private key PEM. */ keyPath: string; }; /** * Generate a self-signed certificate using only Node.js built-in crypto. * Returns PEM-encoded certificate and private key strings. */ export declare function generateCertificate(options?: CertificateOptions): CertificateResult; /** * Generate a self-signed certificate and write PEM files to disk. * Returns the same CertificateResult as generateCertificate(). */ export declare function generateCertificateFiles(options: CertificateFileOptions): Promise; /** * A request captured by a bin, including method, headers, body and metadata. */ type CapturedRequest = { /** Unique identifier for this captured request */ id: string; /** Identifier of the bin that captured this request */ binId: string; /** HTTP method (GET, POST, etc.) */ method: string; /** Request URL path + query, relative to the bin (e.g. "/foo?x=1") */ url: string; /** Sub-path after the bin id ("/" if the request hit the bin root) */ path: string; /** Parsed query string parameters */ query: Record; /** Request headers */ headers: Record; /** Client IP address as reported by Fastify */ remoteAddress: string; /** Content-Type header value, if any */ contentType?: string; /** Original body length in bytes */ bodySize: number; /** Body payload as utf8 text, base64-encoded bytes, or null when empty */ body: string | null; /** Encoding used for the `body` field */ bodyEncoding: "utf8" | "base64" | "none"; /** True if the body was longer than the configured `maxBodySize` */ truncated: boolean; /** ISO timestamp of when the request was captured */ capturedAt: string; }; /** * Metadata for a bin (without its captured requests). */ type Bin = { /** Unique short identifier for the bin */ id: string; /** ISO timestamp of bin creation */ createdAt: string; /** ISO timestamp at which the bin expires */ expiresAt: string; /** Number of requests currently stored in the bin */ requestCount: number; }; /** * One bin and its captured requests, stored as a single Keyv value. * `tokenHash` is the SHA-256 hex digest of the owner token. * The store does not keep the raw token. */ type BinDocument = { bin: Bin; tokenHash?: string; requests: CapturedRequest[]; }; /** * Options for a {@link MockHttpBins} instance. */ type MockHttpBinsOptions = { /** * Keyv store for bins. The default is `new Keyv()`, which keeps data in memory. * Pass an instance when you want a different Keyv adapter. */ keyv?: Keyv; /** Bin lifetime in milliseconds. The default is 24 hours. */ defaultTtlMs?: number; /** Maximum number of requests in one bin. The default is 100. */ maxRequestsPerBin?: number; /** Maximum captured body size in bytes. The default is 128 KiB. */ maxBodySize?: number; /** Length of a generated bin id or request id. The default is 12. */ idLength?: number; }; /** * Stores request bins in Keyv. * The default store is `new Keyv()`, which keeps data in memory. */ export declare class MockHttpBins { private readonly _keyv; private readonly _defaultTtlMs; private readonly _maxRequestsPerBin; private readonly _maxBodySize; private readonly _idLength; constructor(options?: MockHttpBinsOptions); /** Keyv instance that stores the bins. */ get keyv(): Keyv; /** Maximum captured body size in bytes. */ get maxBodySize(): number; /** Maximum number of requests in one bin. */ get maxRequestsPerBin(): number; /** Default bin lifetime in milliseconds. */ get defaultTtlMs(): number; /** * Create a bin and an owner token. * The method returns the token once. The store keeps only the SHA-256 hash. * Throws when Keyv does not store the bin. */ createBin(): Promise; /** * Store a bin when the id is free. * Return undefined when the id is already in use. */ private tryStore; /** * Try each id in a short space. * Throw only when every id is already in use. */ private createByScan; /** * Return the bin when the owner token matches. * A missing bin and a wrong token both fail. * The result does not say which one occurred. */ authorizeOwner(id: string, token: string): Promise<{ ok: true; bin: Bin; } | { ok: false; }>; /** * Look up a bin by id. * Returns `undefined` when the bin does not exist or Keyv has expired it. * A failed read also returns `undefined` when the Keyv instance has an `error` listener. */ getBin(id: string): Promise; /** * List the bins that Keyv still holds. * Throws when the Keyv store has no iterator. * When the Keyv instance has an `error` listener, a failed walk returns the bins read before the error. */ listBins(): Promise; /** * List the bins that match this owner token. * The method returns no other bins. * Throws when the Keyv store has no iterator. */ listBinsForToken(token: string): Promise; /** * Delete a bin. Returns true when the bin existed. * The delete waits for captures already queued for that bin, so a capture cannot write the bin back. */ deleteBin(id: string): Promise; /** * Record a request for a bin. * Returns `undefined` when the bin does not exist. * Throws when Keyv does not store the capture. */ recordRequest(binId: string, raw: Omit): Promise; /** * Read captured requests when the token matches the current document. * Return undefined when the bin is missing or the token does not match. */ readOwnedRequests(id: string, token: string): Promise; /** * Read one capture when the token matches the current document. * `ok: false` means the bin is missing or the token does not match. */ readOwnedRequest(id: string, token: string, reqId: string): Promise<{ ok: false; } | { ok: true; request: CapturedRequest | undefined; }>; /** * Clear captures when the token matches the current document. * The check and the write share one lock, so a replacement bin is not cleared. */ clearOwnedRequests(id: string, token: string): Promise; /** * Delete a bin when the token matches the current document. * The check and the delete share one lock, so a replacement bin stays. */ deleteOwnedBin(id: string, token: string): Promise; /** List captured requests for a bin, newest first. */ getRequests(binId: string): Promise; /** Look up one captured request. */ getRequest(binId: string, reqId: string): Promise; /** * Remove captured requests and keep the bin. * Returns false when the bin does not exist. * Throws when Keyv does not store the change. */ clearRequests(binId: string): Promise; /** Return the current document when the owner token matches. */ private ownedDocument; /** Keyv 6 yields nothing when the store has no iterator. Listing must fail instead. */ private canIterate; /** Throw when the Keyv store has no iterator. */ private requireIterator; /** Returns false when the bin does not exist. */ private appendRequest; /** * Write a bin document with a TTL from its lifetime. * Keyv returns false or throws when the write fails. Both cases throw here. */ private save; /** * Run writes for one bin in order. * Instances that share one Keyv share this lock. * A failed write does not block the next write for that bin. */ private enqueue; /** Keyv keeps a key without a TTL forever, so the TTL never drops below 1 ms. */ private ttlFor; private binKey; private generateId; } /** * Configuration for the injected response */ type InjectionResponse = { /** * The response body (can be string, object, or buffer) */ response: string | Record | Buffer; /** * HTTP status code for the response * @default 200 */ statusCode?: number; /** * Response headers */ headers?: Record; }; /** * Criteria for matching requests to inject responses */ type InjectionMatcher = { /** * URL path to match (supports wildcards with *) * @example "/api/users" - exact match * @example "/api/*" - wildcard match */ url?: string; /** * Hostname to match * @example "localhost" * @example "api.example.com" */ hostname?: string; /** * HTTP method to match * @example "GET" * @example "POST" */ method?: string; /** * Request headers to match (all specified headers must match) */ headers?: Record; }; /** * Function that returns an injection response */ type InjectionResponseFunction = (request: FastifyRequest) => InjectionResponse; /** * A tap represents an active injection that can be removed later */ type InjectionTap = { /** * Unique identifier for this injection */ id: string; /** * The response configuration or a function that returns it */ response: InjectionResponse | InjectionResponseFunction; /** * The request matcher configuration */ matcher?: InjectionMatcher; }; /** * Manages HTTP response injections for testing and mocking */ declare class TapManager { private _injections; constructor(); /** * Get all active injection taps */ get injections(): Map; /** * Check if there are any active injections */ get hasInjections(): boolean; /** * Inject a custom response for requests matching the given criteria * @param response - The response configuration or a function that returns it * @param matcher - Optional criteria to match requests * @returns A tap object that can be used to remove the injection */ inject(response: InjectionResponse | InjectionResponseFunction, matcher?: InjectionMatcher): InjectionTap; /** * Remove an injection by its tap object or ID * @param tapOrId - The tap object or tap ID to remove * @returns true if the injection was removed, false if it wasn't found */ removeInjection(tapOrId: InjectionTap | string): boolean; /** * Find the first injection that matches the given request * @param request - The Fastify request object * @returns The matching injection tap, or undefined if no match */ matchRequest(request: FastifyRequest): InjectionTap | undefined; /** * Clear all injections */ clear(): void; /** * Check if a request matches the given matcher criteria * @param request - The Fastify request object * @param matcher - The matcher criteria (undefined matches all requests) * @returns true if the request matches */ private requestMatches; /** * Check if a URL matches a pattern (supports wildcards with *) * @param url - The URL to test * @param pattern - The pattern to match against * @returns true if the URL matches the pattern */ private urlMatches; } type HttpBinOptions = { httpMethods?: boolean; redirects?: boolean; requestInspection?: boolean; responseInspection?: boolean; statusCodes?: boolean; responseFormats?: boolean; cookies?: boolean; anything?: boolean; auth?: boolean; images?: boolean; dynamicData?: boolean; bins?: boolean; }; type HttpsOptions = { /** * PEM-encoded certificate string, or file path to a certificate PEM file. */ cert?: string; /** * PEM-encoded private key string, or file path to a private key PEM file. */ key?: string; /** * If true, auto-generate a self-signed certificate. Defaults to true when no cert/key provided. */ autoGenerate?: boolean; /** * Options for auto-generating a self-signed certificate. Only used when auto-generating. */ certificateOptions?: CertificateOptions; }; type MockHttpOptions = { /** * The port to listen on. If not provided, defaults to 3000 and detects the next available port if in use. */ port?: number; /** * The host to listen on. If not provided, defaults to '0.0.0.0'. */ host?: string; /** * Whether to automatically detect the next available port if the provided port is in use. Defaults * to true. */ autoDetectPort?: boolean; /** * Whether to use Helmet for security headers. Defaults to true. */ helmet?: boolean; /** * Whether to serve files from the package `public/` directory (favicon, logos). * Defaults to true. Disable this when those files are served by another layer * such as Cloudflare Workers Assets. */ staticFiles?: boolean; /** * Whether to serve the Docula documentation site and OpenAPI spec. Defaults to true. */ apiDocs?: boolean; /** * Path to the built Docula site (`site/dist`). Defaults to the package's * `site/dist` directory. Explicit paths are resolved from the current working directory. */ siteDistPath?: string; /** * Configure which httpbin-style mock routes to enable. Defaults to all enabled. */ httpBin?: HttpBinOptions; /** * Rate limiting options. Defaults to 1000 requests per minute (localhost excluded). * Set to undefined to disable rate limiting, or provide custom options to configure. */ rateLimit?: boolean | RateLimitPluginOptions; /** * Hookified options. */ hookOptions?: HookifiedOptions; /** * Whether to enable logging. Defaults to true. */ logging?: boolean; /** * Fastify plugin boot timeout in milliseconds. Set to `0` to disable the * timeout (needed on Cloudflare Workers, where avvio timers are unreliable). */ pluginTimeout?: number; /** * HTTPS configuration. Set to true to auto-generate a self-signed certificate, * or provide an object with cert/key strings/paths or auto-generation options. */ https?: boolean | HttpsOptions; /** * Whether to enable HTTP/2 support. When used with `https`, enables h2 (HTTP/2 over TLS). * When used without `https`, enables h2c (HTTP/2 cleartext). * Defaults to false. */ http2?: boolean; /** * Whether to allow HTTP/1.1 fallback when using HTTP/2 with HTTPS (ALPN negotiation). * Only applies when both `http2` and `https` are enabled. * Defaults to true. */ http1?: boolean; }; declare class MockHttp extends Hookified { private _port; private _host; private _autoDetectPort; private _helmet; private _staticFiles; private _apiDocs; private _siteDistPath; private _logging; private _pluginTimeout?; private _httpBin; private _rateLimit?; private _http2; private _http1; private _https; private _httpsCredentials; private _server; private _taps; private _bins; private _binHealthCheck?; constructor(options?: MockHttpOptions); /** * The port to listen on. If not provided, defaults to 3000 and detects the next available port if in use. * @default 3000 */ get port(): number; /** * The port to listen on. If not provided, defaults to 3000 and detects the next available port if in use. * @default 3000 */ set port(port: number); /** * The host to listen on. If not provided, defaults to 'localhost'. * @default 'localhost' */ get host(): string; /** * The host to listen on. If not provided, defaults to 'localhost'. * @default 'localhost' */ set host(host: string); /** * Whether to automatically detect the next available port if the provided port is in use. Defaults to true. * @default true */ get autoDetectPort(): boolean; /** * Whether to automatically detect the next available port if the provided port is in use. Defaults to true. * @default true */ set autoDetectPort(autoDetectPort: boolean); /** * Whether to use Helmet for security headers. Defaults to true. * @default true */ get helmet(): boolean; /** * Whether to use Helmet for security headers. Defaults to true. * @default true */ set helmet(helmet: boolean); /** * Whether to serve files from the package `public/` directory. Defaults to true. * @default true */ get staticFiles(): boolean; /** * Whether to serve files from the package `public/` directory. Defaults to true. * @default true */ set staticFiles(staticFiles: boolean); /** * Whether to serve the Docula documentation site and OpenAPI spec. Defaults to true. * @default true */ get apiDocs(): boolean; /** * Whether to serve the Docula documentation site and OpenAPI spec. Defaults to true. * @default true */ set apiDocs(apiDocs: boolean); /** * Path to the built Docula site served when `apiDocs` is enabled. * @default the package `site/dist` directory */ get siteDistPath(): string; /** * Path to the built Docula site served when `apiDocs` is enabled. * @default the package `site/dist` directory */ set siteDistPath(siteDistPath: string); /** * Whether to enable logging. Defaults to true. * @default true */ get logging(): boolean; /** * Whether to enable logging. Defaults to true. * @default true */ set logging(logging: boolean); /** * Fastify plugin boot timeout in milliseconds. `undefined` uses Fastify's default. */ get pluginTimeout(): number | undefined; /** * Fastify plugin boot timeout in milliseconds. `undefined` uses Fastify's default. */ set pluginTimeout(pluginTimeout: number | undefined); /** * HTTPS configuration. Set to true to auto-generate a self-signed certificate, * or provide an HttpsOptions object with cert/key or auto-generation options. */ get https(): HttpsOptions | undefined; /** * HTTPS configuration. Set to true to auto-generate a self-signed certificate, * or provide an HttpsOptions object with cert/key or auto-generation options. */ set https(value: boolean | HttpsOptions | undefined); /** * Whether the server is running in HTTPS mode. */ get isHttps(): boolean; /** * Whether HTTP/2 support is enabled. * @default false */ get http2(): boolean; /** * Whether HTTP/2 support is enabled. * @default false */ set http2(http2: boolean); /** * Whether to allow HTTP/1.1 fallback when using HTTP/2 with HTTPS. * @default true */ get http1(): boolean; /** * Whether to allow HTTP/1.1 fallback when using HTTP/2 with HTTPS. * @default true */ set http1(http1: boolean); /** * HTTP Bin options. Defaults to all enabled. */ get httpBin(): HttpBinOptions; /** * HTTP Bin options. Defaults to all enabled. */ set httpBin(httpBinary: HttpBinOptions); /** * Rate limiting options. Defaults to 1000 requests per minute (localhost excluded). * Set to undefined to disable rate limiting, or provide custom options to configure. * @default { max: 1000, timeWindow: "1 minute", allowList: ["127.0.0.1", "::1"] } */ get rateLimit(): RateLimitPluginOptions | undefined; /** * Rate limiting options. Defaults to 1000 requests per minute (localhost excluded). * Set to undefined to disable rate limiting, or provide custom options to configure. * * Note: Changing this property requires restarting the server (close() then start()) for changes to take effect. * @default { max: 1000, timeWindow: "1 minute", allowList: ["127.0.0.1", "::1"] } */ set rateLimit(rateLimit: RateLimitPluginOptions | undefined); /** * The Fastify server instance. */ get server(): FastifyInstance; /** * The Fastify server instance. */ set server(server: FastifyInstance); /** * The TapManager instance for managing injection taps. */ get taps(): TapManager; /** * The TapManager instance for managing injection taps. */ set taps(taps: TapManager); /** * The MockHttpBins instance for request bins. */ get bins(): MockHttpBins; /** * The MockHttpBins instance for request bins. */ set bins(bins: MockHttpBins); /** * Override the bin storage probe used by `GET /healthz`. * The default probe reads the in-memory Keyv. */ set binHealthCheck(check: () => Promise); /** Whether bin storage can serve a read or a MongoDB ping. */ checkBinStore(): Promise; /** * Register plugins and routes without listening. Use `inject()` against * `server`, or call `start()` to bind a port. */ initialize(): Promise; /** * Start the Fastify server. If the server is already running, it will be closed and restarted. */ start(): Promise; /** * Close the Fastify server. */ close(): Promise; /** * Detect the next available port to run on. * @returns The port that is available to run on */ detectPort(): Promise; /** * Register OpenAPI generation and the Docula documentation site. * @param fastifyInstance - the server instance to register the routes on. */ registerApiDocs(fastifyInstance?: FastifyInstance): Promise; /** * Register `@fastify/swagger` and the live `/openapi.json` spec route. * @param fastifyInstance - the server instance to register the routes on. */ registerSwagger(fastifyInstance?: FastifyInstance): Promise; /** * Serve the built Docula site from `siteDistPath` when the directory exists. * @param fastifyInstance - the server instance to register the routes on. */ registerSite(fastifyInstance?: FastifyInstance): Promise; /** * Register the HTTP methods routes. * @param fastifyInstance - the server instance to register the routes on. */ registerHttpMethods(fastifyInstance?: FastifyInstance): Promise; /** * Register the status code routes. * @param fastifyInstance - the server instance to register the routes on. */ registerStatusCodeRoutes(fastifyInstance?: FastifyInstance): Promise; /** * Register the request inspection routes. * @param fastifyInstance - the server instance to register the routes on. */ registerRequestInspectionRoutes(fastifyInstance?: FastifyInstance): Promise; /** * Register the response inspection routes. * @param fastifyInstance - the server instance to register the routes on. */ registerResponseInspectionRoutes(fastifyInstance?: FastifyInstance): Promise; registerResponseFormatRoutes(fastifyInstance?: FastifyInstance): Promise; /** * Register the redirect routes. * @param fastifyInstance - the server instance to register the routes on. */ registerRedirectRoutes(fastifyInstance?: FastifyInstance): Promise; /** * Register the cookie routes. * @param fastifyInstance - the server instance to register the routes on. */ registerCookieRoutes(fastifyInstance?: FastifyInstance): Promise; /** * Register the anything routes. * @param fastifyInstance - the server instance to register the routes on. */ registerAnythingRoutes(fastifyInstance?: FastifyInstance): Promise; /** * Register the auth routes. * @param fastifyInstance - the server instance to register the routes on. */ registerAuthRoutes(fastifyInstance?: FastifyInstance): Promise; /** * Register the image routes. * @param fastifyInstance - the server instance to register the routes on. */ registerImageRoutes(fastifyInstance?: FastifyInstance): Promise; /** * Register the dynamic data routes. * @param fastifyInstance - the server instance to register the routes on. */ registerDynamicDataRoutes(fastifyInstance?: FastifyInstance): Promise; /** * Register the request bin routes (management at /bins and capture at /b/:id). * @param fastifyInstance - the server instance to register the routes on. */ registerBinRoutes(fastifyInstance?: FastifyInstance): Promise; private resolveHttpsCredentials; private loadPemValue; } export declare const start: () => Promise; export { type Bin, type CapturedRequest, type CertificateFileOptions, type CertificateOptions, type CertificateResult, type HttpsOptions, type InjectionMatcher, type InjectionResponse, type InjectionTap, type MockHttpBinsOptions, MockHttp as default, MockHttp as mockhttp };