@bsv/auth-express-middleware
Version:
BSV Blockchain mutual-authentication express middleware
115 lines • 5.22 kB
TypeScript
import { Request, Response, NextFunction } from 'express';
import { VerifiableCertificate, Peer, AuthMessage, RequestedCertificateSet, Transport, SessionManager, WalletInterface, PubKeyHex } from '@bsv/sdk';
export interface AuthRequest extends Request {
auth?: {
identityKey: PubKeyHex | 'unknown';
};
}
export interface AuthMiddlewareOptions {
wallet: WalletInterface;
sessionManager?: SessionManager;
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?: 'debug' | 'info' | 'warn' | 'error';
}
/**
* 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>;
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?: 'debug' | 'info' | 'warn' | 'error');
/**
* 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>;
/**
* 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): void;
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