@re-auth/http-adapters
Version:
HTTP protocol adapters for ReAuth - framework-agnostic integration with Express, Fastify, and Hono
256 lines (253 loc) • 8.08 kB
text/typescript
import { Token, ReAuthEngine, AuthOutput } from '@re-auth/reauth';
import { ReAuthJWTPayload } from '@re-auth/reauth/services';
import { CookiePrefixOptions } from 'hono/utils/cookie';
interface HttpAdapterConfig {
engine: ReAuthEngine;
basePath?: string;
cors?: CorsConfig;
rateLimit?: RateLimitConfig;
security?: SecurityConfig;
validation?: ValidationConfig;
cookie?: {
name: string;
refreshTokenName?: string;
options: {
httpOnly?: boolean;
secure?: boolean;
sameSite?: 'lax' | 'strict' | 'none';
path?: string;
domain?: string;
maxAge?: number;
expires?: Date;
partitioned?: boolean;
prefix?: CookiePrefixOptions;
priority?: 'low' | 'medium' | 'high';
};
refreshOptions?: {
httpOnly?: boolean;
secure?: boolean;
sameSite?: 'lax' | 'strict' | 'none';
path?: string;
domain?: string;
maxAge?: number;
expires?: Date;
partitioned?: boolean;
prefix?: CookiePrefixOptions;
priority?: 'low' | 'medium' | 'high';
};
};
headerToken?: {
accesssTokenHeader: string;
refreshTokenHeader?: string;
};
}
interface CorsConfig {
origin?: string | string[] | boolean | ((origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) => void);
credentials?: boolean;
allowedHeaders?: string[];
exposedHeaders?: string[];
methods?: string[];
preflightContinue?: boolean;
optionsSuccessStatus?: number;
}
interface RateLimitConfig {
windowMs?: number;
max?: number;
message?: string;
standardHeaders?: boolean;
legacyHeaders?: boolean;
skipSuccessfulRequests?: boolean;
skipFailedRequests?: boolean;
keyGenerator?: (request: any) => string;
}
interface SecurityConfig {
helmet?: boolean | HelmetConfig;
csrf?: boolean | CsrfConfig;
sanitizeInput?: boolean;
sanitizeOutput?: boolean;
}
interface HelmetConfig {
contentSecurityPolicy?: boolean | object;
crossOriginEmbedderPolicy?: boolean;
crossOriginOpenerPolicy?: boolean;
crossOriginResourcePolicy?: boolean;
dnsPrefetchControl?: boolean;
frameguard?: boolean | object;
hidePoweredBy?: boolean;
hsts?: boolean | object;
ieNoOpen?: boolean;
noSniff?: boolean;
originAgentCluster?: boolean;
permittedCrossDomainPolicies?: boolean;
referrerPolicy?: boolean | object;
xssFilter?: boolean;
}
interface CsrfConfig {
secret?: string;
cookie?: boolean | object;
sessionKey?: string;
value?: (req: any) => string;
}
interface ValidationConfig {
validateInput?: boolean;
validateOutput?: boolean;
maxPayloadSize?: number;
allowedFields?: string[];
sanitizeFields?: string[];
}
interface HttpRequest {
method: string;
url: string;
path: string;
query: Record<string, any>;
params: Record<string, string>;
body: any;
headers: Record<string, string>;
cookies?: Record<string, string>;
ip?: string;
userAgent?: string;
user?: AuthenticatedUser | null;
}
interface AuthenticatedUser {
/** The authenticated subject from the session */
subject: any;
/** The session token */
token: Token;
/** Whether the session is valid */
valid: boolean;
/** Session metadata */
metadata?: {
payload?: ReAuthJWTPayload;
type?: 'jwt' | 'legacy' | undefined;
[key: string]: any;
};
}
interface HttpResponse {
status(code: number): this;
json(data: any): this;
send(data: any): this;
header(name: string, value: string): this;
cookie(name: string, value: string, options?: any): this;
clearCookie(name: string, options?: any): this;
}
interface FrameworkAdapter<TRequest = any, TResponse = any, TNext = any> {
name: string;
createMiddleware(): (req: TRequest, res: TResponse, next: TNext) => Promise<void> | void;
createUserMiddleware(): (req: TRequest, res: TResponse, next: TNext) => Promise<void> | void;
extractRequest(req: TRequest): HttpRequest;
sendResponse(res: TResponse, data: any, statusCode?: number): void;
handleError(res: TResponse, error: Error, statusCode?: number): void;
getCurrentUser(req: TRequest): Promise<AuthenticatedUser | null>;
}
interface RouteHandler {
(req: HttpRequest, res: HttpResponse): Promise<any> | any;
}
interface AuthStepRequest extends HttpRequest {
params: Record<string, string>;
plugin: {
name: string;
step: string;
};
}
interface SessionRequest extends HttpRequest {
headers: Record<string, string> & {
authorization?: string;
};
}
interface PluginEndpoint {
pluginName: string;
stepName: string;
path: string;
method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
requiresAuth: boolean;
description?: string;
inputSchema?: any;
outputSchema?: any;
}
interface ApiResponse<T = any> {
success: boolean;
data?: T;
error?: {
code: string;
message: string;
details?: any;
};
meta?: {
timestamp: string;
requestId?: string;
pagination?: {
page: number;
limit: number;
total: number;
};
};
}
interface AuthStepResponse extends ApiResponse<AuthOutput> {
data?: AuthOutput & {
nextStep?: string;
requiresRedirect?: boolean;
sessionToken?: Token;
};
status: number;
/** Redirect URL for OAuth flows */
redirect?: string;
/** Secret data (cookies) to set for OAuth flows */
secret?: Record<string, string>;
}
interface SessionResponse extends ApiResponse {
data?: {
valid: boolean;
subject?: any;
token?: Token;
expiresAt?: string;
metadata?: {
payload?: ReAuthJWTPayload;
type?: 'jwt' | 'legacy' | undefined;
[key: string]: any;
};
};
}
interface PluginListResponse extends ApiResponse {
data?: Array<{
name: string;
description: string;
steps: Array<{
name: string;
description?: string;
method: string;
path: string;
requiresAuth: boolean;
}>;
}>;
}
interface MiddlewareFunction<TRequest = any, TResponse = any, TNext = any> {
(req: TRequest, res: TResponse, next: TNext): Promise<void> | void;
}
interface SecurityMiddleware {
cors(): MiddlewareFunction;
rateLimit(): MiddlewareFunction;
helmet(): MiddlewareFunction;
validation(): MiddlewareFunction;
}
declare class HttpAdapterError extends Error {
statusCode: number;
code: string;
details?: any | undefined;
constructor(message: string, statusCode?: number, code?: string, details?: any | undefined);
}
declare class ValidationError extends HttpAdapterError {
constructor(message: string, details?: any);
}
declare class AuthenticationError extends HttpAdapterError {
constructor(message: string, details?: any);
}
declare class AuthorizationError extends HttpAdapterError {
constructor(message: string, details?: any);
}
declare class NotFoundError extends HttpAdapterError {
constructor(message: string, details?: any);
}
declare class RateLimitError extends HttpAdapterError {
constructor(message: string, details?: any);
}
export { type ApiResponse, type AuthStepRequest, type AuthStepResponse, type AuthenticatedUser, AuthenticationError, AuthorizationError, type CorsConfig, type CsrfConfig, type FrameworkAdapter, type HelmetConfig, type HttpAdapterConfig, HttpAdapterError, type HttpRequest, type HttpResponse, type MiddlewareFunction, NotFoundError, type PluginEndpoint, type PluginListResponse, type RateLimitConfig, RateLimitError, type RouteHandler, type SecurityConfig, type SecurityMiddleware, type SessionRequest, type SessionResponse, type ValidationConfig, ValidationError };