@bsv/auth-express-middleware
Version:
BSV Blockchain mutual-authentication express middleware
164 lines • 6.91 kB
TypeScript
import { Request, Response, NextFunction } from 'express';
import { VerifiableCertificate, Peer, AuthMessage, RequestedCertificateSet, Transport, SessionManager, AsyncSessionManager, WalletInterface, PubKeyHex } from '@bsv/sdk';
import { LogLevel } from './authMiddlewareHelpers.js';
export type { LogLevel } from './authMiddlewareHelpers.js';
export { isLogLevelEnabled, getLogMethod } from './authMiddlewareHelpers.js';
export { writeBodyToWriter } from './authMiddlewareHelpers.js';
export interface AuthRequest extends Request {
auth?: {
identityKey: PubKeyHex;
};
}
export interface AuthMiddlewareOptions {
wallet: WalletInterface;
sessionManager?: SessionManager | AsyncSessionManager;
allowUnauthenticated?: boolean;
certificatesToRequest?: RequestedCertificateSet;
onCertificatesReceived?: (senderPublicKey: string, certs: VerifiableCertificate[], req: AuthRequest, res: Response, next: NextFunction) => void;
/**
* Optional logger (e.g., console). If not provided, logging is disabled.
*/
logger?: typeof console;
/**
* Optional logging level. Defaults to no logging if not provided.
* 'debug' | 'info' | 'warn' | 'error'
*
* - debug: Logs *everything*, including low-level details of the auth process.
* - info: Logs general informational messages about normal operation.
* - warn: Logs potential issues but not necessarily errors.
* - error: Logs only critical issues and errors.
*/
logLevel?: LogLevel;
}
/**
* Transport implementation for Express.
*/
export declare class ExpressTransport implements Transport {
peer?: Peer;
allowAuthenticated: boolean;
openNonGeneralHandles: Record<string, Array<{
res: Response;
next: Function;
}>>;
openGeneralHandles: Record<string, {
next: Function;
res: Response;
}>;
openNextHandlers: Record<string, NextFunction>;
openNextHandlerTimeouts: Record<string, ReturnType<typeof setTimeout>>;
private messageCallback?;
private readonly logger;
private readonly logLevel;
/**
* Constructs a new ExpressTransport instance.
*
* @param {boolean} [allowUnauthenticated=false] - Whether to allow unauthenticated requests passed the auth middleware.
* If `true`, requests without authentication will be permitted, and `req.auth.identityKey`
* will be set to `"unknown"`. If `false`, unauthenticated requests will result in a `401 Unauthorized` response.
* @param {typeof console} [logger] - Logger to use (e.g., console). If omitted, logging is disabled.
* @param {'debug' | 'info' | 'warn' | 'error'} [logLevel] - Log level. If omitted, no logs are output.
*/
constructor(allowUnauthenticated?: boolean, logger?: typeof console, logLevel?: LogLevel);
/**
* Internal logging method, only logs if logger is defined and log level is appropriate.
*
* @param level - The log level for this message
* @param message - The message to log
* @param data - Optional additional data to log
*/
private log;
setPeer(peer: Peer): void;
/**
* Sends an AuthMessage to the connected Peer.
* This method uses an Express response object to deliver the message to the specified Peer.
*
* ### Parameters:
* @param {AuthMessage} message - The authenticated message to send.
*
* ### Returns:
* @returns {Promise<void>} A promise that resolves once the message has been sent successfully.
*/
send(message: AuthMessage): Promise<void>;
/**
* Handles a general (authenticated application) AuthMessage response.
*/
private sendGeneralMessage;
/**
* Reads response headers from a binary reader.
*/
private readResponseHeaders;
/**
* Handles a non-general (handshake) AuthMessage response.
*/
private sendNonGeneralMessage;
/**
* Stores the callback bound by a Peer
* @param callback
*/
onData(callback: (message: AuthMessage) => Promise<void>): Promise<void>;
/**
* Handles an incoming request for the Express server.
*
* This method processes both general and non-general message types,
* manages peer-to-peer certificate handling, and modifies the response object
* to enable custom behaviors like certificate requests and tailored responses.
*
* ### Behavior:
* - For `/.well-known/auth`:
* - Handles non-general messages and listens for certificates.
* - Calls the `onCertificatesReceived` callback (if provided) when certificates are received.
* - For general messages:
* - Sets up a listener for peer-to-peer general messages.
* - Overrides response methods (`send`, `json`, etc.) for custom handling.
* - Returns a 401 error if mutual authentication fails.
*
* ### Parameters:
* @param {AuthRequest} req - The incoming HTTP request.
* @param {Response} res - The HTTP response.
* @param {NextFunction} next - The Express `next` middleware function.
* @param {Function} [onCertificatesReceived] - Optional callback invoked when certificates are received.
*/
handleIncomingRequest(req: AuthRequest, res: Response, next: NextFunction, onCertificatesReceived?: (senderPublicKey: string, certs: VerifiableCertificate[], req: AuthRequest, res: Response, next: NextFunction) => void): Promise<void>;
/**
* Handles a request to /.well-known/auth (non-general / handshake messages).
*/
private handleWellKnownAuth;
/**
* Registers a certificate-received listener for a non-general message.
*/
private registerCertificateListener;
/**
* Processes certificates received from a peer during the handshake.
*/
private handleCertificatesForPeer;
/**
* Handles an authenticated general message (has x-bsv-auth-request-id header).
*/
private handleGeneralMessage;
/**
* Sets up the intercepted response for an authenticated general message.
*/
private setupAuthenticatedResponse;
/**
* Overrides the response methods to intercept and buffer the response for signing.
*/
private hijackResponse;
/**
* Either calls next() immediately or stores it pending certificate arrival.
*/
private scheduleNextOrCertificateWait;
/**
* Handles a request with no auth headers.
*/
private handleUnauthenticated;
private checkRes;
private resetRes;
}
/**
* Creates an Express middleware that handles authentication via BSV-SDK.
*
* @param {AuthMiddlewareOptions} options
* @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware
*/
export declare function createAuthMiddleware(options: AuthMiddlewareOptions): (req: AuthRequest, res: Response, next: NextFunction) => void;
//# sourceMappingURL=index.d.ts.map