blaizejs 0.3.2 → 0.3.3
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/dist/chunk-337RPHG5.js +11 -0
- package/dist/{chunk-HB6MRTGD.js.map → chunk-337RPHG5.js.map} +1 -1
- package/dist/{unsupported-media-type-error-VVHRDTUH.js → chunk-HX7XLEO3.js} +3 -9
- package/dist/{chunk-7IM52S7P.js.map → chunk-HX7XLEO3.js.map} +1 -1
- package/dist/chunk-KE2IOPV4.js +11 -0
- package/dist/{chunk-IFP53BNM.js.map → chunk-KE2IOPV4.js.map} +1 -1
- package/dist/chunk-LY65OJH4.js +11 -0
- package/dist/{chunk-3VK325MM.js.map → chunk-LY65OJH4.js.map} +1 -1
- package/dist/chunk-VM3QGHVO.js +11 -0
- package/dist/{chunk-CQKM74J4.js.map → chunk-VM3QGHVO.js.map} +1 -1
- package/dist/index.cjs +38 -3486
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +38 -3153
- package/dist/index.js.map +1 -1
- package/dist/{validation-error-TXMSFWZL.js → internal-server-error-JHHSKW5B.js} +3 -9
- package/dist/{internal-server-error-PVME2DGN.js → payload-too-large-error-SOQINKUL.js} +3 -9
- package/dist/{payload-too-large-error-QQG7MKGT.js → unsupported-media-type-error-KJMHH5CY.js} +3 -9
- package/dist/validation-error-Q6IOTN4C.js +11 -0
- package/package.json +6 -6
- package/dist/chunk-3VK325MM.js +0 -31
- package/dist/chunk-7IM52S7P.js +0 -31
- package/dist/chunk-CQKM74J4.js +0 -39
- package/dist/chunk-HB6MRTGD.js +0 -39
- package/dist/chunk-IFP53BNM.js +0 -149
- /package/dist/{internal-server-error-PVME2DGN.js.map → internal-server-error-JHHSKW5B.js.map} +0 -0
- /package/dist/{payload-too-large-error-QQG7MKGT.js.map → payload-too-large-error-SOQINKUL.js.map} +0 -0
- /package/dist/{unsupported-media-type-error-VVHRDTUH.js.map → unsupported-media-type-error-KJMHH5CY.js.map} +0 -0
- /package/dist/{validation-error-TXMSFWZL.js.map → validation-error-Q6IOTN4C.js.map} +0 -0
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../blaize-types/src/errors.ts","../src/errors/correlation.ts","../src/errors/internal-server-error.ts","../src/errors/validation-error.ts","../src/errors/payload-too-large-error.ts","../src/errors/unsupported-media-type-error.ts","../src/index.ts","../src/middleware/execute.ts","../src/middleware/compose.ts","../src/middleware/create.ts","../src/plugins/create.ts","../src/router/create.ts","../src/config.ts","../src/router/discovery/parser.ts","../src/server/create.ts","../src/server/start.ts","../src/server/dev-certificate.ts","../src/context/errors.ts","../src/context/store.ts","../src/upload/multipart-parser.ts","../src/upload/utils.ts","../src/context/create.ts","../src/errors/not-found-error.ts","../src/errors/boundary.ts","../src/middleware/error-boundary.ts","../src/server/request-handler.ts","../src/server/stop.ts","../src/server/validation.ts","../src/plugins/lifecycle.ts","../src/plugins/errors.ts","../src/plugins/validation.ts","../src/router/discovery/cache.ts","../src/router/discovery/loader.ts","../src/router/discovery/parallel.ts","../src/router/discovery/finder.ts","../src/router/discovery/profiler.ts","../src/router/discovery/watchers.ts","../src/router/validation/schema.ts","../src/router/validation/body.ts","../src/router/validation/params.ts","../src/router/validation/query.ts","../src/router/validation/response.ts","../src/router/handlers/executor.ts","../src/router/matching/params.ts","../src/router/matching/matcher.ts","../src/router/registry/fast-registry.ts","../src/router/utils/matching-helpers.ts","../src/router/router.ts","../../blaize-types/src/index.ts","../src/errors/unauthorized-error.ts","../src/errors/forbidden-error.ts","../src/errors/conflict-error.ts","../src/errors/rate-limit-error.ts","../src/errors/request-timeout-error.ts","../src/errors/unprocessable-entity-error.ts"],"sourcesContent":["/**\n * Error type definitions and interfaces for the BlaizeJS framework\n *\n * This module contains all the type definitions used for error handling\n * across the BlaizeJS framework, including server-side errors, client-side\n * errors, and HTTP response formats.\n */\n\n/**\n * Structure of error responses sent over HTTP\n *\n * This interface defines the JSON format used for all error responses\n * from BlaizeJS servers. It matches the structure returned by BlaizeError.toJSON()\n *\n * @example\n * ```json\n * {\n * \"type\": \"VALIDATION_ERROR\",\n * \"title\": \"Request validation failed\",\n * \"status\": 400,\n * \"correlationId\": \"req_abc123\",\n * \"timestamp\": \"2024-01-15T10:30:00.000Z\",\n * \"details\": {\n * \"fields\": [\"email\", \"password\"]\n * }\n * }\n * ```\n */\nexport interface BlaizeErrorResponse {\n /** Error type from the ErrorType enum */\n type: ErrorType;\n\n /** Human-readable error message */\n title: string;\n\n /** HTTP status code */\n status: number;\n\n /** Correlation ID for request tracing */\n correlationId: string;\n\n /** ISO timestamp when error occurred */\n timestamp: string;\n\n /** Optional error-specific details */\n details?: unknown;\n}\n\n/**\n * Context information for network-related errors\n *\n * Used by client-side error classes to provide additional context\n * about network failures, timeouts, and connection issues.\n */\nexport interface NetworkErrorContext {\n /** The URL that failed */\n url: string;\n\n /** HTTP method being attempted */\n method: string;\n\n /** Correlation ID for tracing */\n correlationId: string;\n\n /** Timeout value if applicable */\n timeout?: number;\n\n /** The original error that caused the network failure */\n originalError: Error;\n\n /** Additional network-specific details */\n networkDetails?: {\n /** Whether this was a connection timeout */\n isTimeout?: boolean;\n\n /** Whether this was a DNS resolution failure */\n isDnsFailure?: boolean;\n\n /** Whether this was a connection refused error */\n isConnectionRefused?: boolean;\n\n /** HTTP status code if received before failure */\n statusCode?: number;\n };\n}\n\n/**\n * Context information for request timeout errors\n *\n * Specialized context for timeout-specific errors with timing information.\n */\nexport interface TimeoutErrorContext {\n /** The URL that timed out */\n url: string;\n\n /** HTTP method being attempted */\n method: string;\n\n /** Correlation ID for tracing */\n correlationId: string;\n\n /** Configured timeout value in milliseconds */\n timeoutMs: number;\n\n /** Actual duration before timeout in milliseconds */\n elapsedMs: number;\n\n /** Type of timeout (request, connection, etc.) */\n timeoutType: 'request' | 'connection' | 'response' | 'idle';\n}\n\n/**\n * Context information for response parsing errors\n *\n * Used when the client receives a response but cannot parse it properly.\n */\nexport interface ParseErrorContext {\n /** The URL that returned unparseable content */\n url: string;\n\n /** HTTP method used */\n method: string;\n\n /** Correlation ID for tracing */\n correlationId: string;\n\n /** HTTP status code received */\n statusCode: number;\n\n /** Content-Type header if available */\n contentType?: string;\n\n /** Expected response format */\n expectedFormat: 'json' | 'text' | 'binary';\n\n /** Sample of the actual response content (truncated for safety) */\n responseSample?: string;\n\n /** The original parsing error */\n originalError: Error;\n}\n\n/**\n * Validation error field details\n *\n * Structure for field-level validation errors with multiple error messages\n * per field.\n */\nexport interface ValidationFieldError {\n /** Field name or path (e.g., \"email\", \"user.profile.name\") */\n field: string;\n\n /** Array of error messages for this field */\n messages: string[];\n\n /** The invalid value that caused the error */\n rejectedValue?: unknown;\n\n /** Expected type or format */\n expectedType?: string;\n}\n\n/**\n * Validation error details structure\n *\n * Used by ValidationError to provide structured information about\n * what fields failed validation and why.\n */\nexport interface ValidationErrorDetails {\n /** Array of field-level errors */\n fields: ValidationFieldError[];\n\n /** Total number of validation errors */\n errorCount: number;\n\n /** The section that failed validation */\n section: 'params' | 'query' | 'body' | 'response';\n\n /** Schema name if available */\n schemaName?: string;\n}\n\n/**\n * All available error types in the BlaizeJS framework\n *\n * This enum provides both compile-time type safety and runtime values\n * for error type identification across server and client packages.\n *\n * @example Type-safe error handling:\n * ```typescript\n * function handleError(errorType: ErrorType) {\n * switch (errorType) {\n * case ErrorType.VALIDATION_ERROR:\n * // Handle validation error\n * break;\n * case ErrorType.NOT_FOUND:\n * // Handle not found error\n * break;\n * // TypeScript ensures all cases are covered\n * }\n * }\n * ```\n */\nexport enum ErrorType {\n // Server-side business logic errors\n /** Request validation failed (400) */\n VALIDATION_ERROR = 'VALIDATION_ERROR',\n\n /** Resource not found (404) */\n NOT_FOUND = 'NOT_FOUND',\n\n /** Authentication required (401) */\n UNAUTHORIZED = 'UNAUTHORIZED',\n\n /** Access forbidden (403) */\n FORBIDDEN = 'FORBIDDEN',\n\n /** Resource conflict (409) */\n CONFLICT = 'CONFLICT',\n\n /** Rate limit exceeded (429) */\n RATE_LIMITED = 'RATE_LIMITED',\n\n /** Internal server error (500) */\n INTERNAL_SERVER_ERROR = 'INTERNAL_SERVER_ERROR',\n\n /** File/Request Too Large (413) */\n PAYLOAD_TOO_LARGE = 'PAYLOAD_TOO_LARGE',\n\n /** Wrong Content Type (415) */\n UNSUPPORTED_MEDIA_TYPE = 'UNSUPPORTED_MEDIA_TYPE',\n\n /** Upload Timeout (408) */\n UPLOAD_TIMEOUT = 'UPLOAD_TIMEOUT',\n\n /** Valid Format Invalid Semantics (422) */\n UNPROCESSABLE_ENTITY = 'UNPROCESSABLE_ENTITY',\n\n // Client-side errors\n /** Network connectivity failure (0) */\n NETWORK_ERROR = 'NETWORK_ERROR',\n\n /** Request or response timeout (0) */\n TIMEOUT_ERROR = 'TIMEOUT_ERROR',\n\n /** Response parsing failure (0) */\n PARSE_ERROR = 'PARSE_ERROR',\n\n /** Generic HTTP error (varies) */\n HTTP_ERROR = 'HTTP_ERROR',\n}\n\n/**\n * Error severity levels for logging and monitoring\n *\n * Provides a way to categorize errors by their impact and urgency.\n */\nexport enum ErrorSeverity {\n /** Low impact, often user errors */\n LOW = 'low',\n\n /** Medium impact, application errors */\n MEDIUM = 'medium',\n\n /** High impact, system errors */\n HIGH = 'high',\n\n /** Critical impact, service disruption */\n CRITICAL = 'critical',\n}\n\n/**\n * Abstract base class for all BlaizeJS errors\n *\n * This class provides the foundation for all error types in the BlaizeJS framework.\n * It extends JavaScript's built-in Error class and adds framework-specific properties\n * for consistent error handling across server and client.\n *\n * @example\n * ```typescript\n * import { ErrorType } from './types';\n *\n * class NotFoundError extends BlaizeError<{ resourceId: string }> {\n * constructor(message = 'Resource not found', details?: { resourceId: string }) {\n * super(ErrorType.NOT_FOUND, message, 404, getCurrentCorrelationId(), details);\n * }\n * }\n * ```\n *\n * @template TDetails - Type for error-specific details object\n */\nexport abstract class BlaizeError<TDetails = unknown> extends Error {\n /**\n * Error type identifier from the ErrorType enum\n * Used for programmatic error handling and client-side error routing\n */\n readonly type: ErrorType;\n\n /**\n * Human-readable error title/message\n * Should be descriptive enough for debugging but safe for end users\n */\n readonly title: string;\n\n /**\n * HTTP status code associated with this error\n * Used by the error boundary to set appropriate response status\n */\n readonly status: number;\n\n /**\n * Correlation ID for request tracing\n * Links this error to the specific request that generated it\n */\n readonly correlationId: string;\n\n /**\n * Timestamp when the error occurred\n * Useful for debugging and log correlation\n */\n readonly timestamp: Date;\n\n /**\n * Additional error-specific details\n * Type-safe error context that varies by error type\n */\n readonly details?: TDetails | undefined;\n\n /**\n * Creates a new BlaizeError instance\n *\n * @param type - Error type from the ErrorType enum\n * @param title - Human-readable error message\n * @param status - HTTP status code\n * @param correlationId - Request correlation ID for tracing\n * @param details - Optional error-specific details\n */\n protected constructor(\n type: ErrorType,\n title: string,\n status: number,\n correlationId: string,\n details?: TDetails | undefined\n ) {\n super(title);\n\n // Set the error name to the class name for better stack traces\n this.name = this.constructor.name;\n\n // Framework-specific properties\n this.type = type;\n this.title = title;\n this.status = status;\n this.correlationId = correlationId;\n this.timestamp = new Date();\n this.details = details;\n\n // Maintain proper prototype chain for instanceof checks\n Object.setPrototypeOf(this, new.target.prototype);\n\n // Capture stack trace if available (V8 feature)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /**\n * Serializes the error to a plain object suitable for HTTP responses\n *\n * @returns Object representation of the error\n */\n toJSON() {\n const base = {\n type: this.type,\n title: this.title,\n status: this.status,\n correlationId: this.correlationId,\n timestamp: this.timestamp.toISOString(),\n };\n\n // Only include details if they are not undefined\n if (this.details !== undefined) {\n return { ...base, details: this.details };\n }\n\n return base;\n }\n\n /**\n * Returns a string representation of the error\n * Includes correlation ID for easier debugging\n */\n toString(): string {\n return `${this.name}: ${this.title} [${this.correlationId}]`;\n }\n}\n\n/**\n * Interface for payload too large error details\n */\nexport interface PayloadTooLargeErrorDetails {\n fileCount?: number;\n maxFiles?: number;\n filename?: string;\n field?: string;\n contentType?: string;\n currentSize?: number;\n maxSize?: number;\n}\n\n/**\n * Interface for unsupported media type error details\n */\nexport interface UnsupportedMediaTypeErrorDetails {\n receivedMimeType?: string;\n allowedMimeTypes?: string[];\n filename?: string;\n}\n\n/**\n * Interface for authentication error details\n */\nexport interface UnauthorizedErrorDetails {\n /** Reason for authentication failure */\n reason?:\n | 'missing_token'\n | 'invalid_token'\n | 'expired_token'\n | 'malformed_token'\n | 'insufficient_scope'\n | string;\n\n /** Authentication scheme (Bearer, Basic, etc.) */\n authScheme?: string;\n\n /** Authentication realm */\n realm?: string;\n\n /** Detailed error description */\n error_description?: string;\n\n /** Required scopes or permissions */\n requiredScopes?: string[];\n\n /** Login URL for interactive authentication */\n loginUrl?: string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for authorization/permission error details\n */\nexport interface ForbiddenErrorDetails {\n /** Required permission or role */\n requiredPermission?: string;\n\n /** User's current permissions */\n userPermissions?: string[];\n\n /** Resource being accessed */\n resource?: string;\n\n /** Action being attempted */\n action?: string;\n\n /** Reason for access denial */\n reason?: 'insufficient_permissions' | 'account_suspended' | 'resource_locked' | string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for resource conflict error details\n */\nexport interface ConflictErrorDetails {\n /** Type of conflict */\n conflictType?:\n | 'duplicate_key'\n | 'version_mismatch'\n | 'concurrent_modification'\n | 'business_rule'\n | string;\n\n /** Field that caused the conflict */\n field?: string;\n\n /** Existing value that conflicts */\n existingValue?: unknown;\n\n /** Provided value that conflicts */\n providedValue?: unknown;\n\n /** Resource that has the conflicting value */\n conflictingResource?: string;\n\n /** Current version/etag of the resource */\n currentVersion?: string;\n\n /** Expected version/etag */\n expectedVersion?: string;\n\n /** Suggested resolution */\n resolution?: string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for rate limiting error details\n */\nexport interface RateLimitErrorDetails {\n /** Maximum requests allowed in the time window */\n limit?: number;\n\n /** Remaining requests in current window */\n remaining?: number;\n\n /** When the rate limit resets */\n resetTime?: Date;\n\n /** Seconds until the rate limit resets */\n retryAfter?: number;\n\n /** Time window for the rate limit */\n window?: string;\n\n /** Identifier used for rate limiting (IP, user ID, etc.) */\n identifier?: string;\n\n /** Type of rate limit hit */\n limitType?: 'global' | 'per_user' | 'per_ip' | 'per_endpoint' | string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for internal server error details\n */\nexport interface InternalServerErrorDetails {\n /** Original error message (for debugging) */\n originalError?: string;\n\n /** Stack trace (for debugging) */\n stackTrace?: string;\n\n /** Component where the error occurred */\n component?: string;\n\n /** Operation being performed */\n operation?: string;\n\n /** Internal error code */\n internalErrorCode?: string;\n\n /** When the error occurred */\n timestamp?: Date;\n\n /** Whether this error should be retryable */\n retryable?: boolean;\n\n /** Additional debugging context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for NotFound error details\n * Provides context about the missing resource\n */\nexport interface NotFoundErrorDetails {\n /** Type of resource that was not found */\n resourceType?: string;\n\n /** ID or identifier of the resource */\n resourceId?: string;\n\n /** Collection or table where the resource was searched */\n collection?: string;\n\n /** Search criteria that was used */\n query?: Record<string, unknown>;\n\n /** Search criteria that was used (for backward compatibility) */\n searchCriteria?: Record<string, unknown>;\n\n /** The path that was attempted */\n path?: string;\n\n /** HTTP method used (for API endpoints) */\n method?: string;\n\n /** The path that was attempted (for backward compatibility) */\n attemptedPath?: string;\n\n /** Parent resource information for nested resources */\n parentResource?: {\n type: string;\n id: string;\n };\n\n /** Helpful suggestion for the user */\n suggestion?: string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n// TODO: This can potentiall be removed\n/**\n * Interface for body parsing errors stored in context state\n */\nexport interface BodyParseError {\n /**\n * Type of parsing error that occurred\n */\n readonly type:\n | 'json_parse_error'\n | 'form_parse_error'\n | 'multipart_parse_error'\n | 'body_read_error';\n\n /**\n * Human-readable error message\n */\n readonly message: string;\n\n /**\n * Original error object or details\n */\n readonly error: unknown;\n}\n\n/**\n * Type guard to check if an object is a BodyParseError\n */\nexport function isBodyParseError(error: unknown): error is BodyParseError {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'type' in error &&\n 'message' in error &&\n 'error' in error &&\n typeof (error as any).type === 'string' &&\n typeof (error as any).message === 'string'\n );\n}\n\n/**\n * Context information for error transformation\n */\nexport interface ErrorTransformContext {\n url: string;\n method: string;\n correlationId: string;\n timeoutMs?: number;\n elapsedMs?: number;\n statusCode?: number;\n contentType?: string;\n responseSample?: string;\n [key: string]: unknown;\n}\n","/**\n * Correlation ID system for request tracing across async operations\n *\n * This module provides utilities for generating, storing, and accessing\n * correlation IDs that follow requests through the entire application stack.\n * Uses AsyncLocalStorage for automatic context propagation.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\n/**\n * AsyncLocalStorage instance for storing correlation IDs\n * Separate from the main context storage to allow independent lifecycle management\n */\nconst correlationStorage = new AsyncLocalStorage<string>();\n\n/**\n * Generates a new unique correlation ID\n *\n * Format: req_[timestamp_base36]_[random_base36]\n * Example: req_k3x2m1_9z8y7w6v\n *\n * @returns A unique correlation ID string\n */\nexport function generateCorrelationId(): string {\n const timestamp = Date.now().toString(36); // Base36 encoded timestamp\n const random = Math.random().toString(36).substr(2, 9); // Base36 random string\n return `req_${timestamp}_${random}`;\n}\n\n/**\n * Gets the current correlation ID from AsyncLocalStorage\n *\n * @returns The current correlation ID, or 'unknown' if none is set\n */\nexport function getCurrentCorrelationId(): string {\n const stored = correlationStorage.getStore();\n return stored && stored.trim() ? stored : 'unknown';\n}\n\n/**\n * Sets the correlation ID in the current AsyncLocalStorage context\n *\n * This will affect the current execution context and any subsequent\n * async operations that inherit from it.\n *\n * @param correlationId - The correlation ID to set\n */\nexport function setCorrelationId(correlationId: string): void {\n correlationStorage.enterWith(correlationId);\n}\n\n/**\n * Runs a function with a specific correlation ID\n *\n * Creates a new AsyncLocalStorage context with the provided correlation ID.\n * The correlation ID will be available to the function and any async operations\n * it spawns, but will not affect the parent context.\n *\n * @param correlationId - The correlation ID to use for this context\n * @param fn - The function to run with the correlation ID\n * @returns The result of the function\n *\n * @example\n * ```typescript\n * const result = await withCorrelationId('req_123', async () => {\n * console.log(getCurrentCorrelationId()); // 'req_123'\n * return await processRequest();\n * });\n * ```\n */\nexport function withCorrelationId<T>(\n correlationId: string,\n fn: () => T | Promise<T>\n): T | Promise<T> {\n return correlationStorage.run(correlationId, fn);\n}\n\n/**\n * Extracts correlation ID from headers or generates a new one\n *\n * Looks for the 'x-correlation-id' header and uses it if present.\n * If not found, empty, or undefined, generates a new correlation ID.\n *\n * @param headers - HTTP headers object\n * @returns A correlation ID (either from headers or newly generated)\n *\n * @example\n * ```typescript\n * // From incoming request headers\n * const correlationId = getOrGenerateCorrelationId(request.headers);\n *\n * // Use in request processing\n * await withCorrelationId(correlationId, async () => {\n * // Process request with correlation tracking\n * });\n * ```\n */\nexport function getOrGenerateCorrelationId(headers: Record<string, string | undefined>): string {\n const headerCorrelationId = headers['x-correlation-id'];\n\n // Use header value if it exists and is not empty\n if (headerCorrelationId && headerCorrelationId.trim()) {\n return headerCorrelationId;\n }\n\n // Generate new correlation ID if header is missing or empty\n return generateCorrelationId();\n}\n\n/**\n * Creates a middleware function for setting correlation ID from request headers\n *\n * This is a utility for integrating correlation ID handling into the middleware stack.\n * It extracts or generates a correlation ID and sets it for the request processing.\n *\n * @returns Middleware function that sets correlation ID\n *\n * @example\n * ```typescript\n * import { createServer } from 'blaizejs';\n * import { createCorrelationMiddleware } from './correlation';\n *\n * const server = createServer({\n * middleware: [\n * createCorrelationMiddleware(),\n * // ... other middleware\n * ]\n * });\n * ```\n */\nexport function createCorrelationMiddleware() {\n return {\n name: 'correlation',\n execute: async (context: any, next: () => Promise<void>) => {\n // Extract headers from context (adapting to BlaizeJS context structure)\n const headers = context.request.headers();\n const correlationId = getOrGenerateCorrelationId(headers);\n\n // Set correlation ID and process request\n await withCorrelationId(correlationId, next);\n },\n debug: () => ({ stage: 'correlation-id-setup' }),\n };\n}\n\n/**\n * Type-safe wrapper for functions that need correlation ID context\n *\n * Ensures that a function always has access to a correlation ID,\n * either from the current context or by generating a new one.\n *\n * @param fn - Function that requires correlation ID context\n * @returns Wrapped function that guarantees correlation ID availability\n */\nexport function withEnsuredCorrelation<T extends any[], R>(\n fn: (...args: T) => R | Promise<R>\n): (...args: T) => R | Promise<R> {\n return (...args: T): R | Promise<R> => {\n const currentCorrelationId = getCurrentCorrelationId();\n\n // If we already have a correlation ID, just run the function\n if (currentCorrelationId !== 'unknown') {\n return fn(...args);\n }\n\n // Generate new correlation ID and run function in that context\n const newCorrelationId = generateCorrelationId();\n return withCorrelationId(newCorrelationId, () => fn(...args));\n };\n}\n\n/**\n * Debugging utility to get correlation storage information\n *\n * @internal This is for debugging purposes only\n */\nexport function _getCorrelationStorageInfo() {\n return {\n hasActiveStore: correlationStorage.getStore() !== undefined,\n currentCorrelationId: correlationStorage.getStore() ?? null,\n };\n}\n","/**\n * InternalServerError class for server-side errors\n *\n * This error is thrown for unexpected server-side errors that are not\n * the client's fault. It provides debugging context while protecting\n * sensitive information in production.\n */\n\nimport { BlaizeError, ErrorType } from '@blaize-types/errors';\n\nimport { getCurrentCorrelationId } from './correlation';\n\nimport type { InternalServerErrorDetails } from '@blaize-types/errors';\n/**\n * Error thrown for internal server errors\n *\n * Automatically sets HTTP status to 500 and provides debugging context.\n * Note: In production, sensitive details should be filtered by error boundary.\n *\n * @example Basic usage:\n * ```typescript\n * throw new InternalServerError('Something went wrong');\n * ```\n *\n * @example With debugging details:\n * ```typescript\n * throw new InternalServerError('Database error', {\n * originalError: error.message,\n * component: 'user-service',\n * operation: 'createUser',\n * retryable: true\n * });\n * ```\n *\n * @example Wrapping an existing error:\n * ```typescript\n * try {\n * await database.connect();\n * } catch (error) {\n * throw new InternalServerError('Database connection failed', {\n * originalError: error.message,\n * stackTrace: error.stack,\n * component: 'database',\n * retryable: true\n * });\n * }\n * ```\n */\nexport class InternalServerError extends BlaizeError<InternalServerErrorDetails> {\n /**\n * Creates a new InternalServerError instance\n *\n * @param title - Human-readable error message\n * @param details - Optional debugging context\n * @param correlationId - Optional correlation ID (uses current context if not provided)\n */\n constructor(\n title: string,\n details: InternalServerErrorDetails | undefined = undefined,\n correlationId: string | undefined = undefined\n ) {\n super(\n ErrorType.INTERNAL_SERVER_ERROR,\n title,\n 500, // HTTP 500 Internal Server Error\n correlationId ?? getCurrentCorrelationId(),\n details\n );\n }\n}\n","/**\n * ValidationError class for request validation failures\n *\n * This error is thrown when request validation fails (params, query, body, or response).\n * It provides structured information about which fields failed validation and why.\n */\n\nimport { BlaizeError, ErrorType } from '@blaize-types/errors';\n\nimport { getCurrentCorrelationId } from './correlation';\n\nimport type { ValidationErrorDetails } from '@blaize-types/errors';\n\n/**\n * Error thrown when request validation fails\n *\n * Automatically sets HTTP status to 400 and provides structured\n * validation error information for better client debugging.\n *\n * @example Basic usage:\n * ```typescript\n * throw new ValidationError('Email is required');\n * ```\n *\n * @example With detailed field information:\n * ```typescript\n * throw new ValidationError('Validation failed', {\n * fields: [\n * {\n * field: 'email',\n * messages: ['Email is required', 'Email must be valid'],\n * rejectedValue: '',\n * expectedType: 'string'\n * }\n * ],\n * errorCount: 1,\n * section: 'body'\n * });\n * ```\n */\nexport class ValidationError extends BlaizeError<ValidationErrorDetails> {\n /**\n * Creates a new ValidationError instance\n *\n * @param title - Human-readable error message\n * @param details - Optional structured validation details\n * @param correlationId - Optional correlation ID (uses current context if not provided)\n */\n constructor(\n title: string,\n details: ValidationErrorDetails | undefined = undefined,\n correlationId: string | undefined = undefined\n ) {\n super(\n ErrorType.VALIDATION_ERROR,\n title,\n 400, // HTTP 400 Bad Request\n correlationId ?? getCurrentCorrelationId(),\n details\n );\n }\n}\n","import { getCurrentCorrelationId } from './correlation';\nimport { BlaizeError, ErrorType } from '../../../blaize-types/src/errors';\n\nimport type { PayloadTooLargeErrorDetails } from '@blaize-types/errors';\n\nexport class PayloadTooLargeError extends BlaizeError<PayloadTooLargeErrorDetails> {\n constructor(\n title: string,\n details?: PayloadTooLargeErrorDetails | undefined,\n correlationId?: string\n ) {\n super(\n ErrorType.PAYLOAD_TOO_LARGE,\n title,\n 413,\n correlationId ?? getCurrentCorrelationId(),\n details\n );\n }\n}\n","import { getCurrentCorrelationId } from './correlation';\nimport { BlaizeError, ErrorType } from '../../../blaize-types/src/errors';\n\nexport class UnsupportedMediaTypeError extends BlaizeError {\n constructor(title: string, details?: unknown, correlationId?: string) {\n super(\n ErrorType.UNSUPPORTED_MEDIA_TYPE,\n title,\n 415,\n correlationId ?? getCurrentCorrelationId(),\n details\n );\n }\n}\n","/**\n * BlaizeJS Core\n *\n * A blazing-fast, type-safe Node.js framework with file-based routing,\n * powerful middleware, and end-to-end type safety.\n *\n * @package blaizejs\n */\n\nimport { compose } from './middleware/compose';\nimport { create as createMiddleware } from './middleware/create';\nimport { create as createPlugin } from './plugins/create';\nimport {\n createDeleteRoute,\n createGetRoute,\n createHeadRoute,\n createOptionsRoute,\n createPatchRoute,\n createPostRoute,\n createPutRoute,\n} from './router/create';\nimport { create as createServer } from './server/create';\n\n// TODO: ideally this could be import as an npm package, but for now we use a relative path\n// Explicit imports to avoid using values without importing\nexport * from '../../blaize-types/src/index';\n\n// Re-export everything\n// Server module exports\nexport { createServer };\n\n// Router module exports\nexport {\n createDeleteRoute,\n createGetRoute,\n createHeadRoute,\n createOptionsRoute,\n createPatchRoute,\n createPostRoute,\n createPutRoute,\n};\n\n// Middleware module exports\nexport { createMiddleware, compose };\n\n// Plugins module exports\nexport { createPlugin };\n\n// Version information\nexport const VERSION = '0.1.0';\n\n// Namespaced exports with different names to avoid conflicts\nexport const ServerAPI = { createServer };\nexport const RouterAPI = {\n createDeleteRoute,\n createGetRoute,\n createHeadRoute,\n createOptionsRoute,\n createPatchRoute,\n createPostRoute,\n createPutRoute,\n};\nexport const MiddlewareAPI = { createMiddleware, compose };\nexport const PluginsAPI = { createPlugin };\n\n// Server-side error classes\nexport { ValidationError } from './errors/validation-error';\nexport { NotFoundError } from './errors/not-found-error';\nexport { UnauthorizedError } from './errors/unauthorized-error';\nexport { ForbiddenError } from './errors/forbidden-error';\nexport { ConflictError } from './errors/conflict-error';\nexport { RateLimitError } from './errors/rate-limit-error';\nexport { InternalServerError } from './errors/internal-server-error';\nexport { PayloadTooLargeError } from './errors/payload-too-large-error';\nexport { RequestTimeoutError } from './errors/request-timeout-error';\nexport { UnsupportedMediaTypeError } from './errors/unsupported-media-type-error';\nexport { UnprocessableEntityError } from './errors/unprocessable-entity-error';\n\n// Default export\nconst Blaize = {\n // Core functions\n createServer,\n createMiddleware,\n createPlugin,\n\n // Namespaces (using the non-conflicting names)\n Server: ServerAPI,\n Router: RouterAPI,\n Middleware: MiddlewareAPI,\n Plugins: PluginsAPI,\n\n // Constants\n VERSION,\n};\n\nexport default Blaize;\nexport { Blaize };\n","import type { Context } from '@blaize-types/context';\nimport type { Middleware, NextFunction } from '@blaize-types/middleware';\n\n/**\n * Execute a single middleware, handling both function and object forms\n */\nexport function execute(\n middleware: Middleware | undefined,\n ctx: Context,\n next: NextFunction\n): Promise<void> {\n // Handle undefined middleware (safety check)\n if (!middleware) {\n return Promise.resolve(next());\n }\n\n // Handle middleware with skip function\n if (middleware.skip && middleware.skip(ctx)) {\n return Promise.resolve(next());\n }\n\n try {\n // Execute middleware\n const result = middleware.execute(ctx, next);\n\n // Handle both Promise and non-Promise returns\n if (result instanceof Promise) {\n // Return the promise directly to allow errors to propagate\n return result;\n } else {\n // Only wrap non-Promise returns\n return Promise.resolve(result);\n }\n } catch (error) {\n // Handle synchronous errors\n return Promise.reject(error);\n }\n}\n","import { execute } from './execute';\n\nimport type { Context } from '@blaize-types/context';\nimport type { Middleware, NextFunction, MiddlewareFunction } from '@blaize-types/middleware';\n\n/**\n * Compose multiple middleware functions into a single middleware function\n */\nexport function compose(middlewareStack: Middleware[]): MiddlewareFunction {\n // No middleware? Return a pass-through function\n if (middlewareStack.length === 0) {\n return async (_, next) => {\n await Promise.resolve(next());\n };\n }\n\n // Return a function that executes the middleware stack\n return async function (ctx: Context, finalHandler: NextFunction): Promise<void> {\n // Keep track of which \"next\" functions have been called\n const called = new Set<number>();\n\n // Create dispatch function to process middleware stack\n const dispatch = async (i: number): Promise<void> => {\n // If we've reached the end of the stack, execute the final handler\n if (i >= middlewareStack.length) {\n // Ensure we're returning a Promise regardless of what finalHandler returns\n return Promise.resolve(finalHandler());\n }\n\n // Get current middleware\n const middleware = middlewareStack[i];\n\n // Create a next function that can only be called once\n const nextDispatch = () => {\n if (called.has(i)) {\n throw new Error('next() called multiple times');\n }\n\n // Mark this middleware's next as called\n called.add(i);\n\n // Move to the next middleware\n return dispatch(i + 1);\n };\n\n // Use the executeMiddleware function we defined\n return execute(middleware, ctx, nextDispatch);\n };\n\n // Start middleware chain execution\n return dispatch(0);\n };\n}\n","import type { Middleware, MiddlewareOptions, MiddlewareFunction } from '@blaize-types/middleware';\n\n/**\n * Create a middleware\n */\nexport function create(handlerOrOptions: MiddlewareFunction | MiddlewareOptions): Middleware {\n // If handlerOrOptions is a function, convert it to our middleware object format\n if (typeof handlerOrOptions === 'function') {\n return {\n name: 'anonymous', // Default name for function middleware\n execute: handlerOrOptions,\n debug: false,\n };\n }\n\n // Otherwise, handle it as middleware options\n const { name = 'anonymous', handler, skip, debug = false } = handlerOrOptions;\n\n // Create base middleware object with required properties\n const middleware: Middleware = {\n name,\n execute: handler,\n debug,\n };\n\n if (skip !== undefined) {\n return {\n ...middleware,\n skip,\n };\n }\n\n return middleware;\n}\n","import type { Plugin, PluginFactory, PluginHooks } from '@blaize-types/plugins';\nimport type { Server } from '@blaize-types/server';\n\n/**\n * Create a plugin with the given name, version, and setup function\n */\nexport function create<T = any>(\n name: string,\n version: string,\n setup: (\n app: Server,\n options: T\n ) => void | Partial<PluginHooks> | Promise<void> | Promise<Partial<PluginHooks>>,\n defaultOptions: Partial<T> = {}\n): PluginFactory<T> {\n // Input validation\n if (!name || typeof name !== 'string') {\n throw new Error('Plugin name must be a non-empty string');\n }\n\n if (!version || typeof version !== 'string') {\n throw new Error('Plugin version must be a non-empty string');\n }\n\n if (typeof setup !== 'function') {\n throw new Error('Plugin setup must be a function');\n }\n\n // Return the factory function\n return function pluginFactory(userOptions?: Partial<T>) {\n // Merge default options with user options\n const mergedOptions = { ...defaultOptions, ...userOptions } as T;\n\n // Create the base plugin object\n const plugin: Plugin = {\n name,\n version,\n\n // The register hook calls the user's setup function\n register: async (app: Server) => {\n const result = await setup(app, mergedOptions);\n\n // If setup returns hooks, merge them into this plugin\n if (result && typeof result === 'object') {\n // Now we explicitly assign to our plugin object\n Object.assign(plugin, result);\n }\n },\n };\n\n return plugin;\n };\n}\n","import { fileURLToPath } from 'node:url';\n\nimport { getRoutesDir } from '../config';\nimport { parseRoutePath } from './discovery/parser';\n\nimport type {\n CreateGetRoute,\n CreatePostRoute,\n CreatePutRoute,\n CreateDeleteRoute,\n CreatePatchRoute,\n CreateHeadRoute,\n CreateOptionsRoute,\n} from '@blaize-types/router';\n\n/**\n * Get the file path of the function that called createXRoute\n */\nfunction getCallerFilePath(): string {\n const originalPrepareStackTrace = Error.prepareStackTrace;\n\n try {\n Error.prepareStackTrace = (_, stack) => stack;\n const stack = new Error().stack as unknown as NodeJS.CallSite[];\n\n // Stack: getCallerFilePath -> createXRoute -> route file\n const callerFrame = stack[3];\n if (!callerFrame || typeof callerFrame.getFileName !== 'function') {\n throw new Error('Unable to determine caller file frame');\n }\n const fileName = callerFrame.getFileName();\n\n if (!fileName) {\n throw new Error('Unable to determine caller file name');\n }\n\n if (fileName.startsWith('file://')) {\n return fileURLToPath(fileName);\n }\n\n return fileName;\n } finally {\n Error.prepareStackTrace = originalPrepareStackTrace;\n }\n}\n\n/**\n * Convert caller file path to route path using existing parsing logic\n */\nfunction getRoutePath(): string {\n const callerPath = getCallerFilePath();\n const routesDir = getRoutesDir();\n\n const parsedRoute = parseRoutePath(callerPath, routesDir);\n console.log(`🔎 Parsed route path: ${parsedRoute.routePath} from file: ${callerPath}`);\n\n return parsedRoute.routePath;\n}\n\n/**\n * Create a GET route\n * SIMPLER FIX: Just pass the config through, TypeScript will handle the types\n */\nexport const createGetRoute: CreateGetRoute = config => {\n validateMethodConfig('GET', config);\n\n const path = getRoutePath();\n\n return {\n GET: config as any, // Let TypeScript infer the proper types\n path,\n };\n};\n\n/**\n * Create a POST route\n */\nexport const createPostRoute: CreatePostRoute = config => {\n validateMethodConfig('POST', config);\n\n const path = getRoutePath();\n\n return {\n POST: config as any, // Let TypeScript infer the proper types\n path,\n };\n};\n\n/**\n * Create a PUT route\n */\nexport const createPutRoute: CreatePutRoute = config => {\n validateMethodConfig('PUT', config);\n\n const path = getRoutePath();\n\n return {\n PUT: config as any, // Let TypeScript infer the proper types\n path,\n };\n};\n\n/**\n * Create a DELETE route\n */\nexport const createDeleteRoute: CreateDeleteRoute = config => {\n validateMethodConfig('DELETE', config);\n\n const path = getRoutePath();\n\n return {\n DELETE: config as any, // Let TypeScript infer the proper types\n path,\n };\n};\n\n/**\n * Create a PATCH route\n */\nexport const createPatchRoute: CreatePatchRoute = config => {\n validateMethodConfig('PATCH', config);\n\n const path = getRoutePath();\n\n return {\n PATCH: config as any, // Let TypeScript infer the proper types\n path,\n };\n};\n\n/**\n * Create a HEAD route (same signature as GET - no body)\n */\nexport const createHeadRoute: CreateHeadRoute = config => {\n validateMethodConfig('HEAD', config);\n\n const path = getRoutePath();\n\n return {\n HEAD: config as any, // Let TypeScript infer the proper types\n path,\n };\n};\n\n/**\n * Create an OPTIONS route (same signature as GET - no body)\n */\nexport const createOptionsRoute: CreateOptionsRoute = config => {\n validateMethodConfig('OPTIONS', config);\n\n const path = getRoutePath();\n\n return {\n OPTIONS: config as any, // Let TypeScript infer the proper types\n path,\n };\n};\n\n/**\n * Validate a method configuration\n */\nfunction validateMethodConfig(method: string, config: any): void {\n if (!config.handler || typeof config.handler !== 'function') {\n throw new Error(`Handler for method ${method} must be a function`);\n }\n\n if (config.middleware && !Array.isArray(config.middleware)) {\n throw new Error(`Middleware for method ${method} must be an array`);\n }\n\n // Validate schema if provided\n if (config.schema) {\n validateSchema(method, config.schema);\n }\n\n // Method-specific warnings\n switch (method) {\n case 'GET':\n case 'HEAD':\n case 'DELETE':\n if (config.schema?.body) {\n console.warn(`Warning: ${method} requests typically don't have request bodies`);\n }\n break;\n }\n}\n\n/**\n * Validate schema structure\n */\nfunction validateSchema(method: string, schema: any): void {\n const { params, query, body, response } = schema;\n\n // Basic validation - ensure they look like Zod schemas if provided\n if (params && (!params._def || typeof params.parse !== 'function')) {\n throw new Error(`Params schema for ${method} must be a valid Zod schema`);\n }\n\n if (query && (!query._def || typeof query.parse !== 'function')) {\n throw new Error(`Query schema for ${method} must be a valid Zod schema`);\n }\n\n if (body && (!body._def || typeof body.parse !== 'function')) {\n throw new Error(`Body schema for ${method} must be a valid Zod schema`);\n }\n\n if (response && (!response._def || typeof response.parse !== 'function')) {\n throw new Error(`Response schema for ${method} must be a valid Zod schema`);\n }\n}\n","// config/runtime-config.ts\ninterface RuntimeConfig {\n routesDir?: string;\n basePath?: string;\n // Add other runtime configuration as needed\n}\n\n// Internal state - not exported\nlet config: RuntimeConfig = {};\n\n/**\n * Set runtime configuration\n */\nexport function setRuntimeConfig(newConfig: Partial<RuntimeConfig>): void {\n config = { ...config, ...newConfig };\n}\n\n/**\n * Get full runtime configuration\n */\nexport function getRuntimeConfig(): RuntimeConfig {\n return { ...config };\n}\n\n/**\n * Get the configured routes directory\n */\nexport function getRoutesDir(): string {\n if (!config.routesDir) {\n throw new Error('Routes directory not configured. Make sure server is properly initialized.');\n }\n return config.routesDir;\n}\n\n/**\n * Get the configured base path\n */\nexport function getBasePath(): string {\n return config.basePath || '';\n}\n\n/**\n * Clear configuration (useful for testing)\n */\nexport function clearRuntimeConfig(): void {\n config = {};\n}\n","import * as path from 'node:path';\n\nimport type { ParsedRoute } from '@blaize-types/router';\n\n/**\n * Parse a file path into a route path\n * Works consistently across Windows and Unix-like file systems\n */\nexport function parseRoutePath(filePath: string, basePath: string): ParsedRoute {\n // Clean file:// URLs if present\n if (filePath.startsWith('file://')) {\n filePath = filePath.replace('file://', '');\n }\n if (basePath.startsWith('file://')) {\n basePath = basePath.replace('file://', '');\n }\n\n // Convert all backslashes to forward slashes for consistent handling\n const forwardSlashFilePath = filePath.replace(/\\\\/g, '/');\n const forwardSlashBasePath = basePath.replace(/\\\\/g, '/');\n\n // Ensure the base path ends with a slash for proper prefix removal\n const normalizedBasePath = forwardSlashBasePath.endsWith('/')\n ? forwardSlashBasePath\n : `${forwardSlashBasePath}/`;\n\n // Remove the base path to get the relative path\n let relativePath = forwardSlashFilePath;\n if (forwardSlashFilePath.startsWith(normalizedBasePath)) {\n relativePath = forwardSlashFilePath.substring(normalizedBasePath.length);\n } else if (forwardSlashFilePath.startsWith(forwardSlashBasePath)) {\n relativePath = forwardSlashFilePath.substring(forwardSlashBasePath.length);\n // If base path didn't end with a slash but we still matched, ensure relative path doesn't start with a slash\n if (relativePath.startsWith('/')) {\n relativePath = relativePath.substring(1);\n }\n } else {\n // If base path isn't a prefix of file path, use path.relative as a fallback\n // But convert to forward slashes for consistency\n relativePath = path.relative(forwardSlashBasePath, forwardSlashFilePath).replace(/\\\\/g, '/');\n }\n\n // Remove file extension (anything after the last dot)\n relativePath = relativePath.replace(/\\.[^.]+$/, '');\n\n // Split the path into segments\n const segments = relativePath.split('/').filter(Boolean);\n const params: string[] = [];\n\n // Transform file path segments to route path segments\n const routeSegments = segments.map(segment => {\n // Handle dynamic parameters ([param])\n if (segment.startsWith('[') && segment.endsWith(']')) {\n const paramName = segment.slice(1, -1);\n params.push(paramName);\n return `:${paramName}`;\n }\n return segment;\n });\n\n // Create the final route path\n let routePath = routeSegments.length > 0 ? `/${routeSegments.join('/')}` : '/';\n\n // Handle index routes\n if (routePath.endsWith('/index')) {\n routePath = routePath.slice(0, -6) || '/';\n }\n\n return {\n filePath,\n routePath,\n params,\n };\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport EventEmitter from 'node:events';\n\nimport { setRuntimeConfig } from '../config';\nimport { startServer } from './start';\nimport { registerSignalHandlers, stopServer } from './stop';\nimport { validateServerOptions } from './validation';\nimport { createPluginLifecycleManager } from '../plugins/lifecycle';\nimport { validatePlugin } from '../plugins/validation';\nimport { createRouter } from '../router/router';\n\nimport type { Context } from '@blaize-types/context';\nimport type { Middleware } from '@blaize-types/middleware';\nimport type { Plugin } from '@blaize-types/plugins';\nimport type { Server, ServerOptions, ServerOptionsInput, StopOptions } from '@blaize-types/server';\n\nexport const DEFAULT_OPTIONS: ServerOptions = {\n port: 3000,\n host: 'localhost',\n routesDir: './routes',\n http2: {\n enabled: true,\n },\n middleware: [],\n plugins: [],\n};\n\n/**\n * Creates the configuration options by merging defaults with user-provided options\n */\nfunction createServerOptions(options: ServerOptionsInput = {}): ServerOptions {\n const baseOptions: ServerOptions = { ...DEFAULT_OPTIONS };\n setRuntimeConfig({ routesDir: options.routesDir || baseOptions.routesDir });\n\n return {\n port: options.port ?? baseOptions.port,\n host: options.host ?? baseOptions.host,\n routesDir: options.routesDir ?? baseOptions.routesDir,\n http2: {\n enabled: options.http2?.enabled ?? baseOptions.http2?.enabled,\n keyFile: options.http2?.keyFile ?? baseOptions.http2?.keyFile,\n certFile: options.http2?.certFile ?? baseOptions.http2?.certFile,\n },\n middleware: [...(baseOptions.middleware || []), ...(options.middleware || [])],\n plugins: [...(baseOptions.plugins || []), ...(options.plugins || [])],\n };\n}\n\n/**\n * Creates the server listen method\n */\nfunction createListenMethod(\n serverInstance: Server,\n validatedOptions: ServerOptions,\n initialMiddleware: Middleware[],\n initialPlugins: Plugin[]\n): Server['listen'] {\n return async () => {\n // Initialize middleware and plugins\n await initializeComponents(serverInstance, initialMiddleware, initialPlugins);\n\n // Use the functional manager\n await serverInstance.pluginManager.initializePlugins(serverInstance);\n\n // Start the server\n await startServer(serverInstance, validatedOptions);\n\n await serverInstance.pluginManager.onServerStart(serverInstance, serverInstance.server);\n\n // Setup signal handlers and emit events\n setupServerLifecycle(serverInstance);\n\n return serverInstance;\n };\n}\n\n/**\n * Initializes middleware and plugins\n */\nasync function initializeComponents(\n serverInstance: Server,\n initialMiddleware: Middleware[],\n initialPlugins: Plugin[]\n): Promise<void> {\n // Initialize middleware from options\n for (const mw of initialMiddleware) {\n serverInstance.use(mw);\n }\n\n // Register plugins from options\n for (const p of initialPlugins) {\n await serverInstance.register(p);\n }\n}\n\n/**\n * Sets up server lifecycle (signal handlers, events)\n */\nfunction setupServerLifecycle(serverInstance: Server): void {\n // Register signal handlers for graceful shutdown\n const signalHandlers = registerSignalHandlers(() => serverInstance.close());\n\n // Store handlers to unregister when server closes\n serverInstance._signalHandlers = signalHandlers;\n\n // Emit started event\n serverInstance.events.emit('started');\n}\n\n/**\n * Creates the server close method\n */\nfunction createCloseMethod(serverInstance: Server): Server['close'] {\n return async (stopOptions?: StopOptions) => {\n if (!serverInstance.server) {\n return;\n }\n\n // Prepare options\n const options: StopOptions = { ...stopOptions };\n\n // Unregister signal handlers if they exist\n if (serverInstance._signalHandlers) {\n serverInstance._signalHandlers.unregister();\n delete serverInstance._signalHandlers;\n }\n\n // Call stopServer with the server instance\n await stopServer(serverInstance, options);\n };\n}\n\n/**\n * Creates the server use method for adding middleware\n */\nfunction createUseMethod(serverInstance: Server): Server['use'] {\n return middleware => {\n const middlewareArray = Array.isArray(middleware) ? middleware : [middleware];\n serverInstance.middleware.push(...middlewareArray);\n return serverInstance;\n };\n}\n\n/**\n * Creates the server register method for plugins\n */\nfunction createRegisterMethod(serverInstance: Server): Server['register'] {\n return async plugin => {\n validatePlugin(plugin);\n serverInstance.plugins.push(plugin);\n await plugin.register(serverInstance);\n return serverInstance;\n };\n}\n\n/**\n * Creates a BlaizeJS server instance\n */\nexport function create(options: ServerOptionsInput = {}): Server {\n // Create and validate options\n const mergedOptions = createServerOptions(options);\n\n let validatedOptions: ServerOptions;\n try {\n validatedOptions = validateServerOptions(mergedOptions);\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to create server: ${error.message}`);\n }\n throw new Error(`Failed to create server: ${String(error)}`);\n }\n\n // Extract options and prepare initial components\n const { port, host, middleware, plugins } = validatedOptions;\n // TODO: create registries to manage middleware and plugins\n const initialMiddleware = Array.isArray(middleware) ? [...middleware] : [];\n const initialPlugins = Array.isArray(plugins) ? [...plugins] : [];\n\n // Initialize core server components\n const contextStorage = new AsyncLocalStorage<Context>();\n const router = createRouter({\n routesDir: validatedOptions.routesDir,\n watchMode: process.env.NODE_ENV === 'development',\n });\n // Create plugin lifecycle manager\n const pluginManager = createPluginLifecycleManager({\n debug: process.env.NODE_ENV === 'development',\n continueOnError: true,\n });\n const events = new EventEmitter();\n\n // Create server instance with minimal properties\n const serverInstance: Server = {\n server: null as any,\n port,\n host,\n context: contextStorage,\n events,\n plugins: [],\n middleware: [],\n _signalHandlers: { unregister: () => {} },\n use: () => serverInstance,\n register: async () => serverInstance,\n listen: async () => serverInstance,\n close: async () => {},\n router,\n pluginManager,\n };\n\n // Add methods to the server instance\n serverInstance.listen = createListenMethod(\n serverInstance,\n validatedOptions,\n initialMiddleware,\n initialPlugins\n );\n serverInstance.close = createCloseMethod(serverInstance);\n serverInstance.use = createUseMethod(serverInstance);\n serverInstance.register = createRegisterMethod(serverInstance);\n\n return serverInstance;\n}\n","import * as fs from 'node:fs';\nimport * as http from 'node:http';\nimport * as http2 from 'node:http2';\n\nimport { generateDevCertificates } from './dev-certificate';\nimport { createRequestHandler } from './request-handler';\n\nimport type { Server, Http2Options, ServerOptions } from '@blaize-types/server';\n\n// Extract certificate handling to a separate function\nasync function prepareCertificates(\n http2Options: Http2Options\n): Promise<{ keyFile?: string; certFile?: string }> {\n // Not using HTTP/2? No certificates needed\n if (!http2Options.enabled) {\n return {};\n }\n\n const { keyFile, certFile } = http2Options;\n\n // If certificates are missing and in development, generate them\n const isDevMode = process.env.NODE_ENV === 'development';\n const certificatesMissing = !keyFile || !certFile;\n\n if (certificatesMissing && isDevMode) {\n const devCerts = await generateDevCertificates();\n return devCerts;\n }\n\n // If certificates are still missing, throw error\n if (certificatesMissing) {\n throw new Error(\n 'HTTP/2 requires SSL certificates. Provide keyFile and certFile in http2 options. ' +\n 'In development, set NODE_ENV=development to generate them automatically.'\n );\n }\n\n return { keyFile, certFile };\n}\n\n// Create server based on protocol\nfunction createServerInstance(\n isHttp2: boolean,\n certOptions: { keyFile?: string; certFile?: string }\n): http.Server | http2.Http2SecureServer {\n if (!isHttp2) {\n return http.createServer();\n }\n\n // Create HTTP/2 server options\n const http2ServerOptions: http2.SecureServerOptions = {\n allowHTTP1: true, // Allow fallback to HTTP/1.1\n };\n\n // Read certificate files\n try {\n if (certOptions.keyFile) {\n http2ServerOptions.key = fs.readFileSync(certOptions.keyFile);\n }\n if (certOptions.certFile) {\n http2ServerOptions.cert = fs.readFileSync(certOptions.certFile);\n }\n } catch (err) {\n throw new Error(\n `Failed to read certificate files: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n\n return http2.createSecureServer(http2ServerOptions);\n}\n\n// Start listening on the specified port and host\nfunction listenOnPort(\n server: http.Server | http2.Http2SecureServer,\n port: number,\n host: string,\n isHttp2: boolean\n): Promise<void> {\n return new Promise((resolve, reject) => {\n server.listen(port, host, () => {\n const protocol = isHttp2 ? 'https' : 'http';\n const url = `${protocol}://${host}:${port}`;\n console.log(`\n🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥\n\n ⚡ BlaizeJS DEVELOPMENT SERVER HOT AND READY ⚡\n \n 🚀 Server: ${url}\n 🔥 Hot Reload: Enabled\n 🛠️ Mode: Development\n \n Time to build something amazing! 🚀\n\n🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥\n`);\n resolve();\n });\n\n server.on('error', err => {\n console.error('Server error:', err);\n reject(err);\n });\n });\n}\n\nasync function initializePlugins(serverInstance: Server): Promise<void> {\n for (const plugin of serverInstance.plugins) {\n if (typeof plugin.initialize === 'function') {\n await plugin.initialize(serverInstance);\n }\n }\n}\n\n// Main server start function - now with much lower complexity\nexport async function startServer(\n serverInstance: Server,\n serverOptions: ServerOptions\n): Promise<void> {\n // Server already running? Do nothing.\n if (serverInstance.server) {\n return;\n }\n\n try {\n // Get effective port and host\n const port = serverOptions.port;\n const host = serverOptions.host;\n\n // Initialize all registered plugins\n await initializePlugins(serverInstance);\n\n // Determine if using HTTP/2\n const http2Options = serverOptions.http2 || { enabled: true };\n const isHttp2 = !!http2Options.enabled;\n\n // Prepare certificates if needed\n const certOptions = await prepareCertificates(http2Options);\n\n // Update the server options if we generated certificates\n if (serverOptions.http2 && certOptions.keyFile && certOptions.certFile) {\n serverOptions.http2.keyFile = certOptions.keyFile;\n serverOptions.http2.certFile = certOptions.certFile;\n }\n\n // Create the server instance\n const server = createServerInstance(isHttp2, certOptions);\n\n // Store the server in the instance\n serverInstance.server = server;\n\n // Update server instance properties\n serverInstance.port = port;\n serverInstance.host = host;\n\n // Configure request handling\n const requestHandler = createRequestHandler(serverInstance);\n server.on('request', requestHandler);\n\n // Start listening\n await listenOnPort(server, port, host, isHttp2);\n } catch (error) {\n console.error('Failed to start server:', error);\n throw error;\n }\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport * as selfsigned from 'selfsigned';\n\nexport interface DevCertificates {\n keyFile: string;\n certFile: string;\n}\n\nexport async function generateDevCertificates(): Promise<DevCertificates> {\n const certDir = path.join(process.cwd(), '.blaizejs', 'certs');\n const keyPath = path.join(certDir, 'dev.key');\n const certPath = path.join(certDir, 'dev.cert');\n \n // Check if certificates already exist\n if (fs.existsSync(keyPath) && fs.existsSync(certPath)) {\n return {\n keyFile: keyPath,\n certFile: certPath\n };\n }\n \n // Create directory if it doesn't exist\n if (!fs.existsSync(certDir)) {\n fs.mkdirSync(certDir, { recursive: true });\n }\n \n // Generate self-signed certificate\n const attrs = [{ name: 'commonName', value: 'localhost' }];\n const options = {\n days: 365,\n algorithm: 'sha256',\n keySize: 2048,\n extensions: [\n { name: 'basicConstraints', cA: true },\n {\n name: 'keyUsage',\n keyCertSign: true,\n digitalSignature: true,\n nonRepudiation: true,\n keyEncipherment: true,\n dataEncipherment: true\n },\n {\n name: 'extKeyUsage',\n serverAuth: true,\n clientAuth: true\n },\n {\n name: 'subjectAltName',\n altNames: [\n { type: 2, value: 'localhost' },\n { type: 7, ip: '127.0.0.1' }\n ]\n }\n ]\n };\n \n // Generate the certificates\n const pems = selfsigned.generate(attrs, options);\n \n // Write the key and certificate to files\n fs.writeFileSync(keyPath, Buffer.from(pems.private, 'utf-8'));\n fs.writeFileSync(certPath, Buffer.from(pems.cert, 'utf-8'));\n \n console.log(`\\n🔒 Generated self-signed certificates for development at ${certDir}\\n`);\n \n return {\n keyFile: keyPath,\n certFile: certPath\n };\n}","export class ResponseSentError extends Error {\n constructor(message: string = '❌ Response has already been sent') {\n super(message);\n this.name = 'ResponseSentError';\n }\n}\n\nexport class ResponseSentHeaderError extends ResponseSentError {\n constructor(message: string = 'Cannot set header after response has been sent') {\n super(message);\n }\n}\n\nexport class ResponseSentContentError extends ResponseSentError {\n constructor(message: string = 'Cannot set content type after response has been sent') {\n super(message);\n }\n}\n\nexport class ParseUrlError extends ResponseSentError {\n constructor(message: string = 'Invalide URL') {\n super(message);\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\n\nimport type { Context, QueryParams, State, UnknownFunction } from '@blaize-types/context';\n\n/**\n * AsyncLocalStorage instance for storing request context\n */\nexport const contextStorage = new AsyncLocalStorage<Context>();\n\n/**\n * Returns the current context from AsyncLocalStorage\n */\nexport function getContext<S extends State = State, TBody = unknown, TQuery = QueryParams>():\n | Context<S, TBody, TQuery>\n | undefined {\n return contextStorage.getStore() as Context<S, TBody, TQuery> | undefined;\n}\n\n/**\n * Wraps a callback function with a context\n */\nexport function runWithContext<T>(\n context: Context,\n callback: () => T | Promise<T>\n): T | Promise<T> {\n return contextStorage.run(context, callback);\n}\n\n/**\n * Middleware function that ensures a context is available in AsyncLocalStorage\n */\nexport async function contextMiddleware(\n context: Context,\n next: () => Promise<void>\n): Promise<void> {\n return runWithContext(context, next);\n}\n\n/**\n * Utility to check if code is running within a context\n */\nexport function hasContext(): boolean {\n return contextStorage.getStore() !== undefined;\n}\n\n/**\n * Creates a function that will run with the current context\n *\n * @param fn The function to bind to the current context\n * @returns A function that will execute with the bound context\n */\nexport function bindContext<TFunction extends UnknownFunction>(fn: TFunction): TFunction {\n const context = getContext();\n if (!context) {\n return fn;\n }\n\n // Using function instead of arrow function to preserve 'this'\n return function (this: unknown, ...args: Parameters<TFunction>): ReturnType<TFunction> {\n return runWithContext(context, () => fn.apply(this, args)) as ReturnType<TFunction>;\n } as TFunction;\n}\n","import { randomUUID } from 'node:crypto';\nimport { createWriteStream, type WriteStream } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { Readable } from 'node:stream';\n\nimport { extractBoundary, parseContentDisposition, parseContentType } from './utils';\n\nimport type { UnifiedRequest } from '@blaize-types/context';\nimport type { UploadedFile, MultipartData, ParseOptions, ParserState } from '@blaize-types/upload';\n\n// Default options with sensible defaults\nconst DEFAULT_OPTIONS: Required<ParseOptions> = {\n maxFileSize: 10 * 1024 * 1024, // 10MB\n maxFiles: 10,\n maxFieldSize: 1 * 1024 * 1024, // 1MB\n allowedMimeTypes: [],\n allowedExtensions: [],\n strategy: 'stream',\n tempDir: tmpdir(),\n computeHash: false,\n};\n\n/**\n * Create initial parser state\n */\nfunction createParserState(boundary: string, options: Partial<ParseOptions> = {}): ParserState {\n return {\n boundary: Buffer.from(`--${boundary}`),\n options: { ...DEFAULT_OPTIONS, ...options },\n fields: new Map(),\n files: new Map(),\n buffer: Buffer.alloc(0),\n stage: 'boundary',\n currentHeaders: '',\n currentField: null,\n currentFilename: undefined,\n currentMimetype: 'application/octet-stream',\n currentContentLength: 0,\n fileCount: 0,\n fieldCount: 0,\n currentBufferChunks: [],\n currentStream: null,\n currentTempPath: null,\n currentWriteStream: null,\n streamController: null,\n cleanupTasks: [],\n // Track validation state\n hasFoundValidBoundary: false,\n hasProcessedAnyPart: false,\n isFinished: false,\n };\n}\n\n/**\n * Process a chunk of data through the parser state machine\n */\nasync function processChunk(state: ParserState, chunk: Buffer): Promise<ParserState> {\n const newBuffer = Buffer.concat([state.buffer, chunk]);\n let currentState = { ...state, buffer: newBuffer };\n\n // Process buffer until no more progress can be made\n while (currentState.buffer.length > 0 && !currentState.isFinished) {\n const nextState = await processCurrentStage(currentState);\n if (nextState === currentState) break; // No progress made, need more data\n currentState = nextState;\n }\n\n return currentState;\n}\n\n/**\n * Process current stage of parsing\n */\nasync function processCurrentStage(state: ParserState): Promise<ParserState> {\n switch (state.stage) {\n case 'boundary':\n return processBoundary(state);\n case 'headers':\n return processHeaders(state);\n case 'content':\n return processContent(state);\n default: {\n const { InternalServerError } = await import('../errors/internal-server-error');\n throw new InternalServerError(`Invalid parser stage`, {\n operation: state.stage,\n });\n }\n }\n}\n\n/**\n * Process boundary detection\n */\nfunction processBoundary(state: ParserState): ParserState {\n const boundaryIndex = state.buffer.indexOf(state.boundary);\n if (boundaryIndex === -1) return state;\n\n // Mark that we found at least one boundary\n const hasFoundValidBoundary = true;\n\n // Consume boundary and check for end\n let buffer = state.buffer.subarray(boundaryIndex + state.boundary.length);\n\n // Check for end boundary (-- after boundary)\n if (buffer.length >= 2 && buffer.subarray(0, 2).equals(Buffer.from('--'))) {\n return {\n ...state,\n buffer,\n hasFoundValidBoundary,\n isFinished: true,\n stage: 'boundary',\n };\n }\n\n // Skip CRLF after boundary\n if (buffer.length >= 2 && buffer.subarray(0, 2).equals(Buffer.from('\\r\\n'))) {\n buffer = buffer.subarray(2);\n }\n\n return {\n ...state,\n buffer,\n hasFoundValidBoundary,\n stage: 'headers',\n currentHeaders: '',\n };\n}\n\n/**\n * Process headers section\n */\nasync function processHeaders(state: ParserState): Promise<ParserState> {\n const headerEnd = state.buffer.indexOf('\\r\\n\\r\\n');\n if (headerEnd === -1) return state;\n\n const headers = state.buffer.subarray(0, headerEnd).toString('utf8');\n const buffer = state.buffer.subarray(headerEnd + 4);\n\n const disposition = parseContentDisposition(headers);\n if (!disposition) {\n // ✅ HTTP 400 - Bad Request for malformed headers\n const { ValidationError } = await import('../errors/validation-error');\n throw new ValidationError('Missing or invalid Content-Disposition header');\n }\n\n const mimetype = parseContentType(headers);\n const isFile = disposition.filename !== undefined;\n\n // Validation\n if (isFile && state.fileCount >= state.options.maxFiles) {\n const { PayloadTooLargeError } = await import('../errors/payload-too-large-error');\n throw new PayloadTooLargeError('Too many files in upload', {\n fileCount: state.fileCount + 1,\n maxFiles: state.options.maxFiles,\n filename: disposition.filename,\n });\n }\n\n if (\n isFile &&\n state.options.allowedMimeTypes.length > 0 &&\n !state.options.allowedMimeTypes.includes(mimetype)\n ) {\n const { UnsupportedMediaTypeError } = await import('../errors/unsupported-media-type-error');\n throw new UnsupportedMediaTypeError('File type not allowed', {\n receivedMimeType: mimetype,\n allowedMimeTypes: state.options.allowedMimeTypes,\n filename: disposition.filename,\n });\n }\n\n return {\n ...state,\n buffer,\n stage: 'content',\n currentHeaders: headers,\n currentField: disposition.name,\n currentFilename: disposition.filename,\n currentMimetype: mimetype,\n currentContentLength: 0,\n fileCount: isFile ? state.fileCount + 1 : state.fileCount,\n fieldCount: isFile ? state.fieldCount : state.fieldCount + 1,\n currentBufferChunks: [],\n };\n}\n\n/**\n * Process content section\n */\nasync function processContent(state: ParserState): Promise<ParserState> {\n const nextBoundaryIndex = state.buffer.indexOf(state.boundary);\n\n let contentChunk: Buffer;\n let isComplete = false;\n let buffer = state.buffer;\n\n if (nextBoundaryIndex === -1) {\n // No boundary found, process safely\n const safeLength = Math.max(0, state.buffer.length - state.boundary.length);\n if (safeLength === 0) return state; // Need more data\n\n contentChunk = state.buffer.subarray(0, safeLength);\n buffer = state.buffer.subarray(safeLength);\n } else {\n // Found boundary, process content before it (minus CRLF)\n const contentEnd = Math.max(0, nextBoundaryIndex - 2);\n contentChunk = state.buffer.subarray(0, contentEnd);\n buffer = state.buffer.subarray(nextBoundaryIndex);\n isComplete = true;\n }\n\n let updatedState = { ...state, buffer };\n\n if (contentChunk.length > 0) {\n updatedState = await processContentChunk(updatedState, contentChunk);\n }\n\n if (isComplete) {\n updatedState = await finalizeCurrentPart(updatedState);\n updatedState = {\n ...updatedState,\n stage: 'boundary' as const,\n hasProcessedAnyPart: true, // Mark that we've processed at least one part\n };\n }\n\n return updatedState;\n}\n\n/**\n * Process a chunk of content data\n */\nasync function processContentChunk(state: ParserState, chunk: Buffer): Promise<ParserState> {\n const newContentLength = state.currentContentLength + chunk.length;\n\n // Size validation\n const maxSize =\n state.currentFilename !== undefined ? state.options.maxFileSize : state.options.maxFieldSize;\n\n if (newContentLength > maxSize) {\n const isFile = state.currentFilename !== undefined;\n const { PayloadTooLargeError } = await import('../errors/payload-too-large-error');\n const payloadErrorDetals = state.currentField\n ? {\n contentType: isFile ? 'file' : 'field',\n currentSize: newContentLength,\n maxSize,\n field: state.currentField,\n filename: state.currentFilename,\n }\n : {\n contentType: isFile ? 'file' : 'field',\n currentSize: newContentLength,\n maxSize,\n filename: state.currentFilename,\n };\n throw new PayloadTooLargeError(\n `${isFile ? 'File' : 'Field'} size exceeds limit`,\n payloadErrorDetals\n );\n }\n\n if (state.currentFilename !== undefined) {\n return processFileChunk(state, chunk, newContentLength);\n } else {\n return {\n ...state,\n currentContentLength: newContentLength,\n currentBufferChunks: [...state.currentBufferChunks, chunk],\n };\n }\n}\n\n/**\n * Process file chunk based on strategy\n */\nasync function processFileChunk(\n state: ParserState,\n chunk: Buffer,\n newContentLength: number\n): Promise<ParserState> {\n switch (state.options.strategy) {\n case 'memory':\n return {\n ...state,\n currentContentLength: newContentLength,\n currentBufferChunks: [...state.currentBufferChunks, chunk],\n };\n\n case 'stream':\n if (state.streamController) {\n state.streamController.enqueue(chunk);\n }\n return { ...state, currentContentLength: newContentLength };\n\n case 'temp':\n if (state.currentWriteStream) {\n await writeToStream(state.currentWriteStream, chunk);\n }\n return { ...state, currentContentLength: newContentLength };\n\n default: {\n const { ValidationError } = await import('../errors/validation-error');\n throw new ValidationError(`Invalid parsing strategy`);\n // TODO: create new error type to support \"strategy\" + \"supportedStrategies\"\n // throw new ValidationError(`Invalid parsing strategy`, {\n // strategy: state.options.strategy,\n // supportedStrategies: ['memory', 'stream', 'temp'],\n // });\n }\n }\n}\n\n/**\n * Initialize file processing for current part\n */\nasync function initializeFileProcessing(state: ParserState): Promise<ParserState> {\n if (state.currentFilename === undefined) return state;\n\n switch (state.options.strategy) {\n case 'memory':\n return { ...state, currentBufferChunks: [] };\n\n case 'stream': {\n let streamController: ReadableStreamDefaultController<Uint8Array> | null = null;\n const stream = new ReadableStream<Uint8Array>({\n start: controller => {\n streamController = controller;\n },\n });\n\n return {\n ...state,\n currentStream: stream as any, // Type cast for Node.js compatibility\n streamController,\n };\n }\n\n case 'temp': {\n const tempPath = join(state.options.tempDir, `upload-${randomUUID()}`);\n const writeStream = createWriteStream(tempPath);\n const cleanupTask = async () => {\n try {\n const { unlink } = await import('node:fs/promises');\n await unlink(tempPath);\n } catch (error) {\n console.warn(`Failed to cleanup temp file: ${tempPath}`, error);\n }\n };\n\n return {\n ...state,\n currentTempPath: tempPath,\n currentWriteStream: writeStream,\n cleanupTasks: [...state.cleanupTasks, cleanupTask],\n };\n }\n\n default: {\n const { ValidationError } = await import('../errors/validation-error');\n throw new ValidationError(`Invalid file processing strategy`);\n // throw new ValidationError(`Invalid file processing strategy`, {\n // strategy: state.options.strategy,\n // });\n }\n }\n}\n\n/**\n * Finalize current part and add to collections\n */\nasync function finalizeCurrentPart(state: ParserState): Promise<ParserState> {\n if (!state.currentField) return resetCurrentPart(state);\n\n if (state.currentFilename !== undefined) {\n return finalizeFile(state);\n } else {\n return finalizeField(state);\n }\n}\n\n/**\n * Finalize file processing\n */\nasync function finalizeFile(state: ParserState): Promise<ParserState> {\n if (!state.currentField || state.currentFilename === undefined) {\n return resetCurrentPart(state);\n }\n\n let stream: Readable;\n let buffer: Buffer | undefined;\n let tempPath: string | undefined;\n\n switch (state.options.strategy) {\n case 'memory':\n buffer = Buffer.concat(state.currentBufferChunks);\n stream = Readable.from(buffer);\n break;\n\n case 'stream':\n if (state.streamController) {\n state.streamController.close();\n }\n stream = state.currentStream!;\n break;\n\n case 'temp':\n if (state.currentWriteStream) {\n await closeStream(state.currentWriteStream);\n }\n tempPath = state.currentTempPath!;\n stream = Readable.from(Buffer.alloc(0)); // Placeholder\n break;\n\n default: {\n // ✅ HTTP 400 - Bad Request for invalid strategy\n const { ValidationError } = await import('../errors/validation-error');\n throw new ValidationError(`Invalid file finalization strategy`);\n // throw new ValidationError(`Invalid file finalization strategy`, {\n // strategy: state.options.strategy,\n // });\n }\n }\n\n const file: UploadedFile = {\n filename: state.currentFilename,\n fieldname: state.currentField,\n mimetype: state.currentMimetype,\n size: state.currentContentLength,\n stream,\n buffer,\n tempPath,\n };\n\n const updatedFiles = addToCollection(state.files, state.currentField, file);\n\n return {\n ...resetCurrentPart(state),\n files: updatedFiles,\n };\n}\n\n/**\n * Finalize field processing\n */\nfunction finalizeField(state: ParserState): ParserState {\n if (!state.currentField) return resetCurrentPart(state);\n\n const value = Buffer.concat(state.currentBufferChunks).toString('utf8');\n const updatedFields = addToCollection(state.fields, state.currentField, value);\n\n return {\n ...resetCurrentPart(state),\n fields: updatedFields,\n };\n}\n\n/**\n * Reset current part state\n */\nfunction resetCurrentPart(state: ParserState): ParserState {\n return {\n ...state,\n currentField: null,\n currentFilename: undefined,\n currentContentLength: 0,\n currentBufferChunks: [],\n currentStream: null,\n streamController: null,\n currentTempPath: null,\n currentWriteStream: null,\n };\n}\n\n/**\n * Add item to collection immutably\n */\nfunction addToCollection<T>(collection: Map<string, T[]>, key: string, value: T): Map<string, T[]> {\n const newCollection = new Map(collection);\n const existing = newCollection.get(key) || [];\n newCollection.set(key, [...existing, value]);\n return newCollection;\n}\n\n/**\n * Finalize parsing and return results\n */\nasync function finalize(state: ParserState): Promise<MultipartData> {\n // Validate that we found valid multipart data\n if (!state.hasFoundValidBoundary) {\n const { ValidationError } = await import('../errors/validation-error');\n throw new ValidationError('No valid multipart boundary found');\n // throw new ValidationError('No valid multipart boundary found', {\n // errorType: 'invalid_multipart',\n // reason: 'Missing or malformed boundary markers',\n // });`\n }\n\n // If we found boundaries but didn't process any parts, it's empty/invalid\n if (state.hasFoundValidBoundary && !state.hasProcessedAnyPart) {\n const { ValidationError } = await import('../errors/validation-error');\n throw new ValidationError('Empty multipart request');\n // throw new ValidationError('Empty multipart request', {\n // errorType: 'empty_multipart',\n // reason: 'Valid boundaries found but no data parts processed',\n // });\n }\n\n const fields: Record<string, string | string[]> = {};\n for (const [key, values] of state.fields.entries()) {\n fields[key] = values.length === 1 ? values[0]! : values;\n }\n\n const files: Record<string, UploadedFile | UploadedFile[]> = {};\n for (const [key, fileList] of state.files.entries()) {\n files[key] = fileList.length === 1 ? fileList[0]! : fileList;\n }\n\n return { fields, files };\n}\n\n/**\n * Cleanup resources\n */\nasync function cleanup(state: ParserState): Promise<void> {\n // Execute all cleanup tasks\n await Promise.allSettled(state.cleanupTasks.map(task => task()));\n\n // Close any open streams\n if (state.streamController) {\n state.streamController.close();\n }\n\n if (state.currentWriteStream) {\n await closeStream(state.currentWriteStream);\n }\n}\n\n// Helper functions\nasync function writeToStream(stream: WriteStream, chunk: Buffer): Promise<void> {\n return new Promise((resolve, reject) => {\n stream.write(chunk, error => {\n if (error) reject(error);\n else resolve();\n });\n });\n}\n\nasync function closeStream(stream: WriteStream): Promise<void> {\n return new Promise(resolve => {\n stream.end(() => resolve());\n });\n}\n\n/**\n * Main parsing function (functional interface)\n */\nexport async function parseMultipartRequest(\n request: UnifiedRequest,\n options: Partial<ParseOptions> = {}\n): Promise<MultipartData> {\n const contentType = (request.headers['content-type'] as string) || '';\n const boundary = extractBoundary(contentType);\n\n if (!boundary) {\n const { UnsupportedMediaTypeError } = await import('../errors/unsupported-media-type-error');\n throw new UnsupportedMediaTypeError('Missing boundary in multipart content-type', {\n receivedContentType: contentType,\n expectedFormat: 'multipart/form-data; boundary=...',\n });\n }\n\n let state = createParserState(boundary, options);\n\n // Initialize file processing if needed\n if (state.currentFilename !== undefined) {\n state = await initializeFileProcessing(state);\n }\n\n try {\n // Process request stream\n for await (const chunk of request) {\n state = await processChunk(state, chunk as Buffer);\n }\n\n return finalize(state);\n } finally {\n await cleanup(state);\n }\n}\n","// Hoisted regex patterns\nconst BOUNDARY_REGEX = /boundary=([^;]+)/i;\nconst CONTENT_DISPOSITION_REGEX =\n /Content-Disposition:\\s*form-data;\\s*name=\"([^\"]+)\"(?:;[\\s\\r\\n]*filename=\"([^\"]*)\")?/i;\nconst CONTENT_TYPE_REGEX = /Content-Type:\\s*([^\\r\\n]+)/i;\nconst MULTIPART_REGEX = /multipart\\/form-data/i;\n\n/**\n * Extract boundary from Content-Type header\n */\nexport function extractBoundary(contentType: string): string | null {\n const match = contentType.match(BOUNDARY_REGEX);\n if (!match || !match[1]) return null;\n\n let boundary = match[1].trim();\n if (boundary.startsWith('\"') && boundary.endsWith('\"')) {\n boundary = boundary.slice(1, -1);\n }\n\n return boundary || null;\n}\n\n/**\n * Parse Content-Disposition header\n */\nexport function parseContentDisposition(\n headers: string\n): { name: string; filename?: string } | null {\n const match = headers.match(CONTENT_DISPOSITION_REGEX);\n if (!match || !match[1]) return null;\n\n return {\n name: match[1],\n filename: match[2] !== undefined ? match[2] : undefined,\n };\n}\n\n/**\n * Parse Content-Type header\n */\nexport function parseContentType(headers: string): string {\n const match = headers.match(CONTENT_TYPE_REGEX);\n return match && match[1]?.trim() ? match[1].trim() : 'application/octet-stream';\n}\n\n/**\n * Check if content type is multipart\n */\nexport function isMultipartContent(contentType: string): boolean {\n return MULTIPART_REGEX.test(contentType);\n}\n","import {\n ParseUrlError,\n ResponseSentContentError,\n ResponseSentError,\n ResponseSentHeaderError,\n} from './errors';\nimport { hasContext, getContext } from './store';\nimport { parseMultipartRequest } from '../upload/multipart-parser';\nimport { isMultipartContent } from '../upload/utils';\n\nimport type {\n Context,\n ContextOptions,\n MultipartLimits,\n QueryParams,\n RequestParams,\n State,\n StreamOptions,\n UnifiedRequest,\n UnifiedResponse,\n} from '@blaize-types/context';\nimport type { BodyParseError } from '@blaize-types/errors';\n\nconst CONTENT_TYPE_HEADER = 'Content-Type';\n\nconst DEFAULT_BODY_LIMITS = {\n json: 512 * 1024, // 512KB - Most APIs should be much smaller\n form: 1024 * 1024, // 1MB - Reasonable for form submissions\n text: 5 * 1024 * 1024, // 5MB - Documents, logs, code files\n multipart: {\n maxFileSize: 50 * 1024 * 1024, // 50MB per file\n maxTotalSize: 100 * 1024 * 1024, // 100MB total request\n maxFiles: 10,\n maxFieldSize: 1024 * 1024, // 1MB for form fields\n },\n raw: 10 * 1024 * 1024, // 10MB for unknown content types\n};\n\n/**\n * Parse URL and extract path and query parameters using modern URL API\n */\nfunction parseRequestUrl(req: UnifiedRequest): {\n path: string;\n url: URL | null;\n query: QueryParams;\n} {\n const originalUrl = (req as any).url || '/';\n\n // Construct full URL for parsing\n const host = req.headers.host || 'localhost';\n const protocol = req.socket && (req.socket as any).encrypted ? 'https' : 'http';\n const fullUrl = `${protocol}://${host}${originalUrl.startsWith('/') ? '' : '/'}${originalUrl}`;\n try {\n const url = new URL(fullUrl);\n\n // Extract path\n const path = url.pathname;\n\n // Parse query parameters using URLSearchParams\n const query: QueryParams = {};\n url.searchParams.forEach((value, key) => {\n // Handle array parameters (key=value1&key=value2)\n if (query[key] !== undefined) {\n if (Array.isArray(query[key])) {\n (query[key] as string[]).push(value);\n } else {\n query[key] = [query[key] as string, value];\n }\n } else {\n query[key] = value;\n }\n });\n\n return { path, url, query };\n } catch (error) {\n // Fallback for invalid URLs\n console.warn(`Invalid URL: ${fullUrl}`, error);\n throw new ParseUrlError(`Invalid URL: ${fullUrl}`);\n }\n}\n\n/**\n * Determine if the request is using HTTP/2\n */\nfunction isHttp2Request(req: UnifiedRequest): boolean {\n // Check for HTTP/2 specific properties\n return 'stream' in req || ('httpVersionMajor' in req && (req as any).httpVersionMajor === 2);\n}\n\n/**\n * Get the HTTP protocol (http or https)\n */\nfunction getProtocol(req: UnifiedRequest): string {\n // Check for encrypted socket\n const encrypted = req.socket && (req.socket as any).encrypted;\n // Check for X-Forwarded-Proto header (common in proxy environments)\n const forwardedProto = req.headers['x-forwarded-proto'];\n\n if (forwardedProto) {\n if (Array.isArray(forwardedProto)) {\n // Handle array of header values (uncommon but possible)\n return forwardedProto[0]?.split(',')[0]?.trim() || 'http';\n } else {\n // Handle string header value (typical case)\n return forwardedProto.split(',')[0]?.trim() || 'http';\n }\n }\n\n // Default protocol based on socket encryption\n return encrypted ? 'https' : 'http';\n}\n\n/**\n * Create a new context object for a request/response cycle\n */\nexport async function createContext<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n res: UnifiedResponse,\n options: ContextOptions = {}\n): Promise<Context<State, TBody, TQuery>> {\n // Extract basic request information\n const { path, url, query } = parseRequestUrl(req);\n const method = req.method || 'GET';\n const isHttp2 = isHttp2Request(req);\n const protocol = getProtocol(req);\n\n // Initialize state\n const params: RequestParams = {};\n const state = { ...(options.initialState || {}) };\n\n // Track response status\n const responseState = { sent: false };\n\n // Create the context object with its components\n const ctx: Context<State, TBody, TQuery> = {\n request: createRequestObject<TBody, TQuery>(req, {\n path,\n url,\n query: query as TQuery,\n params,\n method,\n isHttp2,\n protocol,\n }),\n response: {} as Context<State, TBody, TQuery>['response'],\n state,\n };\n\n ctx.response = createResponseObject(res, responseState, ctx);\n\n // Parse body if requested\n if (options.parseBody) {\n await parseBodyIfNeeded(req, ctx, options);\n }\n\n return ctx;\n}\n\n/**\n * Create the request object portion of the context\n */\nfunction createRequestObject<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n info: {\n path: string;\n url: URL | null;\n query: TQuery;\n params: RequestParams;\n method: string;\n isHttp2: boolean;\n protocol: string;\n }\n): Context<State, TBody, TQuery>['request'] {\n return {\n raw: req,\n ...info,\n header: createRequestHeaderGetter(req),\n headers: createRequestHeadersGetter(req),\n body: undefined as unknown as TBody,\n };\n}\n\n/**\n * Create a function to get a single request header\n */\nfunction createRequestHeaderGetter(req: UnifiedRequest) {\n return (name: string): string | undefined => {\n const value = req.headers[name.toLowerCase()];\n if (Array.isArray(value)) {\n return value.join(', ');\n }\n return value || undefined;\n };\n}\n\n/**\n * Create a function to get multiple request headers\n */\nfunction createRequestHeadersGetter(req: UnifiedRequest) {\n const headerGetter = createRequestHeaderGetter(req);\n\n return (names?: string[]): Record<string, string | undefined> => {\n if (names && Array.isArray(names) && names.length > 0) {\n return names.reduce<Record<string, string | undefined>>((acc, name) => {\n acc[name] = headerGetter(name);\n return acc;\n }, {});\n } else {\n return Object.entries(req.headers).reduce<Record<string, string | undefined>>(\n (acc, [key, value]) => {\n acc[key] = Array.isArray(value) ? value.join(', ') : value || undefined;\n return acc;\n },\n {}\n );\n }\n };\n}\n\n/**\n * Create the response object portion of the context\n */\nfunction createResponseObject<S extends State = State, TBody = unknown, TQuery = QueryParams>(\n res: UnifiedResponse,\n responseState: { sent: boolean },\n ctx: Context<S, TBody, TQuery>\n): Context<S, TBody, TQuery>['response'] {\n return {\n raw: res,\n\n get sent() {\n return responseState.sent;\n },\n\n status: createStatusSetter(res, responseState, ctx),\n header: createHeaderSetter(res, responseState, ctx),\n headers: createHeadersSetter(res, responseState, ctx),\n type: createContentTypeSetter(res, responseState, ctx),\n\n json: createJsonResponder(res, responseState),\n text: createTextResponder(res, responseState),\n html: createHtmlResponder(res, responseState),\n redirect: createRedirectResponder(res, responseState),\n stream: createStreamResponder(res, responseState),\n };\n}\n\n/**\n * Create a function to set response status\n */\nfunction createStatusSetter<S extends State = State, TBody = unknown, TQuery = QueryParams>(\n res: UnifiedResponse,\n responseState: { sent: boolean },\n ctx: Context<S, TBody, TQuery>\n) {\n return function statusSetter(code: number): Context['response'] {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n res.statusCode = code;\n return ctx.response;\n };\n}\n\n/**\n * Create a function to set a response header\n */\nfunction createHeaderSetter<S extends State = State, TBody = unknown, TQuery = QueryParams>(\n res: UnifiedResponse,\n responseState: { sent: boolean },\n ctx: Context<S, TBody, TQuery>\n) {\n return function headerSetter(name: string, value: string) {\n if (responseState.sent) {\n throw new ResponseSentHeaderError();\n }\n res.setHeader(name, value);\n return ctx.response;\n };\n}\n\n/**\n * Create a function to set multiple response headers\n */\nfunction createHeadersSetter<S extends State = State, TBody = unknown, TQuery = QueryParams>(\n res: UnifiedResponse,\n responseState: { sent: boolean },\n ctx: Context<S, TBody, TQuery>\n) {\n return function headersSetter(headers: Record<string, string>) {\n if (responseState.sent) {\n throw new ResponseSentHeaderError();\n }\n for (const [name, value] of Object.entries(headers)) {\n res.setHeader(name, value);\n }\n return ctx.response;\n };\n}\n\n/**\n * Create a function to set content type header\n */\nfunction createContentTypeSetter<S extends State = State, TBody = unknown, TQuery = QueryParams>(\n res: UnifiedResponse,\n responseState: { sent: boolean },\n ctx: Context<S, TBody, TQuery>\n) {\n return function typeSetter(type: string) {\n if (responseState.sent) {\n throw new ResponseSentContentError();\n }\n res.setHeader(CONTENT_TYPE_HEADER, type);\n return ctx.response;\n };\n}\n\n/**\n * Create a function to send JSON response\n */\nfunction createJsonResponder(res: UnifiedResponse, responseState: { sent: boolean }) {\n return function jsonResponder(body: unknown, status?: number) {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n\n if (status !== undefined) {\n res.statusCode = status;\n }\n\n res.setHeader(CONTENT_TYPE_HEADER, 'application/json');\n res.end(JSON.stringify(body));\n responseState.sent = true;\n };\n}\n\n/**\n * Create a function to send text response\n */\nfunction createTextResponder(res: UnifiedResponse, responseState: { sent: boolean }) {\n return function textResponder(body: string, status?: number) {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n\n if (status !== undefined) {\n res.statusCode = status;\n }\n\n res.setHeader(CONTENT_TYPE_HEADER, 'text/plain');\n res.end(body);\n responseState.sent = true;\n };\n}\n\n/**\n * Create a function to send HTML response\n */\nfunction createHtmlResponder(res: UnifiedResponse, responseState: { sent: boolean }) {\n return function htmlResponder(body: string, status?: number) {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n\n if (status !== undefined) {\n res.statusCode = status;\n }\n\n res.setHeader(CONTENT_TYPE_HEADER, 'text/html');\n res.end(body);\n responseState.sent = true;\n };\n}\n\n/**\n * Create a function to send redirect response\n */\nfunction createRedirectResponder(res: UnifiedResponse, responseState: { sent: boolean }) {\n return function redirectResponder(url: string, status = 302) {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n\n res.statusCode = status;\n res.setHeader('Location', url);\n res.end();\n responseState.sent = true;\n };\n}\n\n/**\n * Create a function to stream response\n */\nfunction createStreamResponder(res: UnifiedResponse, responseState: { sent: boolean }) {\n return function streamResponder(readable: NodeJS.ReadableStream, options: StreamOptions = {}) {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n\n if (options.status !== undefined) {\n res.statusCode = options.status;\n }\n\n if (options.contentType) {\n res.setHeader(CONTENT_TYPE_HEADER, options.contentType);\n }\n\n if (options.headers) {\n for (const [name, value] of Object.entries(options.headers)) {\n res.setHeader(name, value);\n }\n }\n\n // Handle streaming\n readable.pipe(res);\n\n // Mark as sent when the stream ends\n readable.on('end', () => {\n responseState.sent = true;\n });\n\n // Handle errors\n readable.on('error', err => {\n console.error('Stream error:', err);\n if (!responseState.sent) {\n res.statusCode = 500;\n res.end('Stream error');\n responseState.sent = true;\n }\n });\n };\n}\n\n/**\n * Parse request body if enabled in options\n */\nasync function parseBodyIfNeeded<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n ctx: Context<State, TBody, TQuery>,\n options: ContextOptions = {}\n): Promise<void> {\n // Skip parsing for methods that typically don't have bodies\n if (shouldSkipParsing(req.method)) {\n return;\n }\n\n const contentType = req.headers['content-type'] || '';\n const contentLength = parseInt(req.headers['content-length'] || '0', 10);\n\n // Skip if no content\n if (contentLength === 0) {\n return;\n }\n\n const limits = {\n json: options.bodyLimits?.json ?? DEFAULT_BODY_LIMITS.json,\n form: options.bodyLimits?.form ?? DEFAULT_BODY_LIMITS.form,\n text: options.bodyLimits?.text ?? DEFAULT_BODY_LIMITS.text,\n raw: options.bodyLimits?.raw ?? DEFAULT_BODY_LIMITS.raw,\n multipart: {\n maxFileSize:\n options.bodyLimits?.multipart?.maxFileSize ?? DEFAULT_BODY_LIMITS.multipart.maxFileSize,\n maxFiles: options.bodyLimits?.multipart?.maxFiles ?? DEFAULT_BODY_LIMITS.multipart.maxFiles,\n maxFieldSize:\n options.bodyLimits?.multipart?.maxFieldSize ?? DEFAULT_BODY_LIMITS.multipart.maxFieldSize,\n maxTotalSize:\n options.bodyLimits?.multipart?.maxTotalSize ?? DEFAULT_BODY_LIMITS.multipart.maxTotalSize,\n },\n };\n\n try {\n // Apply content-type specific size validation\n if (contentType.includes('application/json')) {\n if (contentLength > limits.json) {\n throw new Error(`JSON body too large: ${contentLength} > ${limits.json} bytes`);\n }\n await parseJsonBody(req, ctx);\n } else if (contentType.includes('application/x-www-form-urlencoded')) {\n if (contentLength > limits.form) {\n throw new Error(`Form body too large: ${contentLength} > ${limits.form} bytes`);\n }\n await parseFormUrlEncodedBody(req, ctx);\n } else if (contentType.includes('text/')) {\n if (contentLength > limits.text) {\n throw new Error(`Text body too large: ${contentLength} > ${limits.text} bytes`);\n }\n await parseTextBody(req, ctx);\n } else if (isMultipartContent(contentType)) {\n // Multipart has its own sophisticated size validation\n await parseMultipartBody(req, ctx, limits.multipart);\n } else {\n // Unknown content type - apply raw limit\n if (contentLength > limits.raw) {\n throw new Error(`Request body too large: ${contentLength} > ${limits.raw} bytes`);\n }\n // Don't parse unknown content types, but allow them through\n return;\n }\n } catch (error) {\n const errorType = contentType.includes('multipart')\n ? 'multipart_parse_error'\n : 'body_read_error';\n setBodyError(ctx, errorType, 'Error reading request body', error);\n }\n}\n\n/**\n * Determine if body parsing should be skipped based on HTTP method\n */\nfunction shouldSkipParsing(method?: string): boolean {\n const skipMethods = ['GET', 'HEAD', 'OPTIONS'];\n return skipMethods.includes(method || 'GET');\n}\n\n/**\n * Parse JSON request body\n */\nasync function parseJsonBody<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n ctx: Context<State, TBody, TQuery>\n): Promise<void> {\n const body = await readRequestBody(req);\n\n if (!body) {\n console.warn('Empty body, skipping JSON parsing');\n return;\n }\n\n // Check if the body is actually \"null\" string\n if (body.trim() === 'null') {\n console.warn('Body is the string \"null\"');\n ctx.request.body = null as TBody;\n return;\n }\n\n try {\n const json = JSON.parse(body);\n ctx.request.body = json as TBody;\n } catch (error) {\n ctx.request.body = null as TBody;\n setBodyError(ctx, 'json_parse_error', 'Invalid JSON in request body', error);\n }\n}\n\n/**\n * Parse URL-encoded form data\n */\nasync function parseFormUrlEncodedBody<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n ctx: Context<State, TBody, TQuery>\n): Promise<void> {\n const body = await readRequestBody(req);\n if (!body) return;\n\n try {\n ctx.request.body = parseUrlEncodedData(body) as TBody;\n } catch (error) {\n ctx.request.body = null as TBody;\n setBodyError(ctx, 'form_parse_error', 'Invalid form data in request body', error);\n }\n}\n\n/**\n * Parse URL-encoded data into an object\n */\nfunction parseUrlEncodedData(body: string): Record<string, string | string[]> {\n const params = new URLSearchParams(body);\n const formData: Record<string, string | string[]> = {};\n\n params.forEach((value, key) => {\n if (formData[key] !== undefined) {\n if (Array.isArray(formData[key])) {\n (formData[key] as string[]).push(value);\n } else {\n formData[key] = [formData[key] as string, value];\n }\n } else {\n formData[key] = value;\n }\n });\n\n return formData;\n}\n\n/**\n * Parse plain text body\n */\nasync function parseTextBody<TBody = null, TQuery = QueryParams>(\n req: UnifiedRequest,\n ctx: Context<State, TBody, TQuery>\n): Promise<void> {\n const body = await readRequestBody(req);\n if (body) {\n ctx.request.body = body as TBody;\n }\n}\n\n/**\n * Parse multipart/form-data request body with improved error handling\n */\nasync function parseMultipartBody<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n ctx: Context<State, TBody, TQuery>,\n multipartLimits: MultipartLimits\n): Promise<void> {\n try {\n const limits = multipartLimits || DEFAULT_BODY_LIMITS.multipart;\n const multipartData = await parseMultipartRequest(req, {\n strategy: 'stream',\n maxFileSize: limits.maxFileSize,\n maxFiles: limits.maxFiles,\n maxFieldSize: limits.maxFieldSize,\n // Could add total size validation here\n });\n\n // Extend context with multipart data (type-safe assignments)\n (ctx.request as any).multipart = multipartData;\n (ctx.request as any).files = multipartData.files;\n\n // Set body to fields for backward compatibility with existing form handling\n ctx.request.body = multipartData.fields as TBody;\n } catch (error) {\n ctx.request.body = null as TBody;\n setBodyError(ctx, 'multipart_parse_error', 'Failed to parse multipart data', error);\n }\n}\n\n/**\n * Set body parsing error in context state with proper typing\n */\nfunction setBodyError<TBody = unknown, TQuery = QueryParams>(\n ctx: Context<State, TBody, TQuery>,\n type: BodyParseError['type'],\n message: string,\n error: unknown\n): void {\n const bodyError: BodyParseError = { type, message, error };\n ctx.state._bodyError = bodyError;\n}\n\n/**\n * Read the entire request body as a string\n */\nasync function readRequestBody(req: UnifiedRequest): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n const chunks: Buffer[] = [];\n\n req.on('data', (chunk: Buffer | string) => {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n });\n\n req.on('end', () => {\n resolve(Buffer.concat(chunks).toString('utf8'));\n });\n\n req.on('error', err => {\n reject(err);\n });\n });\n}\n\n/**\n * Get the current context or throw an error if none exists\n */\nexport function getCurrentContext<\n S extends State = State,\n TBody = unknown,\n TQuery = QueryParams,\n>(): Context<S, TBody, TQuery> {\n const ctx = getContext<S, TBody, TQuery>();\n if (!ctx) {\n throw new Error(\n 'No context found. Ensure this function is called within a request handler, ' +\n 'middleware, or function wrapped with runWithContext().'\n );\n }\n return ctx;\n}\n\n/**\n * Check if we're currently in a request context\n */\nexport function isInRequestContext(): boolean {\n return hasContext();\n}\n","/**\n * NotFoundError class for resource not found errors\n *\n * This error is thrown when a requested resource cannot be found.\n * It provides context about what resource was being looked for and how.\n */\n\nimport { BlaizeError, ErrorType } from '@blaize-types/errors';\n\nimport { getCurrentCorrelationId } from './correlation';\n\nimport type { NotFoundErrorDetails } from '@blaize-types/errors';\n/**\n * Error thrown when a requested resource cannot be found\n *\n * Automatically sets HTTP status to 404 and provides context\n * about the missing resource for better debugging and user experience.\n *\n * @example Basic usage:\n * ```typescript\n * throw new NotFoundError('User not found');\n * ```\n *\n * @example With resource context:\n * ```typescript\n * throw new NotFoundError('User not found', {\n * resourceType: 'User',\n * resourceId: 'user-123',\n * suggestion: 'Check if the user ID is correct'\n * });\n * ```\n *\n * @example API endpoint not found:\n * ```typescript\n * throw new NotFoundError('Endpoint not found', {\n * path: '/api/v1/unknown',\n * method: 'GET',\n * suggestion: 'Check the API documentation'\n * });\n * ```\n */\nexport class NotFoundError extends BlaizeError<NotFoundErrorDetails> {\n /**\n * Creates a new NotFoundError instance\n *\n * @param title - Human-readable error message\n * @param details - Optional context about the missing resource\n * @param correlationId - Optional correlation ID (uses current context if not provided)\n */\n constructor(\n title: string,\n details: NotFoundErrorDetails | undefined = undefined,\n correlationId: string | undefined = undefined\n ) {\n super(\n ErrorType.NOT_FOUND,\n title,\n 404, // HTTP 404 Not Found\n correlationId ?? getCurrentCorrelationId(),\n details\n );\n }\n}\n","import { BlaizeError } from '@blaize-types/errors';\n\nimport { generateCorrelationId } from './correlation';\nimport { InternalServerError } from './internal-server-error';\n\nimport type { BlaizeErrorResponse } from '@blaize-types/errors';\n\n/**\n * Checks if an error is a handled BlaizeError instance\n */\nexport function isHandledError(error: unknown): error is BlaizeError {\n return error instanceof BlaizeError;\n}\n\n/**\n * Formats any error into a standardized BlaizeErrorResponse\n */\nexport function formatErrorResponse(error: unknown): BlaizeErrorResponse {\n // Handle BlaizeError instances - they're already properly formatted\n if (isHandledError(error)) {\n return {\n type: error.type,\n title: error.title,\n status: error.status,\n correlationId: error.correlationId,\n timestamp: error.timestamp.toISOString(),\n details: error.details,\n };\n }\n\n // Handle unexpected errors by wrapping them in InternalServerError\n const correlationId = generateCorrelationId();\n let originalMessage: string;\n\n if (error instanceof Error) {\n originalMessage = error.message;\n } else if (error === null || error === undefined) {\n originalMessage = 'Unknown error occurred';\n } else {\n originalMessage = String(error);\n }\n\n // Create InternalServerError for unexpected errors\n const wrappedError = new InternalServerError(\n 'Internal Server Error',\n { originalMessage },\n correlationId\n );\n\n return {\n type: wrappedError.type,\n title: wrappedError.title,\n status: wrappedError.status,\n correlationId: wrappedError.correlationId,\n timestamp: wrappedError.timestamp.toISOString(),\n details: wrappedError.details,\n };\n}\n\n/**\n * Extracts correlation ID from request headers or generates a new one\n */\nexport function extractOrGenerateCorrelationId(\n headerGetter: (name: string) => string | undefined\n): string {\n return headerGetter('x-correlation-id') ?? generateCorrelationId();\n}\n\n/**\n * Sets response headers for error responses\n */\nexport function setErrorResponseHeaders(\n headerSetter: (name: string, value: string) => void,\n correlationId: string\n): void {\n headerSetter('x-correlation-id', correlationId);\n // Add any other standard error headers here if needed\n}\n","import {\n formatErrorResponse,\n extractOrGenerateCorrelationId,\n setErrorResponseHeaders,\n} from '../errors/boundary';\n\nimport type { Context } from '@blaize-types/context';\nimport type { Middleware, MiddlewareFunction, NextFunction } from '@blaize-types/middleware';\n\n/**\n * Options for configuring the error boundary middleware\n */\nexport interface ErrorBoundaryOptions {\n /** Enable debug logging of caught errors */\n debug?: boolean;\n}\n\n/**\n * Creates an error boundary middleware that catches all errors and converts them to proper HTTP responses\n *\n * This middleware should be placed early in the middleware chain to catch all downstream errors.\n * It ensures that:\n * - All BlaizeError instances are properly formatted as HTTP responses\n * - Unexpected errors are wrapped in InternalServerError and logged\n * - Correlation IDs are preserved and added to response headers\n * - No unhandled errors escape the middleware chain\n */\nexport function createErrorBoundary(options: ErrorBoundaryOptions = {}): Middleware {\n const { debug = false } = options;\n\n const middlewareFn: MiddlewareFunction = async (ctx: Context, next: NextFunction) => {\n try {\n await next();\n } catch (error) {\n // Don't handle errors if response was already sent\n if (ctx.response.sent) {\n if (debug) {\n console.error('Error occurred after response was sent:', error);\n }\n return;\n }\n\n // Log error in debug mode\n if (debug) {\n console.error('Error boundary caught error:', error);\n }\n\n // Extract or generate correlation ID from request\n const correlationId = extractOrGenerateCorrelationId(ctx.request.header);\n\n // Format the error as a proper response\n const errorResponse = formatErrorResponse(error);\n\n // Ensure correlation ID is consistent\n errorResponse.correlationId = correlationId;\n\n // Set appropriate response headers\n setErrorResponseHeaders(ctx.response.header, correlationId);\n\n // Send the formatted error response\n ctx.response.status(errorResponse.status).json(errorResponse);\n }\n };\n\n return {\n name: 'ErrorBoundary',\n execute: middlewareFn,\n debug,\n };\n}\n","import { createContext } from '../context/create';\nimport { runWithContext } from '../context/store';\nimport { NotFoundError } from '../errors/not-found-error';\nimport { compose } from '../middleware/compose';\nimport { createErrorBoundary } from '../middleware/error-boundary';\n\nimport type { Server, RequestHandler } from '@blaize-types/server';\n\nexport function createRequestHandler(serverInstance: Server): RequestHandler {\n return async (req, res) => {\n try {\n // Create context for this request\n const context = await createContext(req, res, {\n parseBody: true, // Enable automatic body parsing\n });\n\n // Create error boundary middleware that catches all thrown error classes\n const errorBoundary = createErrorBoundary();\n\n // Compose all middleware with error boundary first (to catch all errors)\n const allMiddleware = [errorBoundary, ...serverInstance.middleware];\n\n // Compose all middleware into a single function\n const handler = compose(allMiddleware);\n\n // Run the request with context in AsyncLocalStorage\n await runWithContext(context, async () => {\n await handler(context, async () => {\n if (!context.response.sent) {\n // Let the router handle the request\n await serverInstance.router.handleRequest(context);\n // If router didn't handle it either, send a 404\n if (!context.response.sent) {\n throw new NotFoundError(\n `Route not found: ${context.request.method} ${context.request.path}`\n );\n }\n }\n });\n });\n } catch (error) {\n // Handle errors in context creation\n console.error('Error creating context:', error);\n res.writeHead(500, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({\n error: 'Internal Server Error',\n message: 'Failed to process request',\n })\n );\n }\n };\n}\n","import type { Server, StopOptions } from '@blaize-types/server';\n\n// Add a global flag to prevent multiple shutdowns\nlet isShuttingDown = false;\n\n// Replace the stopServer function in stop.ts with this version:\n\nexport async function stopServer(serverInstance: Server, options: StopOptions = {}): Promise<void> {\n const server = serverInstance.server;\n const events = serverInstance.events;\n\n if (isShuttingDown) {\n console.log('⚠️ Shutdown already in progress, ignoring duplicate shutdown request');\n return;\n }\n\n if (!server) {\n return;\n }\n\n isShuttingDown = true;\n const timeout = options.timeout || 5000; // Reduced to 5 seconds for faster restarts\n\n try {\n if (options.onStopping) {\n await options.onStopping();\n }\n\n events.emit('stopping');\n\n // Close router watchers with timeout\n if (serverInstance.router && typeof serverInstance.router.close === 'function') {\n console.log('🔌 Closing router watchers...');\n try {\n // Add timeout to router close\n await Promise.race([\n serverInstance.router.close(),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error('Router close timeout')), 2000)\n ),\n ]);\n console.log('✅ Router watchers closed');\n } catch (error) {\n console.error('❌ Error closing router watchers:', error);\n // Continue with shutdown\n }\n }\n\n // Notify plugins with timeout\n try {\n await Promise.race([\n serverInstance.pluginManager.onServerStop(serverInstance, server),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error('Plugin stop timeout')), 2000)\n ),\n ]);\n } catch (error) {\n console.error('❌ Plugin stop timeout:', error);\n // Continue with shutdown\n }\n\n // Create server close promise with shorter timeout\n const closePromise = new Promise<void>((resolve, reject) => {\n server.close((err?: Error) => {\n if (err) return reject(err);\n resolve();\n });\n });\n\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(() => {\n reject(new Error('Server shutdown timeout'));\n }, timeout);\n });\n\n await Promise.race([closePromise, timeoutPromise]);\n\n // Terminate plugins with timeout\n try {\n await Promise.race([\n serverInstance.pluginManager.terminatePlugins(serverInstance),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error('Plugin terminate timeout')), 1000)\n ),\n ]);\n } catch (error) {\n console.error('❌ Plugin terminate timeout:', error);\n // Continue with shutdown\n }\n\n if (options.onStopped) {\n await options.onStopped();\n }\n\n events.emit('stopped');\n serverInstance.server = null as any;\n\n console.log('✅ Graceful shutdown completed');\n isShuttingDown = false;\n } catch (error) {\n isShuttingDown = false;\n console.error('⚠️ Shutdown error (forcing exit):', error);\n\n // Force close the server if graceful shutdown fails\n if (server && typeof server.close === 'function') {\n server.close();\n }\n\n // In development, force exit to allow tsx to restart\n if (process.env.NODE_ENV === 'development') {\n console.log('🔄 Forcing exit for development restart...');\n process.exit(0);\n }\n\n events.emit('error', error);\n throw error;\n }\n}\n\n/**\n * Register signal handlers for graceful shutdown\n */\nexport function registerSignalHandlers(stopFn: () => Promise<void>): { unregister: () => void } {\n const isDevelopment = process.env.NODE_ENV === 'development';\n\n if (isDevelopment) {\n // Development: Force exit for fast restarts\n const sigintHandler = () => {\n console.log('📤 SIGINT received, forcing exit for development restart...');\n process.exit(0);\n };\n\n const sigtermHandler = () => {\n console.log('📤 SIGTERM received, forcing exit for development restart...');\n process.exit(0);\n };\n\n process.on('SIGINT', sigintHandler);\n process.on('SIGTERM', sigtermHandler);\n\n return {\n unregister: () => {\n process.removeListener('SIGINT', sigintHandler);\n process.removeListener('SIGTERM', sigtermHandler);\n },\n };\n } else {\n // Production: Graceful shutdown\n const sigintHandler = () => {\n console.log('📤 SIGINT received, starting graceful shutdown...');\n stopFn().catch(console.error);\n };\n\n const sigtermHandler = () => {\n console.log('📤 SIGTERM received, starting graceful shutdown...');\n stopFn().catch(console.error);\n };\n\n process.on('SIGINT', sigintHandler);\n process.on('SIGTERM', sigtermHandler);\n\n return {\n unregister: () => {\n process.removeListener('SIGINT', sigintHandler);\n process.removeListener('SIGTERM', sigtermHandler);\n },\n };\n }\n}\n","import { z } from 'zod';\n\nimport type { Middleware } from '@blaize-types/middleware';\nimport type { Plugin } from '@blaize-types/plugins';\nimport type { ServerOptions, ServerOptionsInput } from '@blaize-types/server';\n\n// Create a more flexible validation for the middleware function type\nconst middlewareSchema = z.custom<Middleware>(\n data =>\n data !== null &&\n typeof data === 'object' &&\n 'execute' in data &&\n typeof data.execute === 'function',\n {\n message: 'Expected middleware to have an execute function',\n }\n);\n\n// Create a schema for plugins\nconst pluginSchema = z.custom<Plugin>(\n data =>\n data !== null &&\n typeof data === 'object' &&\n 'register' in data &&\n typeof data.register === 'function',\n {\n message: 'Expected a valid plugin object with a register method',\n }\n);\n\n// Create a schema for HTTP/2 options with conditional validation\nconst http2Schema = z\n .object({\n enabled: z.boolean().optional().default(true),\n keyFile: z.string().optional(),\n certFile: z.string().optional(),\n })\n .refine(\n data => {\n // If HTTP/2 is enabled and not in development mode,\n // both keyFile and certFile must be provided\n if (data.enabled && process.env.NODE_ENV === 'production') {\n return data.keyFile && data.certFile;\n }\n return true;\n },\n {\n message:\n 'When HTTP/2 is enabled (outside of development mode), both keyFile and certFile must be provided',\n }\n );\n\n// Validation schema for server options\nexport const serverOptionsSchema = z.object({\n port: z.number().int().positive().optional().default(3000),\n host: z.string().optional().default('localhost'),\n routesDir: z.string().optional().default('./routes'),\n http2: http2Schema.optional().default({\n enabled: true,\n }),\n middleware: z.array(middlewareSchema).optional().default([]),\n plugins: z.array(pluginSchema).optional().default([]),\n});\n\nexport function validateServerOptions(options: ServerOptionsInput): ServerOptions {\n try {\n return serverOptionsSchema.parse(options);\n } catch (error) {\n // Properly type the error as Zod validation error\n if (error instanceof z.ZodError) {\n // Format the Zod error for better readability\n const formattedError = error.format();\n throw new Error(`Invalid server options: ${JSON.stringify(formattedError, null, 2)}`);\n }\n // For other types of errors\n throw new Error(`Invalid server options: ${String(error)}`);\n }\n}\n","import type { Plugin, PluginLifecycleManager, PluginLifecycleOptions } from '@blaize-types/plugins';\nimport type { Server } from '@blaize-types/server';\n\n/**\n * Create a plugin lifecycle manager\n */\nexport function createPluginLifecycleManager(\n options: PluginLifecycleOptions = {}\n): PluginLifecycleManager {\n const { continueOnError = true, debug = false, onError } = options;\n\n /**\n * Log debug messages if enabled\n */\n function log(message: string, ...args: any[]) {\n if (debug) {\n console.log(`[PluginLifecycle] ${message}`, ...args);\n }\n }\n\n /**\n * Handle plugin errors\n */\n function handleError(plugin: Plugin, phase: string, error: Error) {\n const errorMessage = `Plugin ${plugin.name} failed during ${phase}: ${error.message}`;\n\n if (onError) {\n onError(plugin, phase, error);\n } else {\n console.error(errorMessage, error);\n }\n\n if (!continueOnError) {\n throw new Error(errorMessage);\n }\n }\n\n return {\n /**\n * Initialize all plugins\n */\n async initializePlugins(server: Server): Promise<void> {\n log('Initializing plugins...');\n\n for (const plugin of server.plugins) {\n if (plugin.initialize) {\n try {\n log(`Initializing plugin: ${plugin.name}`);\n await plugin.initialize(server);\n } catch (error) {\n handleError(plugin, 'initialize', error as Error);\n }\n }\n }\n\n log(`Initialized ${server.plugins.length} plugins`);\n },\n\n /**\n * Terminate all plugins in reverse order\n */\n async terminatePlugins(server: Server): Promise<void> {\n log('Terminating plugins...');\n\n const pluginsToTerminate = [...server.plugins].reverse();\n\n for (const plugin of pluginsToTerminate) {\n if (plugin.terminate) {\n try {\n log(`Terminating plugin: ${plugin.name}`);\n await plugin.terminate(server);\n } catch (error) {\n handleError(plugin, 'terminate', error as Error);\n }\n }\n }\n\n log(`Terminated ${pluginsToTerminate.length} plugins`);\n },\n\n /**\n * Notify plugins that the server has started\n */\n async onServerStart(server: Server, httpServer: any): Promise<void> {\n log('Notifying plugins of server start...');\n\n for (const plugin of server.plugins) {\n if (plugin.onServerStart) {\n try {\n log(`Notifying plugin of server start: ${plugin.name}`);\n await plugin.onServerStart(httpServer);\n } catch (error) {\n handleError(plugin, 'onServerStart', error as Error);\n }\n }\n }\n },\n\n /**\n * Notify plugins that the server is stopping\n */\n async onServerStop(server: Server, httpServer: any): Promise<void> {\n log('Notifying plugins of server stop...');\n\n const pluginsToNotify = [...server.plugins].reverse();\n\n for (const plugin of pluginsToNotify) {\n if (plugin.onServerStop) {\n try {\n log(`Notifying plugin of server stop: ${plugin.name}`);\n await plugin.onServerStop(httpServer);\n } catch (error) {\n handleError(plugin, 'onServerStop', error as Error);\n }\n }\n }\n },\n };\n}\n","export class PluginError extends Error {\n constructor(\n public pluginName: string,\n message: string,\n public cause?: Error\n ) {\n super(`Plugin \"${pluginName}\": ${message}`);\n this.name = 'PluginError';\n }\n}\n\nexport class PluginLifecycleError extends PluginError {\n constructor(\n pluginName: string,\n public phase: 'register' | 'initialize' | 'terminate' | 'start' | 'stop',\n cause: Error\n ) {\n super(pluginName, `Failed during ${phase} phase: ${cause.message}`, cause);\n this.name = 'PluginLifecycleError';\n }\n}\n\nexport class PluginDependencyError extends PluginError {\n constructor(\n pluginName: string,\n public missingDependency: string\n ) {\n super(pluginName, `Missing dependency: ${missingDependency}`);\n this.name = 'PluginDependencyError';\n }\n}\n\n// packages/blaizejs/src/plugins/errors.ts (or add to existing errors file)\n\nexport class PluginValidationError extends Error {\n constructor(\n public pluginName: string,\n message: string\n ) {\n super(`Plugin validation error${pluginName ? ` for \"${pluginName}\"` : ''}: ${message}`);\n this.name = 'PluginValidationError';\n }\n}\n\nexport class PluginRegistrationError extends Error {\n constructor(\n public pluginName: string,\n message: string\n ) {\n super(`Plugin registration error for \"${pluginName}\": ${message}`);\n this.name = 'PluginRegistrationError';\n }\n}\n","import { PluginValidationError } from './errors';\n\nimport type { Plugin } from '@blaize-types/plugins';\n\nexport interface PluginValidationOptions {\n /** Require specific plugin properties */\n requireVersion?: boolean;\n /** Validate plugin name format */\n validateNameFormat?: boolean;\n /** Check for reserved plugin names */\n checkReservedNames?: boolean;\n}\n\n/**\n * Reserved plugin names that cannot be used\n */\nconst RESERVED_NAMES = new Set([\n 'core',\n 'server',\n 'router',\n 'middleware',\n 'context',\n 'blaize',\n 'blaizejs',\n]);\n\n/**\n * Valid plugin name pattern (lowercase, letters, numbers, hyphens)\n */\nconst VALID_NAME_PATTERN = /^[a-z]([a-z0-9-]*[a-z0-9])?$/;\n\n/**\n * Valid semantic version pattern\n */\nconst VALID_VERSION_PATTERN = /^\\d+\\.\\d+\\.\\d+(?:-[a-zA-Z0-9-.]+)?(?:\\+[a-zA-Z0-9-.]+)?$/;\n\n/**\n * Validate a plugin object\n */\nexport function validatePlugin(\n plugin: unknown,\n options: PluginValidationOptions = {}\n): asserts plugin is Plugin {\n const { requireVersion = true, validateNameFormat = true, checkReservedNames = true } = options;\n\n // Basic type validation\n if (!plugin || typeof plugin !== 'object') {\n throw new PluginValidationError('', 'Plugin must be an object');\n }\n\n const p = plugin as any;\n\n // Validate name\n if (!p.name || typeof p.name !== 'string') {\n throw new PluginValidationError('', 'Plugin must have a name (string)');\n }\n\n // Validate name format\n if (validateNameFormat && !VALID_NAME_PATTERN.test(p.name)) {\n throw new PluginValidationError(\n p.name,\n 'Plugin name must be lowercase letters, numbers, and hyphens only'\n );\n }\n\n // Check reserved names\n if (checkReservedNames && RESERVED_NAMES.has(p.name.toLowerCase())) {\n throw new PluginValidationError(p.name, `Plugin name \"${p.name}\" is reserved`);\n }\n\n // Validate version\n if (requireVersion) {\n if (!p.version || typeof p.version !== 'string') {\n throw new PluginValidationError(p.name, 'Plugin must have a version (string)');\n }\n\n if (!VALID_VERSION_PATTERN.test(p.version)) {\n throw new PluginValidationError(\n p.name,\n 'Plugin version must follow semantic versioning (e.g., \"1.0.0\")'\n );\n }\n }\n\n // Validate register method\n if (!p.register || typeof p.register !== 'function') {\n throw new PluginValidationError(p.name, 'Plugin must have a register method (function)');\n }\n\n // Validate optional lifecycle methods\n const lifecycleMethods = ['initialize', 'terminate', 'onServerStart', 'onServerStop'];\n\n for (const method of lifecycleMethods) {\n if (p[method] && typeof p[method] !== 'function') {\n throw new PluginValidationError(p.name, `Plugin ${method} must be a function if provided`);\n }\n }\n\n // Validate dependencies if present\n // if (p.dependencies) {\n // if (!Array.isArray(p.dependencies) && typeof p.dependencies !== 'string') {\n // throw new PluginValidationError(\n // p.name,\n // 'Plugin dependencies must be a string or array of strings'\n // );\n // }\n\n // const deps = Array.isArray(p.dependencies) ? p.dependencies : [p.dependencies];\n // for (const dep of deps) {\n // if (typeof dep !== 'string') {\n // throw new PluginValidationError(p.name, 'Plugin dependencies must be strings');\n // }\n // }\n // }\n}\n\n/**\n * Validate plugin options object\n */\nexport function validatePluginOptions(pluginName: string, options: unknown, schema?: any): void {\n // Basic validation\n if (options !== undefined && typeof options !== 'object') {\n throw new PluginValidationError(pluginName, 'Plugin options must be an object');\n }\n\n // If a schema is provided, validate against it\n if (schema && options) {\n try {\n schema.parse(options);\n } catch (error) {\n throw new PluginValidationError(\n pluginName,\n `Plugin options validation failed: ${(error as Error).message}`\n );\n }\n }\n}\n\n/**\n * Validate plugin factory function\n */\nexport function validatePluginFactory(\n factory: unknown\n): asserts factory is (...args: any[]) => any {\n if (typeof factory !== 'function') {\n throw new PluginValidationError('', 'Plugin factory must be a function');\n }\n}\n\n/**\n * Check if a plugin name is valid\n */\nexport function isValidPluginName(name: string): boolean {\n return (\n typeof name === 'string' &&\n name.length > 0 &&\n VALID_NAME_PATTERN.test(name) &&\n !RESERVED_NAMES.has(name.toLowerCase())\n );\n}\n\n/**\n * Check if a version string is valid\n */\nexport function isValidVersion(version: string): boolean {\n return typeof version === 'string' && VALID_VERSION_PATTERN.test(version);\n}\n\n/**\n * Sanitize plugin name (remove invalid characters)\n */\nexport function sanitizePluginName(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, '-')\n .replace(/^-+|-+$/g, '')\n .replace(/-+/g, '-');\n}\n","import * as crypto from 'node:crypto';\nimport * as fs from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport * as path from 'node:path';\n\nimport { loadRouteModule } from './loader';\n\nimport type { FileCache, Route } from '@blaize-types/router';\n\nconst fileRouteCache = new Map<string, FileCache>();\n\nexport async function processChangedFile(\n filePath: string,\n routesDir: string,\n updateCache: boolean = true\n): Promise<Route[]> {\n const stat = await fs.stat(filePath);\n const lastModified = stat.mtime.getTime();\n const cachedEntry = fileRouteCache.get(filePath);\n\n // Skip if file hasn't changed by timestamp (only when updating cache)\n if (updateCache && cachedEntry && cachedEntry.timestamp === lastModified) {\n return cachedEntry.routes;\n }\n\n // Clear module cache for this specific file\n invalidateModuleCache(filePath);\n\n // Load only this file\n const routes = await loadRouteModule(filePath, routesDir);\n\n // Only update cache if requested\n if (updateCache) {\n // Calculate content hash for change detection\n const hash = hashRoutes(routes);\n\n // Update cache\n fileRouteCache.set(filePath, {\n routes,\n timestamp: lastModified,\n hash,\n });\n }\n\n return routes;\n}\n\nexport function hasRouteContentChanged(filePath: string, newRoutes: Route[]): boolean {\n const cachedEntry = fileRouteCache.get(filePath);\n if (!cachedEntry) {\n return true;\n }\n\n const newHash = hashRoutes(newRoutes);\n\n return cachedEntry.hash !== newHash;\n}\n\nexport function clearFileCache(filePath?: string): void {\n if (filePath) {\n fileRouteCache.delete(filePath);\n } else {\n fileRouteCache.clear();\n }\n}\n\nfunction hashRoutes(routes: Route[]): string {\n const routeData = routes.map(route => ({\n path: route.path,\n methods: Object.keys(route)\n .filter(key => key !== 'path')\n .sort()\n .map(method => {\n const methodDef = route[method as keyof Route] as any;\n const handlerString = methodDef?.handler ? methodDef.handler.toString() : null;\n return {\n method,\n // Include handler function string for change detection\n handler: handlerString,\n // Include middleware if present\n middleware: methodDef?.middleware ? methodDef.middleware.length : 0,\n // Include schema structure (but not full serialization which can be unstable)\n hasSchema: !!methodDef?.schema,\n schemaKeys: methodDef?.schema ? Object.keys(methodDef.schema).sort() : [],\n };\n }),\n }));\n\n const dataString = JSON.stringify(routeData);\n const hash = crypto.createHash('md5').update(dataString).digest('hex');\n\n return hash;\n}\n\nfunction invalidateModuleCache(filePath: string): void {\n try {\n // Try to resolve the absolute path\n const absolutePath = path.resolve(filePath);\n\n // Check if we're in a CommonJS environment (require is available)\n if (typeof require !== 'undefined') {\n // Delete from require cache if it exists\n delete require.cache[absolutePath];\n\n // Also try to resolve using require.resolve if the file exists\n try {\n const resolvedPath = require.resolve(absolutePath);\n delete require.cache[resolvedPath];\n } catch (resolveError) {\n // Type guard to ensure resolveError is an Error object\n const errorMessage =\n resolveError instanceof Error ? resolveError.message : String(resolveError);\n console.log(`⚠️ Could not resolve path: ${errorMessage}`);\n }\n } else {\n // In pure ESM environment, try to use createRequire for cache invalidation\n try {\n const require = createRequire(import.meta.url);\n delete require.cache[absolutePath];\n\n try {\n const resolvedPath = require.resolve(absolutePath);\n delete require.cache[resolvedPath];\n } catch {\n console.log(`⚠️ Could not resolve ESM path`);\n }\n } catch {\n console.log(`⚠️ createRequire not available in pure ESM`);\n }\n }\n } catch (error) {\n console.log(`⚠️ Error during module cache invalidation for ${filePath}:`, error);\n }\n}\n","import { parseRoutePath } from './parser';\n\nimport type { Route, RouteDefinition } from '@blaize-types/router';\n\nexport async function dynamicImport(filePath: string) {\n // Add a cache-busting query parameter for ESM\n const cacheBuster = `?t=${Date.now()}`;\n const importPath = filePath + cacheBuster;\n\n try {\n const module = await import(importPath);\n console.log(`✅ Successfully imported module`);\n return module;\n } catch (error) {\n // Type guard to ensure resolveError is an Error object\n const errorMessage = error instanceof Error ? error.message : String(error);\n console.log(`⚠️ Error importing with cache buster, trying original path:`, errorMessage);\n // Fallback to original path\n return import(filePath);\n }\n}\n\n/**\n * Load route modules from a file - supports both default export and named exports\n */\nexport async function loadRouteModule(filePath: string, basePath: string): Promise<Route[]> {\n try {\n // Parse the route path from the file path\n const parsedRoute = parseRoutePath(filePath, basePath);\n // Dynamically import the module\n const module = await dynamicImport(filePath);\n console.log('📦 Module exports:', Object.keys(module));\n\n const routes: Route[] = [];\n\n // Method 1: Check for default export (existing pattern)\n if (module.default && typeof module.default === 'object') {\n const route: Route = {\n ...(module.default as RouteDefinition),\n path: parsedRoute.routePath,\n };\n\n routes.push(route);\n }\n\n // Method 2: Check for named exports that look like routes\n Object.entries(module).forEach(([exportName, exportValue]) => {\n // Skip default export (already handled) and non-objects\n if (exportName === 'default' || !exportValue || typeof exportValue !== 'object') {\n return;\n }\n\n // Check if this export looks like a route (has path property and HTTP methods)\n const potentialRoute = exportValue as any;\n\n if (isValidRoute(potentialRoute)) {\n // For named exports, we might want to use the export name or the route's path\n const route: Route = {\n ...potentialRoute,\n // Use the route's own path if it has one, otherwise derive from file\n path: parsedRoute.routePath,\n };\n\n routes.push(route);\n }\n });\n\n if (routes.length === 0) {\n console.warn(`Route file ${filePath} does not export any valid route definitions`);\n return [];\n }\n\n console.log(`✅ Successfully Loaded ${routes.length} route(s)`);\n return routes;\n } catch (error) {\n console.error(`Failed to load route module ${filePath}:`, error);\n return [];\n }\n}\n\n/**\n * Check if an object looks like a valid route\n */\nfunction isValidRoute(obj: any): boolean {\n if (!obj || typeof obj !== 'object') {\n return false;\n }\n\n // Check if it has at least one HTTP method\n const httpMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];\n const hasHttpMethod = httpMethods.some(\n method => obj[method] && typeof obj[method] === 'object' && obj[method].handler\n );\n\n return hasHttpMethod;\n}\n","import * as os from 'node:os';\n\nimport { processChangedFile } from './cache';\nimport { findRouteFiles } from './finder';\n\nimport type { Route } from '@blaize-types/router';\n\nexport async function processFilesInParallel(\n filePaths: string[],\n processor: (filePath: string) => Promise<Route[]>,\n concurrency: number = Math.max(1, Math.floor(os.cpus().length / 2))\n): Promise<Route[][]> {\n const chunks = chunkArray(filePaths, concurrency);\n const results: Route[][] = [];\n\n for (const chunk of chunks) {\n const chunkResults = await Promise.allSettled(chunk.map(filePath => processor(filePath)));\n\n const successfulResults = chunkResults\n .filter(result => result.status === 'fulfilled')\n .map(result => (result as PromiseFulfilledResult<Route[]>).value);\n\n results.push(...successfulResults);\n }\n\n return results;\n}\n\nexport async function loadInitialRoutesParallel(routesDir: string): Promise<Route[]> {\n const files = await findRouteFiles(routesDir);\n const routeArrays = await processFilesInParallel(files, filePath =>\n processChangedFile(filePath, routesDir)\n );\n\n return routeArrays.flat();\n}\n\nfunction chunkArray<T>(array: T[], chunkSize: number): T[][] {\n const chunks: T[][] = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n chunks.push(array.slice(i, i + chunkSize));\n }\n return chunks;\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\n\nimport type { FindRouteFilesOptions } from '@blaize-types/router';\n\n/**\n * Find all route files in the specified directory\n */\nexport async function findRouteFiles(\n routesDir: string,\n options: FindRouteFilesOptions = {}\n): Promise<string[]> {\n // Convert to absolute path if it's relative\n const absoluteDir = path.isAbsolute(routesDir)\n ? routesDir\n : path.resolve(process.cwd(), routesDir);\n\n console.log('Creating router with routes directory:', absoluteDir);\n\n // Check if directory exists\n try {\n const stats = await fs.stat(absoluteDir);\n if (!stats.isDirectory()) {\n throw new Error(`Route directory is not a directory: ${absoluteDir}`);\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`Route directory not found: ${absoluteDir}`);\n }\n throw error;\n }\n\n const routeFiles: string[] = [];\n const ignore = options.ignore || ['node_modules', '.git'];\n\n async function scanDirectory(dir: string) {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n\n // Skip ignored directories\n if (entry.isDirectory() && ignore.includes(entry.name)) {\n continue;\n }\n\n if (entry.isDirectory()) {\n await scanDirectory(fullPath);\n } else if (isRouteFile(entry.name)) {\n routeFiles.push(fullPath);\n }\n }\n }\n\n await scanDirectory(absoluteDir);\n return routeFiles;\n}\n\n/**\n * Check if a file is a valid route file\n */\nfunction isRouteFile(filename: string): boolean {\n // Route files are TypeScript/JavaScript files that don't start with underscore\n return !filename.startsWith('_') && (filename.endsWith('.ts') || filename.endsWith('.js'));\n}\n","import type { ReloadMetrics } from '@blaize-types/router';\n\nconst profilerState: ReloadMetrics = {\n fileChanges: 0,\n totalReloadTime: 0,\n averageReloadTime: 0,\n slowReloads: [],\n};\n\nexport function trackReloadPerformance(filePath: string, startTime: number): void {\n const duration = Date.now() - startTime;\n\n profilerState.fileChanges++;\n profilerState.totalReloadTime += duration;\n profilerState.averageReloadTime = profilerState.totalReloadTime / profilerState.fileChanges;\n\n if (duration > 100) {\n profilerState.slowReloads.push({ file: filePath, time: duration });\n if (profilerState.slowReloads.length > 10) {\n profilerState.slowReloads.shift();\n }\n }\n\n if (process.env.NODE_ENV === 'development') {\n const emoji = duration < 50 ? '⚡' : duration < 100 ? '🔄' : '🐌';\n console.log(`${emoji} Route reload: ${filePath} (${duration}ms)`);\n }\n}\n\nexport function getReloadMetrics(): Readonly<ReloadMetrics> {\n return { ...profilerState };\n}\n\nexport function resetReloadMetrics(): void {\n profilerState.fileChanges = 0;\n profilerState.totalReloadTime = 0;\n profilerState.averageReloadTime = 0;\n profilerState.slowReloads = [];\n}\n\nexport function withPerformanceTracking<T extends (...args: any[]) => Promise<any>>(\n fn: T,\n filePath: string\n): T {\n console.log(`Tracking performance for: ${filePath}`);\n return (async (...args: Parameters<T>) => {\n const startTime = Date.now();\n try {\n const result = await fn(...args);\n trackReloadPerformance(filePath, startTime);\n return result;\n } catch (error) {\n trackReloadPerformance(filePath, startTime);\n throw error;\n }\n }) as T;\n}\n","import * as path from 'node:path';\n\nimport { watch } from 'chokidar';\n\nimport { hasRouteContentChanged, processChangedFile } from './cache';\nimport { findRouteFiles } from './finder';\n\nimport type { Route, WatchOptions } from '@blaize-types/router';\n\n/**\n * Watch for route file changes\n */\nexport function watchRoutes(routesDir: string, options: WatchOptions = {}) {\n // Debounce rapid file changes\n const debounceMs = options.debounceMs || 16;\n const debouncedCallbacks = new Map<string, NodeJS.Timeout>();\n\n function createDebouncedCallback<T extends (...args: any[]) => void>(\n fn: T,\n filePath: string\n ): (...args: Parameters<T>) => void {\n return (...args: Parameters<T>) => {\n // Clear existing timeout for this file\n const existingTimeout = debouncedCallbacks.get(filePath);\n if (existingTimeout) {\n clearTimeout(existingTimeout);\n }\n\n // Set new timeout\n const timeoutId = setTimeout(() => {\n fn(...args);\n debouncedCallbacks.delete(filePath);\n }, debounceMs);\n\n debouncedCallbacks.set(filePath, timeoutId);\n };\n }\n // Track loaded routes by file path - now stores arrays of routes\n const routesByPath = new Map<string, Route[]>();\n\n // Initial loading of routes\n async function loadInitialRoutes() {\n try {\n const files = await findRouteFiles(routesDir, {\n ignore: options.ignore,\n });\n\n for (const filePath of files) {\n await loadAndNotify(filePath);\n }\n } catch (error) {\n handleError(error);\n }\n }\n\n // Optimized load and notify function\n async function loadAndNotify(filePath: string) {\n try {\n const existingRoutes = routesByPath.get(filePath);\n\n // Step 1: Load new routes WITHOUT updating cache\n const newRoutes = await processChangedFile(filePath, routesDir, false);\n\n if (!newRoutes || newRoutes.length === 0) {\n return;\n }\n\n // Step 2: Check if content has actually changed (cache still has old data)\n if (existingRoutes && !hasRouteContentChanged(filePath, newRoutes)) {\n return;\n }\n\n // Step 3: Content changed! Now update the cache\n await processChangedFile(filePath, routesDir, true);\n\n const normalizedPath = path.normalize(filePath);\n\n if (existingRoutes) {\n routesByPath.set(filePath, newRoutes);\n if (options.onRouteChanged) {\n options.onRouteChanged(normalizedPath, newRoutes);\n }\n } else {\n routesByPath.set(filePath, newRoutes);\n if (options.onRouteAdded) {\n options.onRouteAdded(normalizedPath, newRoutes);\n }\n }\n } catch (error) {\n console.log(`⚠️ Error processing file ${filePath}:`, error);\n handleError(error);\n }\n }\n\n // Handle route file removal\n function handleRemoved(filePath: string) {\n const normalizedPath = path.normalize(filePath);\n const routes = routesByPath.get(normalizedPath);\n\n if (routes && routes.length > 0 && options.onRouteRemoved) {\n options.onRouteRemoved(normalizedPath, routes);\n }\n\n routesByPath.delete(normalizedPath);\n }\n\n // Handle errors\n function handleError(error: unknown) {\n if (options.onError && error instanceof Error) {\n options.onError(error);\n } else {\n console.error('⚠️ Route watcher error:', error);\n }\n }\n\n // Start file watcher\n // Create optimized watcher\n const watcher = watch(routesDir, {\n // Much faster response times\n awaitWriteFinish: {\n stabilityThreshold: 50, // Reduced from 300ms\n pollInterval: 10, // Reduced from 100ms\n },\n\n // Performance optimizations\n usePolling: false,\n atomic: true,\n followSymlinks: false,\n depth: 10,\n\n // More aggressive ignoring\n ignored: [\n /(^|[/\\\\])\\../,\n /node_modules/,\n /\\.git/,\n /\\.DS_Store/,\n /Thumbs\\.db/,\n /\\.(test|spec)\\.(ts|js)$/,\n /\\.d\\.ts$/,\n /\\.map$/,\n /~$/,\n ...(options.ignore || []),\n ],\n });\n\n // Set up event handlers\n watcher\n .on('add', filePath => {\n const debouncedLoad = createDebouncedCallback(loadAndNotify, filePath);\n debouncedLoad(filePath);\n })\n .on('change', filePath => {\n const debouncedLoad = createDebouncedCallback(loadAndNotify, filePath);\n\n // Call debounced load for changed file\n debouncedLoad(filePath);\n })\n .on('unlink', filePath => {\n const debouncedRemove = createDebouncedCallback(handleRemoved, filePath);\n debouncedRemove(filePath);\n })\n .on('error', handleError);\n\n // Load initial routes\n loadInitialRoutes().catch(handleError);\n\n // Return control methods\n return {\n close: () => {\n // Clear any pending debounced callbacks\n debouncedCallbacks.forEach(timeout => clearTimeout(timeout));\n debouncedCallbacks.clear();\n\n return watcher.close();\n },\n getRoutes: () => {\n const allRoutes: Route[] = [];\n for (const routes of routesByPath.values()) {\n allRoutes.push(...routes);\n }\n return allRoutes;\n },\n getRoutesByFile: () => new Map(routesByPath),\n };\n}\n","import { z } from 'zod';\n\nimport { validateBody } from './body';\nimport { validateParams } from './params';\nimport { validateQuery } from './query';\nimport { validateResponse } from './response';\nimport { InternalServerError } from '../../errors/internal-server-error';\nimport { ValidationError } from '../../errors/validation-error';\n\nimport type { Context } from '@blaize-types/context';\nimport type { Middleware, MiddlewareFunction, NextFunction } from '@blaize-types/middleware';\nimport type { RouteSchema } from '@blaize-types/router';\n\n/**\n * Create a validation middleware for request data\n */\nexport function createRequestValidator(schema: RouteSchema, debug: boolean = false): Middleware {\n const middlewareFn: MiddlewareFunction = async (ctx: Context, next: NextFunction) => {\n // Validate params if schema exists - throw immediately on failure\n if (schema.params && ctx.request.params) {\n try {\n ctx.request.params = validateParams(ctx.request.params, schema.params);\n } catch (error) {\n const fieldErrors = extractZodFieldErrors(error);\n const errorCount = fieldErrors.reduce((sum, fe) => sum + fe.messages.length, 0);\n\n throw new ValidationError('Request validation failed', {\n fields: fieldErrors,\n errorCount,\n section: 'params',\n });\n }\n }\n\n // Validate query if schema exists - throw immediately on failure\n if (schema.query && ctx.request.query) {\n try {\n ctx.request.query = validateQuery(ctx.request.query, schema.query);\n } catch (error) {\n const fieldErrors = extractZodFieldErrors(error);\n const errorCount = fieldErrors.reduce((sum, fe) => sum + fe.messages.length, 0);\n\n throw new ValidationError('Request validation failed', {\n fields: fieldErrors,\n errorCount,\n section: 'query',\n });\n }\n }\n\n // Validate body if schema exists - throw immediately on failure\n if (schema.body) {\n try {\n ctx.request.body = validateBody(ctx.request.body, schema.body);\n } catch (error) {\n const fieldErrors = extractZodFieldErrors(error);\n const errorCount = fieldErrors.reduce((sum, fe) => sum + fe.messages.length, 0);\n\n throw new ValidationError('Request validation failed', {\n fields: fieldErrors,\n errorCount,\n section: 'body',\n });\n }\n }\n // Continue if validation passed\n await next();\n };\n\n return {\n name: 'RequestValidator',\n execute: middlewareFn,\n debug,\n };\n}\n\n/**\n * Create a validation middleware for response data\n */\nexport function createResponseValidator<T>(\n responseSchema: z.ZodType<T, z.ZodTypeDef, unknown>,\n debug: boolean = false\n): Middleware {\n const middlewareFn: MiddlewareFunction = async (ctx, next) => {\n // Store the original json method\n const originalJson = ctx.response.json;\n\n // Override the json method to validate the response\n ctx.response.json = (body: unknown, status?: number) => {\n try {\n // Validate the response body\n const validatedBody = validateResponse(body, responseSchema);\n\n // Restore the original json method\n ctx.response.json = originalJson;\n\n // Send the validated response\n return originalJson.call(ctx.response, validatedBody, status);\n } catch (error) {\n // Restore the original json method\n ctx.response.json = originalJson;\n\n throw new InternalServerError('Response validation failed', {\n responseSchema: responseSchema.description || 'Unknown schema',\n validationError: extractZodFieldErrors(error),\n originalResponse: body,\n });\n }\n };\n\n await next();\n };\n\n return {\n name: 'ResponseValidator',\n execute: middlewareFn,\n debug,\n };\n}\n\n/**\n * Extract structured field errors from Zod validation errors\n *\n * Converts Zod errors into a clean array of error messages per field.\n *\n * @param error - The validation error (typically a ZodError)\n * @returns Array of error messages for the field\n *\n * @example\n * ```typescript\n * const zodError = new z.ZodError([\n * { path: ['email'], message: 'Invalid email' },\n * { path: ['email'], message: 'Email is required' }\n * ]);\n *\n * const fieldErrors = extractZodFieldErrors(zodError);\n * // Returns: ['Invalid email', 'Email is required']\n * ```\n */\nfunction extractZodFieldErrors(error: unknown): { field: string; messages: string[] }[] {\n if (error instanceof z.ZodError) {\n // Group errors by field path\n const fieldErrorMap = new Map<string, string[]>();\n\n for (const issue of error.issues) {\n // Get the field path (e.g., ['user', 'email'] becomes 'user.email')\n const fieldPath = issue.path.length > 0 ? issue.path.join('.') : 'root';\n\n if (!fieldErrorMap.has(fieldPath)) {\n fieldErrorMap.set(fieldPath, []);\n }\n fieldErrorMap.get(fieldPath)!.push(issue.message);\n }\n\n // Convert map to array of field errors\n return Array.from(fieldErrorMap.entries()).map(([field, messages]) => ({\n field,\n messages,\n }));\n }\n\n if (error instanceof Error) {\n return [{ field: 'unknown', messages: [error.message] }];\n }\n\n return [{ field: 'unknown', messages: [String(error)] }];\n}\n\n/**\n * 🔄 DEPRECATED: Keep for backward compatibility but mark as deprecated\n *\n * This function maintains the old API for any existing code that might depend on it.\n * New code should use extractZodFieldErrors for better structured error handling.\n *\n * @deprecated Use extractZodFieldErrors instead for better structured error details\n * @param error - The validation error to format\n * @returns Formatted error object (maintains old structure)\n */\nexport function formatValidationError(error: unknown): unknown {\n // Handle Zod errors\n if (\n error &&\n typeof error === 'object' &&\n 'format' in error &&\n typeof error.format === 'function'\n ) {\n return error.format();\n }\n\n // Handle other error types\n return error instanceof Error ? error.message : String(error);\n}\n","import { z } from 'zod';\n\n/**\n * Validate request body\n */\nexport function validateBody<T>(body: unknown, schema: z.ZodType<T>): T {\n if (schema instanceof z.ZodObject) {\n return schema.strict().parse(body) as T;\n }\n // Parse and validate with the provided schema\n return schema.parse(body);\n}\n","import { z } from 'zod';\n\n/**\n * Validate request parameters\n */\nexport function validateParams<T>(\n params: Record<string, string>,\n schema: z.ZodType<T, z.ZodTypeDef, unknown>\n): T {\n if (schema instanceof z.ZodObject) {\n // If schema is an object, ensure strict parsing\n return schema.strict().parse(params) as T;\n }\n // Parse and validate with the provided schema\n return schema.parse(params);\n}\n","import { z } from 'zod';\n\n/**\n * Validate query parameters\n */\nexport function validateQuery<T>(\n query: Record<string, string | string[] | undefined>,\n schema: z.ZodType<T, z.ZodTypeDef, unknown>\n): T {\n if (schema instanceof z.ZodObject) {\n // If schema is an object, ensure strict parsing\n return schema.strict().parse(query) as T;\n }\n // Parse and validate with the provided schema\n return schema.parse(query);\n}\n","import { z } from 'zod';\n\n/**\n * Validate response body\n */\nexport function validateResponse<T>(\n response: unknown,\n schema: z.ZodType<T, z.ZodTypeDef, unknown>\n): T {\n if (schema instanceof z.ZodObject) {\n return schema.strict().parse(response) as T;\n }\n // Parse and validate with the provided schema\n return schema.parse(response);\n}\n","import { compose } from '../../middleware/compose';\nimport { createRequestValidator, createResponseValidator } from '../validation';\n\nimport type { Context } from '@blaize-types/context';\nimport type { RouteMethodOptions } from '@blaize-types/router';\n\n/**\n * Execute a route handler with its middleware\n */\nexport async function executeHandler(\n ctx: Context,\n routeOptions: RouteMethodOptions,\n params: Record<string, string>\n): Promise<void> {\n // Set up middleware chain\n const middleware = [...(routeOptions.middleware || [])];\n\n // Add validation middleware if schemas are defined\n if (routeOptions.schema) {\n if (routeOptions.schema.params || routeOptions.schema.query || routeOptions.schema.body) {\n middleware.unshift(createRequestValidator(routeOptions.schema));\n }\n\n if (routeOptions.schema.response) {\n middleware.push(createResponseValidator(routeOptions.schema.response));\n }\n }\n\n // Compose middleware with the final handler\n const handler = compose([...middleware]);\n\n // Execute the middleware chain\n await handler(ctx, async () => {\n // Execute the handler with the new argument style\n const result = await routeOptions.handler(ctx, params);\n\n // Handle the result if it wasn't already handled by the handler\n if (!ctx.response.sent && result !== undefined) {\n ctx.response.json(result);\n }\n });\n}\n","/**\n * Extract parameter values from a URL path\n */\nexport function extractParams(\n path: string,\n pattern: RegExp,\n paramNames: string[]\n): Record<string, string> {\n const match = pattern.exec(path);\n if (!match) {\n return {};\n }\n\n const params: Record<string, string> = {};\n\n // Extract parameter values from regex match groups\n for (let i = 0; i < paramNames.length; i++) {\n // Add 1 to index since the first capture group is at index 1\n params[paramNames[i]!] = match[i + 1] || '';\n }\n\n return params;\n}\n\n/**\n * Compile a path pattern with parameters\n */\nexport function compilePathPattern(path: string): { pattern: RegExp; paramNames: string[] } {\n const paramNames: string[] = [];\n\n // Special case for root path\n if (path === '/') {\n return {\n pattern: /^\\/$/,\n paramNames: [],\n };\n }\n\n // First escape special regex characters (except for : and [ ] which we process specially)\n let patternString = path.replace(/([.+*?^$(){}|\\\\])/g, '\\\\$1');\n\n // Replace route parameters with regex capture groups\n patternString = patternString\n // Replace :param syntax with capture groups\n .replace(/\\/:([^/]+)/g, (_, paramName) => {\n paramNames.push(paramName);\n return '/([^/]+)';\n })\n // Replace [param] syntax (for file-based routing)\n .replace(/\\/\\[([^\\]]+)\\]/g, (_, paramName) => {\n paramNames.push(paramName);\n return '/([^/]+)';\n });\n\n // Make the trailing slash optional (if not already the root path)\n // This adds an optional trailing slash to the end of the pattern\n patternString = `${patternString}(?:/)?`;\n\n // Create the regex pattern\n // This is safe because we've escaped special RegExp characters and\n // we're using developer-defined routes, not user input\n const pattern = new RegExp(`^${patternString}$`);\n\n return {\n pattern,\n paramNames,\n };\n}\n\n/**\n * Convert parameters object to URL query string\n */\nexport function paramsToQuery(params: Record<string, string | number | boolean>): string {\n const parts: string[] = [];\n\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined && value !== null) {\n const encodedKey = encodeURIComponent(key);\n const encodedValue = encodeURIComponent(String(value));\n parts.push(`${encodedKey}=${encodedValue}`);\n }\n }\n\n return parts.length > 0 ? `?${parts.join('&')}` : '';\n}\n\n/**\n * Build a URL with path parameters\n */\nexport function buildUrl(\n pathPattern: string,\n params: Record<string, string | number | boolean> = {},\n query: Record<string, string | number | boolean> = {}\n): string {\n // Extract path parameters and query parameters\n const pathParams: Record<string, string | number | boolean> = {};\n const queryParams: Record<string, string | number | boolean> = { ...query };\n\n // Find all parameter names in the path\n const paramNames: string[] = [];\n pathPattern.replace(/\\/:([^/]+)/g, (_, paramName) => {\n paramNames.push(paramName);\n return '/';\n });\n\n // Separate params into path params and additional query params\n for (const [key, value] of Object.entries(params)) {\n if (paramNames.includes(key)) {\n pathParams[key] = value;\n } else {\n queryParams[key] = value;\n }\n }\n\n // Replace path parameters\n let url = pathPattern;\n for (const [key, value] of Object.entries(pathParams)) {\n url = url.replace(`:${key}`, encodeURIComponent(String(value)));\n }\n\n // Add query string if needed\n const queryString = paramsToQuery(queryParams);\n\n return url + queryString;\n}\n","import { compilePathPattern, extractParams } from './params';\n\nimport type {\n HttpMethod,\n RouteMethodOptions,\n RouteMatch,\n Matcher,\n RouteEntry,\n Route,\n} from '../../index';\n\n/**\n * Create a route matcher\n */\nexport function createMatcher(): Matcher {\n // Private state\n const routes: RouteEntry[] = [];\n\n return {\n /**\n * Add a route to the matcher\n */\n add(path: string, method: HttpMethod, routeOptions: RouteMethodOptions) {\n const { pattern, paramNames } = compilePathPattern(path);\n\n const newRoute: RouteEntry = {\n path,\n method,\n pattern,\n paramNames,\n routeOptions,\n };\n\n // Find the insertion point using findIndex\n const insertIndex = routes.findIndex(route => paramNames.length < route.paramNames.length);\n\n // If no insertion point found, append to end\n if (insertIndex === -1) {\n routes.push(newRoute);\n } else {\n routes.splice(insertIndex, 0, newRoute);\n }\n },\n\n /**\n * Remove a route from the matcher by path\n */\n remove(path: string) {\n // Remove all routes that match the given path\n for (let i = routes.length - 1; i >= 0; i--) {\n if ((routes[i] as Route).path === path) {\n routes.splice(i, 1);\n }\n }\n },\n\n /**\n * Clear all routes from the matcher\n */\n clear() {\n routes.length = 0;\n },\n\n /**\n * Match a URL path to a route\n */\n match(path: string, method: HttpMethod): RouteMatch | null {\n // First, try to find an exact match for the method\n const pathname = path.split('?')[0];\n if (!pathname) return null;\n\n for (const route of routes) {\n // Skip routes that don't match the method\n if (route.method !== method) continue;\n\n // Try to match the path\n const match = route.pattern.exec(pathname);\n if (match) {\n // Extract parameters from the match\n const params = extractParams(path, route.pattern, route.paramNames);\n\n return {\n route: route.routeOptions,\n params,\n };\n }\n }\n\n // If no exact method match, check if path exists but method is different\n // This allows returning 405 Method Not Allowed instead of 404 Not Found\n const matchingPath = routes.find(\n route => route.method !== method && route.pattern.test(path)\n );\n\n if (matchingPath) {\n // Return null but with allowedMethods to indicate method not allowed\n return {\n route: null,\n params: {},\n methodNotAllowed: true,\n allowedMethods: routes\n .filter(route => route.pattern.test(path))\n .map(route => route.method),\n } as unknown as RouteMatch; // Type assertion for the extended return type\n }\n\n return null; // No match found\n },\n\n /**\n * Get all registered routes\n */\n getRoutes(): { path: string; method: HttpMethod }[] {\n return routes.map(route => ({\n path: route.path,\n method: route.method,\n }));\n },\n\n /**\n * Find routes matching a specific path\n */\n findRoutes(\n path: string\n ): { path: string; method: HttpMethod; params: Record<string, string> }[] {\n return routes\n .filter(route => route.pattern.test(path))\n .map(route => ({\n path: route.path,\n method: route.method,\n params: extractParams(path, route.pattern, route.paramNames),\n }));\n },\n };\n}\n","import type { Route, RouteRegistry } from '@blaize-types/router';\n\nexport function createRouteRegistry(): RouteRegistry {\n return {\n routesByPath: new Map(),\n routesByFile: new Map(),\n pathToFile: new Map(),\n };\n}\n\nexport function updateRoutesFromFile(\n registry: RouteRegistry,\n filePath: string,\n newRoutes: Route[]\n): { added: Route[]; removed: string[]; changed: Route[] } {\n console.log(`Updating routes from file: ${filePath}`);\n const oldPaths = registry.routesByFile.get(filePath) || new Set();\n const newPaths = new Set(newRoutes.map(r => r.path));\n\n // Fast diff calculation\n const added = newRoutes.filter(r => !oldPaths.has(r.path));\n const removed = Array.from(oldPaths).filter(p => !newPaths.has(p));\n const potentiallyChanged = newRoutes.filter(r => oldPaths.has(r.path));\n\n // Check for actual content changes\n const changed = potentiallyChanged.filter(route => {\n const existingRoute = registry.routesByPath.get(route.path);\n return !existingRoute || !routesEqual(existingRoute, route);\n });\n\n // Apply updates\n applyRouteUpdates(registry, filePath, { added, removed, changed });\n\n return { added, removed, changed };\n}\n\nexport function getRouteFromRegistry(registry: RouteRegistry, path: string): Route | undefined {\n return registry.routesByPath.get(path);\n}\n\nexport function getAllRoutesFromRegistry(registry: RouteRegistry): Route[] {\n return Array.from(registry.routesByPath.values());\n}\n\nexport function getFileRoutes(registry: RouteRegistry, filePath: string): Route[] {\n const paths = registry.routesByFile.get(filePath) || new Set();\n return Array.from(paths)\n .map(path => registry.routesByPath.get(path)!)\n .filter(Boolean);\n}\n\nfunction applyRouteUpdates(\n registry: RouteRegistry,\n filePath: string,\n updates: { added: Route[]; removed: string[]; changed: Route[] }\n): void {\n const { added, removed, changed } = updates;\n\n // Remove old routes\n removed.forEach(path => {\n registry.routesByPath.delete(path);\n registry.pathToFile.delete(path);\n });\n\n // Add/update routes\n [...added, ...changed].forEach(route => {\n registry.routesByPath.set(route.path, route);\n registry.pathToFile.set(route.path, filePath);\n });\n\n // Update file -> paths mapping\n const allPathsForFile = new Set([\n ...added.map(r => r.path),\n ...changed.map(r => r.path),\n ...Array.from(registry.routesByFile.get(filePath) || []).filter(p => !removed.includes(p)),\n ]);\n\n if (allPathsForFile.size > 0) {\n registry.routesByFile.set(filePath, allPathsForFile);\n } else {\n registry.routesByFile.delete(filePath);\n }\n}\n\nfunction routesEqual(route1: Route, route2: Route): boolean {\n if (route1.path !== route2.path) return false;\n\n const methods1 = Object.keys(route1)\n .filter(k => k !== 'path')\n .sort();\n const methods2 = Object.keys(route2)\n .filter(k => k !== 'path')\n .sort();\n\n if (methods1.length !== methods2.length) return false;\n\n return methods1.every(method => {\n const handler1 = route1[method as keyof Route];\n const handler2 = route2[method as keyof Route];\n\n // Compare handler signatures/structure rather than function references\n return typeof handler1 === typeof handler2;\n });\n}\n","import type { Route, HttpMethod, RouteMethodOptions, Matcher } from '@blaize-types/router';\n\nexport function addRouteToMatcher(route: Route, matcher: Matcher): void {\n Object.entries(route).forEach(([method, methodOptions]) => {\n if (method === 'path' || !methodOptions) return;\n matcher.add(route.path, method as HttpMethod, methodOptions as RouteMethodOptions);\n });\n}\n\nexport function removeRouteFromMatcher(path: string, matcher: Matcher): void {\n // Use matcher's remove method if available, otherwise fallback to clear/rebuild\n if ('remove' in matcher && typeof matcher.remove === 'function') {\n matcher.remove(path);\n } else {\n // This requires rebuilding the matcher - could be optimized\n console.warn('Matcher does not support selective removal, consider adding remove() method');\n }\n}\n\nexport function updateRouteInMatcher(route: Route, matcher: Matcher): void {\n removeRouteFromMatcher(route.path, matcher);\n addRouteToMatcher(route, matcher);\n}\n\nexport function rebuildMatcherWithRoutes(routes: Route[], matcher: Matcher): void {\n if ('clear' in matcher && typeof matcher.clear === 'function') {\n matcher.clear();\n }\n\n routes.forEach(route => addRouteToMatcher(route, matcher));\n}\n","import { NotFoundError } from '../errors/not-found-error';\nimport { clearFileCache } from './discovery/cache';\nimport { loadInitialRoutesParallel } from './discovery/parallel';\nimport { withPerformanceTracking } from './discovery/profiler';\nimport { watchRoutes } from './discovery/watchers';\nimport { executeHandler } from './handlers';\nimport { createMatcher } from './matching';\nimport {\n createRouteRegistry,\n updateRoutesFromFile,\n getAllRoutesFromRegistry,\n} from './registry/fast-registry';\nimport {\n addRouteToMatcher,\n removeRouteFromMatcher,\n updateRouteInMatcher,\n} from './utils/matching-helpers';\n\nimport type { Context } from '@blaize-types/context';\nimport type { HttpMethod, Route, RouterOptions, Router } from '@blaize-types/router';\n\nconst DEFAULT_ROUTER_OPTIONS = {\n routesDir: './routes',\n basePath: '/',\n watchMode: process.env.NODE_ENV === 'development',\n};\n\n/**\n * Create an optimized router instance with fast hot reload\n */\nexport function createRouter(options: RouterOptions): Router {\n // Merge with default options\n const routerOptions = {\n ...DEFAULT_ROUTER_OPTIONS,\n ...options,\n };\n\n if (options.basePath && !options.basePath.startsWith('/')) {\n console.warn('Base path does nothing');\n }\n\n // Use optimized registry instead of simple array\n const registry = createRouteRegistry();\n const matcher = createMatcher();\n\n // Initialize routes\n let initialized = false;\n let initializationPromise: Promise<void> | null = null;\n let _watchers: Map<string, ReturnType<typeof watchRoutes>> | null = null;\n\n const routeDirectories = new Set<string>([routerOptions.routesDir]);\n\n /**\n * Apply registry changes to matcher efficiently\n */\n function applyMatcherChanges(changes: { added: Route[]; removed: string[]; changed: Route[] }) {\n console.log('\\n🔧 APPLYING MATCHER CHANGES:');\n console.log(` Adding ${changes.added.length} routes`);\n console.log(` Removing ${changes.removed.length} routes`);\n console.log(` Updating ${changes.changed.length} routes`);\n\n // Remove routes first\n changes.removed.forEach(routePath => {\n console.log(` ➖ Removing: ${routePath}`);\n removeRouteFromMatcher(routePath, matcher);\n });\n\n // Add new routes\n changes.added.forEach(route => {\n const methods = Object.keys(route).filter(key => key !== 'path');\n console.log(` ➕ Adding: ${route.path} [${methods.join(', ')}]`);\n addRouteToMatcher(route, matcher);\n });\n\n // Update changed routes\n changes.changed.forEach(route => {\n const methods = Object.keys(route).filter(key => key !== 'path');\n console.log(` 🔄 Updating: ${route.path} [${methods.join(', ')}]`);\n updateRouteInMatcher(route, matcher);\n });\n\n console.log('✅ Matcher changes applied\\n');\n }\n\n /**\n * Add multiple routes with batch processing\n */\n function addRoutesWithSource(routes: Route[], source: string) {\n try {\n // Use registry for batch conflict detection and management\n const changes = updateRoutesFromFile(registry, source, routes);\n\n // Apply all changes to matcher in one operation\n applyMatcherChanges(changes);\n\n return changes;\n } catch (error) {\n console.error(`⚠️ Route conflicts from ${source}:`, error);\n throw error;\n }\n }\n\n /**\n * Optimized route loading with parallel processing\n */\n async function loadRoutesFromDirectory(directory: string, source: string, prefix?: string) {\n try {\n // Use parallel loading for better performance\n const discoveredRoutes = await loadInitialRoutesParallel(directory);\n\n // Apply prefix if provided\n const finalRoutes = discoveredRoutes.map(route =>\n prefix ? { ...route, path: `${prefix}${route.path}` } : route\n );\n\n // Batch add all routes from this directory\n const changes = addRoutesWithSource(finalRoutes, source);\n\n console.log(\n `Loaded ${discoveredRoutes.length} routes from ${source}${prefix ? ` with prefix ${prefix}` : ''} ` +\n `(${changes.added.length} added, ${changes.changed.length} changed, ${changes.removed.length} removed)`\n );\n } catch (error) {\n console.error(`⚠️ Failed to load routes from ${source}:`, error);\n throw error;\n }\n }\n\n /**\n * Initialize the router with parallel route loading\n */\n async function initialize() {\n if (initialized || initializationPromise) {\n return initializationPromise;\n }\n\n initializationPromise = (async () => {\n try {\n // Load routes from all directories in parallel\n await Promise.all(\n Array.from(routeDirectories).map(directory =>\n loadRoutesFromDirectory(directory, directory)\n )\n );\n\n // Set up optimized watching\n if (routerOptions.watchMode) {\n setupOptimizedWatching();\n }\n\n initialized = true;\n } catch (error) {\n console.error('⚠️ Failed to initialize router:', error);\n throw error;\n }\n })();\n\n return initializationPromise;\n }\n\n /**\n * Setup optimized file watching with fast updates\n */\n function setupOptimizedWatching() {\n if (!_watchers) {\n _watchers = new Map();\n }\n\n for (const directory of routeDirectories) {\n if (!_watchers.has(directory)) {\n const watcher = watchRoutes(directory, {\n debounceMs: 16, // ~60fps debouncing\n ignore: ['node_modules', '.git'],\n\n onRouteAdded: (filepath: string, addedRoutes: Route[]) => {\n // Batch process all added routes\n try {\n const changes = updateRoutesFromFile(registry, filepath, addedRoutes);\n applyMatcherChanges(changes);\n } catch (error) {\n console.error(`Error adding routes from ${directory}:`, error);\n }\n },\n\n onRouteChanged: withPerformanceTracking(\n async (filepath: string, changedRoutes: Route[]) => {\n // console.log(`${changedRoutes.length} route(s) changed in ${directory}`);\n\n try {\n console.log(`Processing changes for ${filepath}`);\n // Process all changed routes in one batch operation\n const changes = updateRoutesFromFile(registry, filepath, changedRoutes);\n\n console.log(\n `Changes detected: ${changes.added.length} added, ` +\n `${changes.changed.length} changed, ${changes.removed.length} removed`\n );\n\n // Apply matcher updates efficiently\n applyMatcherChanges(changes);\n\n console.log(\n `Route changes applied: ${changes.added.length} added, ` +\n `${changes.changed.length} changed, ${changes.removed.length} removed`\n );\n } catch (error) {\n console.error(`⚠️ Error updating routes from ${directory}:`, error);\n }\n },\n directory\n ),\n\n onRouteRemoved: (filePath: string, removedRoutes: Route[]) => {\n console.log(`File removed: ${filePath} with ${removedRoutes.length} routes`);\n\n try {\n // Remove all routes from this file\n removedRoutes.forEach(route => {\n removeRouteFromMatcher(route.path, matcher);\n });\n\n // Clear cache for removed file\n clearFileCache(filePath);\n } catch (error) {\n console.error(`⚠️ Error removing routes from ${filePath}:`, error);\n }\n },\n\n onError: (error: Error) => {\n console.error(`⚠️ Route watcher error for ${directory}:`, error);\n },\n });\n\n _watchers.set(directory, watcher);\n }\n }\n }\n\n /**\n * Setup watcher for newly added directory\n */\n function setupWatcherForNewDirectory(directory: string, prefix?: string) {\n if (!_watchers) {\n _watchers = new Map();\n }\n\n const watcher = watchRoutes(directory, {\n debounceMs: 16,\n ignore: ['node_modules', '.git'],\n\n onRouteAdded: (filePath: string, addedRoutes: Route[]) => {\n try {\n // Apply prefix to all routes\n const finalRoutes = addedRoutes.map(route =>\n prefix ? { ...route, path: `${prefix}${route.path}` } : route\n );\n\n // Batch process all added routes\n const changes = updateRoutesFromFile(registry, filePath, finalRoutes);\n applyMatcherChanges(changes);\n } catch (error) {\n console.error(`⚠️ Error adding routes from ${directory}:`, error);\n }\n },\n\n onRouteChanged: withPerformanceTracking(async (filePath: string, changedRoutes: Route[]) => {\n try {\n // Apply prefix to all routes\n const finalRoutes = changedRoutes.map(route =>\n prefix ? { ...route, path: `${prefix}${route.path}` } : route\n );\n\n // Process all changed routes in one batch operation\n const changes = updateRoutesFromFile(registry, filePath, finalRoutes);\n applyMatcherChanges(changes);\n } catch (error) {\n console.error(`⚠️ Error updating routes from ${directory}:`, error);\n }\n }, directory),\n\n onRouteRemoved: (filePath: string, removedRoutes: Route[]) => {\n try {\n removedRoutes.forEach(route => {\n const finalPath = prefix ? `${prefix}${route.path}` : route.path;\n removeRouteFromMatcher(finalPath, matcher);\n });\n clearFileCache(filePath);\n } catch (error) {\n console.error(`Error removing routes from ${filePath}:`, error);\n }\n },\n\n onError: (error: Error) => {\n console.error(`⚠️ Route watcher error for ${directory}:`, error);\n },\n });\n\n _watchers.set(directory, watcher);\n return watcher;\n }\n\n // Initialize router on creation\n initialize().catch(error => {\n console.error('⚠️ Failed to initialize router on creation:', error);\n });\n\n // Public API\n return {\n /**\n * Handle an incoming request\n */\n async handleRequest(ctx: Context) {\n // Ensure router is initialized\n if (!initialized) {\n console.log('🔄 Router not initialized, initializing...');\n await initialize();\n }\n\n const { method, path } = ctx.request;\n console.log(`\\n📥 Handling request: ${method} ${path}`);\n\n // Find matching route\n const match = matcher.match(path, method as HttpMethod);\n\n if (!match) {\n console.log(`❌ No match found for: ${method} ${path}`);\n // Handle 404 Not Found\n throw new NotFoundError('Not found');\n }\n\n console.log(`✅ Route matched: ${method} ${path}`);\n console.log(` Params: ${JSON.stringify(match.params)}`);\n\n // Check for method not allowed\n if (match.methodNotAllowed) {\n // Handle 405 Method Not Allowed\n // TODO: Add support for Method Not Allowed Error\n ctx.response.status(405).json({\n error: '❌ Method Not Allowed',\n allowed: match.allowedMethods,\n });\n\n // Set Allow header with allowed methods\n if (match.allowedMethods && match.allowedMethods.length > 0) {\n ctx.response.header('Allow', match.allowedMethods.join(', '));\n }\n\n return;\n }\n\n // Extract route parameters\n ctx.request.params = match.params;\n\n // Execute the route handler with middleware\n await executeHandler(ctx, match.route!, match.params);\n },\n\n /**\n * Get all registered routes (using optimized registry)\n */\n getRoutes() {\n return getAllRoutesFromRegistry(registry);\n },\n\n /**\n * Add a route programmatically\n */\n addRoute(route: Route) {\n const changes = updateRoutesFromFile(registry, 'programmatic', [route]);\n applyMatcherChanges(changes);\n },\n\n /**\n * Add multiple routes programmatically with batch processing\n */\n addRoutes(routes: Route[]) {\n const changes = updateRoutesFromFile(registry, 'programmatic', routes);\n applyMatcherChanges(changes);\n return changes;\n },\n\n /**\n * Add a route directory (for plugins) with optimized loading\n */\n async addRouteDirectory(directory: string, options: { prefix?: string } = {}) {\n if (routeDirectories.has(directory)) {\n console.warn(`Route directory ${directory} already registered`);\n return;\n }\n\n routeDirectories.add(directory);\n\n // If already initialized, load routes immediately\n if (initialized) {\n await loadRoutesFromDirectory(directory, directory, options.prefix);\n\n // Set up watching for this directory if in watch mode\n if (routerOptions.watchMode) {\n setupWatcherForNewDirectory(directory, options.prefix);\n }\n }\n },\n\n /**\n * Get route conflicts (using registry)\n */\n getRouteConflicts() {\n // Registry handles conflict detection internally\n // This could be enhanced to expose more detailed conflict info\n const conflicts: Array<{ path: string; sources: string[] }> = [];\n // Implementation would depend on registry's conflict tracking\n return conflicts;\n },\n\n /**\n * Close watchers and cleanup (useful for testing)\n */\n async close() {\n if (_watchers) {\n for (const watcher of _watchers.values()) {\n await watcher.close();\n }\n _watchers.clear();\n }\n },\n };\n}\n","export * from './client';\nexport * from './context';\nexport * from './errors';\nexport * from './server';\nexport * from './middleware';\nexport * from './router';\nexport * from './plugins';\nexport * from './upload';\n","/**\n * UnauthorizedError class for authentication failures\n *\n * This error is thrown when authentication is required or has failed.\n * It provides context about authentication requirements and failure reasons.\n */\n\nimport { ErrorType, BlaizeError } from '@blaize-types/errors';\n\nimport { getCurrentCorrelationId } from './correlation';\n\nimport type { UnauthorizedErrorDetails } from '@blaize-types/errors';\n\n/**\n * Error thrown when authentication is required or has failed\n *\n * Automatically sets HTTP status to 401 and provides authentication context.\n *\n * @example Basic usage:\n * ```typescript\n * throw new UnauthorizedError('Authentication required');\n * ```\n *\n * @example With authentication details:\n * ```typescript\n * throw new UnauthorizedError('Token expired', {\n * reason: 'expired_token',\n * authScheme: 'Bearer',\n * loginUrl: '/auth/login'\n * });\n * ```\n */\nexport class UnauthorizedError extends BlaizeError<UnauthorizedErrorDetails> {\n /**\n * Creates a new UnauthorizedError instance\n *\n * @param title - Human-readable error message\n * @param details - Optional authentication context\n * @param correlationId - Optional correlation ID (uses current context if not provided)\n */\n constructor(\n title: string,\n details: UnauthorizedErrorDetails | undefined = undefined,\n correlationId: string | undefined = undefined\n ) {\n super(\n ErrorType.UNAUTHORIZED,\n title,\n 401, // HTTP 401 Unauthorized\n correlationId ?? getCurrentCorrelationId(),\n details\n );\n }\n}\n","/**\n * ForbiddenError class for authorization failures\n *\n * This error is thrown when a user lacks permission to access a resource.\n * It provides context about required permissions and access control.\n */\n\nimport { BlaizeError, ErrorType } from '@blaize-types/errors';\n\nimport { getCurrentCorrelationId } from './correlation';\n\nimport type { ForbiddenErrorDetails } from '@blaize-types/errors';\n\n/**\n * Error thrown when user lacks permission to access a resource\n *\n * Automatically sets HTTP status to 403 and provides permission context.\n *\n * @example Basic usage:\n * ```typescript\n * throw new ForbiddenError('Access denied');\n * ```\n *\n * @example With permission details:\n * ```typescript\n * throw new ForbiddenError('Insufficient permissions', {\n * requiredPermission: 'admin:users:delete',\n * userPermissions: ['admin:users:read'],\n * resource: 'user-123',\n * action: 'delete'\n * });\n * ```\n */\nexport class ForbiddenError extends BlaizeError<ForbiddenErrorDetails> {\n /**\n * Creates a new ForbiddenError instance\n *\n * @param title - Human-readable error message\n * @param details - Optional permission context\n * @param correlationId - Optional correlation ID (uses current context if not provided)\n */\n constructor(\n title: string,\n details: ForbiddenErrorDetails | undefined = undefined,\n correlationId: string | undefined = undefined\n ) {\n super(\n ErrorType.FORBIDDEN,\n title,\n 403, // HTTP 403 Forbidden\n correlationId ?? getCurrentCorrelationId(),\n details\n );\n }\n}\n","/**\n * ConflictError class for resource conflicts\n *\n * This error is thrown when a resource conflict occurs, such as duplicate keys,\n * version mismatches, or concurrent modifications.\n */\n\nimport { BlaizeError, ErrorType } from '@blaize-types/errors';\n\nimport { getCurrentCorrelationId } from './correlation';\n\nimport type { ConflictErrorDetails } from '@blaize-types/errors';\n\n/**\n * Error thrown when a resource conflict occurs\n *\n * Automatically sets HTTP status to 409 and provides conflict context.\n *\n * @example Basic usage:\n * ```typescript\n * throw new ConflictError('Email already exists');\n * ```\n *\n * @example With conflict details:\n * ```typescript\n * throw new ConflictError('Version conflict', {\n * conflictType: 'version_mismatch',\n * currentVersion: '2',\n * expectedVersion: '1',\n * resolution: 'Fetch the latest version and retry'\n * });\n * ```\n */\nexport class ConflictError extends BlaizeError<ConflictErrorDetails> {\n /**\n * Creates a new ConflictError instance\n *\n * @param title - Human-readable error message\n * @param details - Optional conflict context\n * @param correlationId - Optional correlation ID (uses current context if not provided)\n */\n constructor(\n title: string,\n details: ConflictErrorDetails | undefined = undefined,\n correlationId: string | undefined = undefined\n ) {\n super(\n ErrorType.CONFLICT,\n title,\n 409, // HTTP 409 Conflict\n correlationId ?? getCurrentCorrelationId(),\n details\n );\n }\n}\n","/**\n * RateLimitError class for rate limiting violations\n *\n * This error is thrown when rate limits are exceeded.\n * It provides context about the rate limit and when requests can resume.\n */\n\nimport { BlaizeError, ErrorType } from '@blaize-types/errors';\n\nimport { getCurrentCorrelationId } from './correlation';\n\nimport type { RateLimitErrorDetails } from '@blaize-types/errors';\n\n/**\n * Error thrown when rate limits are exceeded\n *\n * Automatically sets HTTP status to 429 and provides rate limit context.\n *\n * @example Basic usage:\n * ```typescript\n * throw new RateLimitError('Too many requests');\n * ```\n *\n * @example With rate limit details:\n * ```typescript\n * throw new RateLimitError('Rate limit exceeded', {\n * limit: 100,\n * remaining: 0,\n * retryAfter: 3600,\n * window: 'hour',\n * identifier: 'user-123'\n * });\n * ```\n */\nexport class RateLimitError extends BlaizeError<RateLimitErrorDetails> {\n /**\n * Creates a new RateLimitError instance\n *\n * @param title - Human-readable error message\n * @param details - Optional rate limit context\n * @param correlationId - Optional correlation ID (uses current context if not provided)\n */\n constructor(\n title: string,\n details: RateLimitErrorDetails | undefined = undefined,\n correlationId: string | undefined = undefined\n ) {\n super(\n ErrorType.RATE_LIMITED,\n title,\n 429, // HTTP 429 Too Many Requests\n correlationId ?? getCurrentCorrelationId(),\n details\n );\n }\n}\n","import { getCurrentCorrelationId } from './correlation';\nimport { BlaizeError, ErrorType } from '../../../blaize-types/src/errors';\n\nexport class RequestTimeoutError extends BlaizeError {\n constructor(title: string, details?: unknown, correlationId?: string) {\n super(\n ErrorType.UPLOAD_TIMEOUT,\n title,\n 408,\n correlationId ?? getCurrentCorrelationId(),\n details\n );\n }\n}\n","import { getCurrentCorrelationId } from './correlation';\nimport { BlaizeError, ErrorType } from '../../../blaize-types/src/errors';\n\nexport class UnprocessableEntityError extends BlaizeError {\n constructor(title: string, details?: unknown, correlationId?: string) {\n super(\n ErrorType.UNPROCESSABLE_ENTITY,\n title,\n 422,\n correlationId ?? getCurrentCorrelationId(),\n details\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+nBO,SAAS,iBAAiB,OAAyC;AACxE,SACE,OAAO,UAAU,YACjB,UAAU,QACV,UAAU,SACV,aAAa,SACb,WAAW,SACX,OAAQ,MAAc,SAAS,YAC/B,OAAQ,MAAc,YAAY;AAEtC;AAzoBA,IA2MY,WAsDA,eAkCU;AAnStB;AAAA;AAAA;AA2MO,IAAK,YAAL,kBAAKA,eAAL;AAGL,MAAAA,WAAA,sBAAmB;AAGnB,MAAAA,WAAA,eAAY;AAGZ,MAAAA,WAAA,kBAAe;AAGf,MAAAA,WAAA,eAAY;AAGZ,MAAAA,WAAA,cAAW;AAGX,MAAAA,WAAA,kBAAe;AAGf,MAAAA,WAAA,2BAAwB;AAGxB,MAAAA,WAAA,uBAAoB;AAGpB,MAAAA,WAAA,4BAAyB;AAGzB,MAAAA,WAAA,oBAAiB;AAGjB,MAAAA,WAAA,0BAAuB;AAIvB,MAAAA,WAAA,mBAAgB;AAGhB,MAAAA,WAAA,mBAAgB;AAGhB,MAAAA,WAAA,iBAAc;AAGd,MAAAA,WAAA,gBAAa;AA9CH,aAAAA;AAAA,OAAA;AAsDL,IAAK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A,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,SAAS;AAAA;AAAA,EAGT;AACF;AAEA,IAAO,gBAAQ;","names":["ErrorType","ErrorSeverity","import_node_async_hooks","create","create","stack","config","path","import_node_async_hooks","fs","path","InternalServerError","ValidationError","PayloadTooLargeError","UnsupportedMediaTypeError","resolve","path","resolve","resolve","resolve","fs","path","module","stat","require","fs","path","path","import_zod","import_zod","import_zod","import_zod","import_zod","path","path","path","path","path","options","DEFAULT_OPTIONS","create","contextStorage","EventEmitter","create"]}
|
|
1
|
+
{"version":3,"sources":["../../../node_modules/node-forge/lib/forge.js","../../../node_modules/node-forge/lib/baseN.js","../../../node_modules/node-forge/lib/util.js","../../../node_modules/node-forge/lib/cipher.js","../../../node_modules/node-forge/lib/cipherModes.js","../../../node_modules/node-forge/lib/aes.js","../../../node_modules/node-forge/lib/oids.js","../../../node_modules/node-forge/lib/asn1.js","../../../node_modules/node-forge/lib/md.js","../../../node_modules/node-forge/lib/hmac.js","../../../node_modules/node-forge/lib/md5.js","../../../node_modules/node-forge/lib/pem.js","../../../node_modules/node-forge/lib/des.js","../../../node_modules/node-forge/lib/pbkdf2.js","../../../node_modules/node-forge/lib/sha256.js","../../../node_modules/node-forge/lib/prng.js","../../../node_modules/node-forge/lib/random.js","../../../node_modules/node-forge/lib/rc2.js","../../../node_modules/node-forge/lib/jsbn.js","../../../node_modules/node-forge/lib/sha1.js","../../../node_modules/node-forge/lib/pkcs1.js","../../../node_modules/node-forge/lib/prime.js","../../../node_modules/node-forge/lib/rsa.js","../../../node_modules/node-forge/lib/pbe.js","../../../node_modules/node-forge/lib/pkcs7asn1.js","../../../node_modules/node-forge/lib/mgf1.js","../../../node_modules/node-forge/lib/mgf.js","../../../node_modules/node-forge/lib/pss.js","../../../node_modules/node-forge/lib/x509.js","../../../node_modules/node-forge/lib/pkcs12.js","../../../node_modules/node-forge/lib/pki.js","../../../node_modules/node-forge/lib/tls.js","../../../node_modules/node-forge/lib/aesCipherSuites.js","../../../node_modules/node-forge/lib/sha512.js","../../../node_modules/node-forge/lib/asn1-validator.js","../../../node_modules/node-forge/lib/ed25519.js","../../../node_modules/node-forge/lib/kem.js","../../../node_modules/node-forge/lib/log.js","../../../node_modules/node-forge/lib/md.all.js","../../../node_modules/node-forge/lib/pkcs7.js","../../../node_modules/node-forge/lib/ssh.js","../../../node_modules/node-forge/lib/index.js","../../../node_modules/selfsigned/index.js","../../blaize-types/src/errors.ts","../src/errors/correlation.ts","../src/errors/internal-server-error.ts","../src/errors/validation-error.ts","../src/errors/payload-too-large-error.ts","../src/errors/unsupported-media-type-error.ts","../src/index.ts","../src/middleware/execute.ts","../src/middleware/compose.ts","../src/middleware/create.ts","../src/plugins/create.ts","../src/router/create.ts","../src/config.ts","../src/router/discovery/parser.ts","../src/server/create.ts","../src/server/start.ts","../src/server/dev-certificate.ts","../src/context/errors.ts","../src/context/store.ts","../src/upload/multipart-parser.ts","../src/upload/utils.ts","../src/context/create.ts","../src/errors/not-found-error.ts","../src/errors/boundary.ts","../src/middleware/error-boundary.ts","../src/server/request-handler.ts","../src/server/stop.ts","../src/server/validation.ts","../src/plugins/lifecycle.ts","../src/plugins/errors.ts","../src/plugins/validation.ts","../src/router/discovery/cache.ts","../src/router/discovery/loader.ts","../src/router/discovery/parallel.ts","../src/router/discovery/finder.ts","../src/router/discovery/profiler.ts","../src/router/discovery/watchers.ts","../../../node_modules/chokidar/esm/index.js","../../../node_modules/chokidar/node_modules/readdirp/esm/index.js","../../../node_modules/chokidar/esm/handler.js","../src/router/validation/schema.ts","../src/router/validation/body.ts","../src/router/validation/params.ts","../src/router/validation/query.ts","../src/router/validation/response.ts","../src/router/handlers/executor.ts","../src/router/matching/params.ts","../src/router/matching/matcher.ts","../src/router/registry/fast-registry.ts","../src/router/utils/matching-helpers.ts","../src/router/router.ts","../../blaize-types/src/index.ts","../src/errors/unauthorized-error.ts","../src/errors/forbidden-error.ts","../src/errors/conflict-error.ts","../src/errors/rate-limit-error.ts","../src/errors/request-timeout-error.ts","../src/errors/unprocessable-entity-error.ts"],"sourcesContent":["/**\n * Node.js module for Forge.\n *\n * @author Dave Longley\n *\n * Copyright 2011-2016 Digital Bazaar, Inc.\n */\nmodule.exports = {\n // default options\n options: {\n usePureJavaScript: false\n }\n};\n","/**\n * Base-N/Base-X encoding/decoding functions.\n *\n * Original implementation from base-x:\n * https://github.com/cryptocoinjs/base-x\n *\n * Which is MIT licensed:\n *\n * The MIT License (MIT)\n *\n * Copyright base-x contributors (c) 2016\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\nvar api = {};\nmodule.exports = api;\n\n// baseN alphabet indexes\nvar _reverseAlphabets = {};\n\n/**\n * BaseN-encodes a Uint8Array using the given alphabet.\n *\n * @param input the Uint8Array to encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the baseN-encoded output string.\n */\napi.encode = function(input, alphabet, maxline) {\n if(typeof alphabet !== 'string') {\n throw new TypeError('\"alphabet\" must be a string.');\n }\n if(maxline !== undefined && typeof maxline !== 'number') {\n throw new TypeError('\"maxline\" must be a number.');\n }\n\n var output = '';\n\n if(!(input instanceof Uint8Array)) {\n // assume forge byte buffer\n output = _encodeWithByteBuffer(input, alphabet);\n } else {\n var i = 0;\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var digits = [0];\n for(i = 0; i < input.length; ++i) {\n for(var j = 0, carry = input[i]; j < digits.length; ++j) {\n carry += digits[j] << 8;\n digits[j] = carry % base;\n carry = (carry / base) | 0;\n }\n\n while(carry > 0) {\n digits.push(carry % base);\n carry = (carry / base) | 0;\n }\n }\n\n // deal with leading zeros\n for(i = 0; input[i] === 0 && i < input.length - 1; ++i) {\n output += first;\n }\n // convert digits to a string\n for(i = digits.length - 1; i >= 0; --i) {\n output += alphabet[digits[i]];\n }\n }\n\n if(maxline) {\n var regex = new RegExp('.{1,' + maxline + '}', 'g');\n output = output.match(regex).join('\\r\\n');\n }\n\n return output;\n};\n\n/**\n * Decodes a baseN-encoded (using the given alphabet) string to a\n * Uint8Array.\n *\n * @param input the baseN-encoded input string.\n *\n * @return the Uint8Array.\n */\napi.decode = function(input, alphabet) {\n if(typeof input !== 'string') {\n throw new TypeError('\"input\" must be a string.');\n }\n if(typeof alphabet !== 'string') {\n throw new TypeError('\"alphabet\" must be a string.');\n }\n\n var table = _reverseAlphabets[alphabet];\n if(!table) {\n // compute reverse alphabet\n table = _reverseAlphabets[alphabet] = [];\n for(var i = 0; i < alphabet.length; ++i) {\n table[alphabet.charCodeAt(i)] = i;\n }\n }\n\n // remove whitespace characters\n input = input.replace(/\\s/g, '');\n\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var bytes = [0];\n for(var i = 0; i < input.length; i++) {\n var value = table[input.charCodeAt(i)];\n if(value === undefined) {\n return;\n }\n\n for(var j = 0, carry = value; j < bytes.length; ++j) {\n carry += bytes[j] * base;\n bytes[j] = carry & 0xff;\n carry >>= 8;\n }\n\n while(carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n\n // deal with leading zeros\n for(var k = 0; input[k] === first && k < input.length - 1; ++k) {\n bytes.push(0);\n }\n\n if(typeof Buffer !== 'undefined') {\n return Buffer.from(bytes.reverse());\n }\n\n return new Uint8Array(bytes.reverse());\n};\n\nfunction _encodeWithByteBuffer(input, alphabet) {\n var i = 0;\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var digits = [0];\n for(i = 0; i < input.length(); ++i) {\n for(var j = 0, carry = input.at(i); j < digits.length; ++j) {\n carry += digits[j] << 8;\n digits[j] = carry % base;\n carry = (carry / base) | 0;\n }\n\n while(carry > 0) {\n digits.push(carry % base);\n carry = (carry / base) | 0;\n }\n }\n\n var output = '';\n\n // deal with leading zeros\n for(i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) {\n output += first;\n }\n // convert digits to a string\n for(i = digits.length - 1; i >= 0; --i) {\n output += alphabet[digits[i]];\n }\n\n return output;\n}\n","/**\n * Utility functions for web applications.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2018 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nvar baseN = require('./baseN');\n\n/* Utilities API */\nvar util = module.exports = forge.util = forge.util || {};\n\n// define setImmediate and nextTick\n(function() {\n // use native nextTick (unless we're in webpack)\n // webpack (or better node-libs-browser polyfill) sets process.browser.\n // this way we can detect webpack properly\n if(typeof process !== 'undefined' && process.nextTick && !process.browser) {\n util.nextTick = process.nextTick;\n if(typeof setImmediate === 'function') {\n util.setImmediate = setImmediate;\n } else {\n // polyfill setImmediate with nextTick, older versions of node\n // (those w/o setImmediate) won't totally starve IO\n util.setImmediate = util.nextTick;\n }\n return;\n }\n\n // polyfill nextTick with native setImmediate\n if(typeof setImmediate === 'function') {\n util.setImmediate = function() { return setImmediate.apply(undefined, arguments); };\n util.nextTick = function(callback) {\n return setImmediate(callback);\n };\n return;\n }\n\n /* Note: A polyfill upgrade pattern is used here to allow combining\n polyfills. For example, MutationObserver is fast, but blocks UI updates,\n so it needs to allow UI updates periodically, so it falls back on\n postMessage or setTimeout. */\n\n // polyfill with setTimeout\n util.setImmediate = function(callback) {\n setTimeout(callback, 0);\n };\n\n // upgrade polyfill to use postMessage\n if(typeof window !== 'undefined' &&\n typeof window.postMessage === 'function') {\n var msg = 'forge.setImmediate';\n var callbacks = [];\n util.setImmediate = function(callback) {\n callbacks.push(callback);\n // only send message when one hasn't been sent in\n // the current turn of the event loop\n if(callbacks.length === 1) {\n window.postMessage(msg, '*');\n }\n };\n function handler(event) {\n if(event.source === window && event.data === msg) {\n event.stopPropagation();\n var copy = callbacks.slice();\n callbacks.length = 0;\n copy.forEach(function(callback) {\n callback();\n });\n }\n }\n window.addEventListener('message', handler, true);\n }\n\n // upgrade polyfill to use MutationObserver\n if(typeof MutationObserver !== 'undefined') {\n // polyfill with MutationObserver\n var now = Date.now();\n var attr = true;\n var div = document.createElement('div');\n var callbacks = [];\n new MutationObserver(function() {\n var copy = callbacks.slice();\n callbacks.length = 0;\n copy.forEach(function(callback) {\n callback();\n });\n }).observe(div, {attributes: true});\n var oldSetImmediate = util.setImmediate;\n util.setImmediate = function(callback) {\n if(Date.now() - now > 15) {\n now = Date.now();\n oldSetImmediate(callback);\n } else {\n callbacks.push(callback);\n // only trigger observer when it hasn't been triggered in\n // the current turn of the event loop\n if(callbacks.length === 1) {\n div.setAttribute('a', attr = !attr);\n }\n }\n };\n }\n\n util.nextTick = util.setImmediate;\n})();\n\n// check if running under Node.js\nutil.isNodejs =\n typeof process !== 'undefined' && process.versions && process.versions.node;\n\n\n// 'self' will also work in Web Workers (instance of WorkerGlobalScope) while\n// it will point to `window` in the main thread.\n// To remain compatible with older browsers, we fall back to 'window' if 'self'\n// is not available.\nutil.globalScope = (function() {\n if(util.isNodejs) {\n return global;\n }\n\n return typeof self === 'undefined' ? window : self;\n})();\n\n// define isArray\nutil.isArray = Array.isArray || function(x) {\n return Object.prototype.toString.call(x) === '[object Array]';\n};\n\n// define isArrayBuffer\nutil.isArrayBuffer = function(x) {\n return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer;\n};\n\n// define isArrayBufferView\nutil.isArrayBufferView = function(x) {\n return x && util.isArrayBuffer(x.buffer) && x.byteLength !== undefined;\n};\n\n/**\n * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for\n * algorithms where bit manipulation, JavaScript limitations, and/or algorithm\n * design only allow for byte operations of a limited size.\n *\n * @param n number of bits.\n *\n * Throw Error if n invalid.\n */\nfunction _checkBitsParam(n) {\n if(!(n === 8 || n === 16 || n === 24 || n === 32)) {\n throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n);\n }\n}\n\n// TODO: set ByteBuffer to best available backing\nutil.ByteBuffer = ByteStringBuffer;\n\n/** Buffer w/BinaryString backing */\n\n/**\n * Constructor for a binary string backed byte buffer.\n *\n * @param [b] the bytes to wrap (either encoded as string, one byte per\n * character, or as an ArrayBuffer or Typed Array).\n */\nfunction ByteStringBuffer(b) {\n // TODO: update to match DataBuffer API\n\n // the data in this buffer\n this.data = '';\n // the pointer for reading from this buffer\n this.read = 0;\n\n if(typeof b === 'string') {\n this.data = b;\n } else if(util.isArrayBuffer(b) || util.isArrayBufferView(b)) {\n if(typeof Buffer !== 'undefined' && b instanceof Buffer) {\n this.data = b.toString('binary');\n } else {\n // convert native buffer to forge buffer\n // FIXME: support native buffers internally instead\n var arr = new Uint8Array(b);\n try {\n this.data = String.fromCharCode.apply(null, arr);\n } catch(e) {\n for(var i = 0; i < arr.length; ++i) {\n this.putByte(arr[i]);\n }\n }\n }\n } else if(b instanceof ByteStringBuffer ||\n (typeof b === 'object' && typeof b.data === 'string' &&\n typeof b.read === 'number')) {\n // copy existing buffer\n this.data = b.data;\n this.read = b.read;\n }\n\n // used for v8 optimization\n this._constructedStringLength = 0;\n}\nutil.ByteStringBuffer = ByteStringBuffer;\n\n/* Note: This is an optimization for V8-based browsers. When V8 concatenates\n a string, the strings are only joined logically using a \"cons string\" or\n \"constructed/concatenated string\". These containers keep references to one\n another and can result in very large memory usage. For example, if a 2MB\n string is constructed by concatenating 4 bytes together at a time, the\n memory usage will be ~44MB; so ~22x increase. The strings are only joined\n together when an operation requiring their joining takes place, such as\n substr(). This function is called when adding data to this buffer to ensure\n these types of strings are periodically joined to reduce the memory\n footprint. */\nvar _MAX_CONSTRUCTED_STRING_LENGTH = 4096;\nutil.ByteStringBuffer.prototype._optimizeConstructedString = function(x) {\n this._constructedStringLength += x;\n if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) {\n // this substr() should cause the constructed string to join\n this.data.substr(0, 1);\n this._constructedStringLength = 0;\n }\n};\n\n/**\n * Gets the number of bytes in this buffer.\n *\n * @return the number of bytes in this buffer.\n */\nutil.ByteStringBuffer.prototype.length = function() {\n return this.data.length - this.read;\n};\n\n/**\n * Gets whether or not this buffer is empty.\n *\n * @return true if this buffer is empty, false if not.\n */\nutil.ByteStringBuffer.prototype.isEmpty = function() {\n return this.length() <= 0;\n};\n\n/**\n * Puts a byte in this buffer.\n *\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putByte = function(b) {\n return this.putBytes(String.fromCharCode(b));\n};\n\n/**\n * Puts a byte in this buffer N times.\n *\n * @param b the byte to put.\n * @param n the number of bytes of value b to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.fillWithByte = function(b, n) {\n b = String.fromCharCode(b);\n var d = this.data;\n while(n > 0) {\n if(n & 1) {\n d += b;\n }\n n >>>= 1;\n if(n > 0) {\n b += b;\n }\n }\n this.data = d;\n this._optimizeConstructedString(n);\n return this;\n};\n\n/**\n * Puts bytes in this buffer.\n *\n * @param bytes the bytes (as a binary encoded string) to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putBytes = function(bytes) {\n this.data += bytes;\n this._optimizeConstructedString(bytes.length);\n return this;\n};\n\n/**\n * Puts a UTF-16 encoded string into this buffer.\n *\n * @param str the string to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putString = function(str) {\n return this.putBytes(util.encodeUtf8(str));\n};\n\n/**\n * Puts a 16-bit integer in this buffer in big-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt16 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 24-bit integer in this buffer in big-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt24 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 32-bit integer in this buffer in big-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt32 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 24 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 16-bit integer in this buffer in little-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt16Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF));\n};\n\n/**\n * Puts a 24-bit integer in this buffer in little-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt24Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF));\n};\n\n/**\n * Puts a 32-bit integer in this buffer in little-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt32Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 24 & 0xFF));\n};\n\n/**\n * Puts an n-bit integer in this buffer in big-endian order.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt = function(i, n) {\n _checkBitsParam(n);\n var bytes = '';\n do {\n n -= 8;\n bytes += String.fromCharCode((i >> n) & 0xFF);\n } while(n > 0);\n return this.putBytes(bytes);\n};\n\n/**\n * Puts a signed n-bit integer in this buffer in big-endian order. Two's\n * complement representation is used.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putSignedInt = function(i, n) {\n // putInt checks n\n if(i < 0) {\n i += 2 << (n - 1);\n }\n return this.putInt(i, n);\n};\n\n/**\n * Puts the given buffer into this buffer.\n *\n * @param buffer the buffer to put into this one.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putBuffer = function(buffer) {\n return this.putBytes(buffer.getBytes());\n};\n\n/**\n * Gets a byte from this buffer and advances the read pointer by 1.\n *\n * @return the byte.\n */\nutil.ByteStringBuffer.prototype.getByte = function() {\n return this.data.charCodeAt(this.read++);\n};\n\n/**\n * Gets a uint16 from this buffer in big-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.ByteStringBuffer.prototype.getInt16 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 8 ^\n this.data.charCodeAt(this.read + 1));\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in big-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.ByteStringBuffer.prototype.getInt24 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 16 ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2));\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in big-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.ByteStringBuffer.prototype.getInt32 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 24 ^\n this.data.charCodeAt(this.read + 1) << 16 ^\n this.data.charCodeAt(this.read + 2) << 8 ^\n this.data.charCodeAt(this.read + 3));\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets a uint16 from this buffer in little-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.ByteStringBuffer.prototype.getInt16Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in little-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.ByteStringBuffer.prototype.getInt24Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2) << 16);\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in little-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.ByteStringBuffer.prototype.getInt32Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2) << 16 ^\n this.data.charCodeAt(this.read + 3) << 24);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets an n-bit integer from this buffer in big-endian order and advances the\n * read pointer by ceil(n/8).\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.ByteStringBuffer.prototype.getInt = function(n) {\n _checkBitsParam(n);\n var rval = 0;\n do {\n // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.\n rval = (rval << 8) + this.data.charCodeAt(this.read++);\n n -= 8;\n } while(n > 0);\n return rval;\n};\n\n/**\n * Gets a signed n-bit integer from this buffer in big-endian order, using\n * two's complement, and advances the read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.ByteStringBuffer.prototype.getSignedInt = function(n) {\n // getInt checks n\n var x = this.getInt(n);\n var max = 2 << (n - 2);\n if(x >= max) {\n x -= max << 1;\n }\n return x;\n};\n\n/**\n * Reads bytes out as a binary encoded string and clears them from the\n * buffer. Note that the resulting string is binary encoded (in node.js this\n * encoding is referred to as `binary`, it is *not* `utf8`).\n *\n * @param count the number of bytes to read, undefined or null for all.\n *\n * @return a binary encoded string of bytes.\n */\nutil.ByteStringBuffer.prototype.getBytes = function(count) {\n var rval;\n if(count) {\n // read count bytes\n count = Math.min(this.length(), count);\n rval = this.data.slice(this.read, this.read + count);\n this.read += count;\n } else if(count === 0) {\n rval = '';\n } else {\n // read all bytes, optimize to only copy when needed\n rval = (this.read === 0) ? this.data : this.data.slice(this.read);\n this.clear();\n }\n return rval;\n};\n\n/**\n * Gets a binary encoded string of the bytes from this buffer without\n * modifying the read pointer.\n *\n * @param count the number of bytes to get, omit to get all.\n *\n * @return a string full of binary encoded characters.\n */\nutil.ByteStringBuffer.prototype.bytes = function(count) {\n return (typeof(count) === 'undefined' ?\n this.data.slice(this.read) :\n this.data.slice(this.read, this.read + count));\n};\n\n/**\n * Gets a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n *\n * @return the byte.\n */\nutil.ByteStringBuffer.prototype.at = function(i) {\n return this.data.charCodeAt(this.read + i);\n};\n\n/**\n * Puts a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.setAt = function(i, b) {\n this.data = this.data.substr(0, this.read + i) +\n String.fromCharCode(b) +\n this.data.substr(this.read + i + 1);\n return this;\n};\n\n/**\n * Gets the last byte without modifying the read pointer.\n *\n * @return the last byte.\n */\nutil.ByteStringBuffer.prototype.last = function() {\n return this.data.charCodeAt(this.data.length - 1);\n};\n\n/**\n * Creates a copy of this buffer.\n *\n * @return the copy.\n */\nutil.ByteStringBuffer.prototype.copy = function() {\n var c = util.createBuffer(this.data);\n c.read = this.read;\n return c;\n};\n\n/**\n * Compacts this buffer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.compact = function() {\n if(this.read > 0) {\n this.data = this.data.slice(this.read);\n this.read = 0;\n }\n return this;\n};\n\n/**\n * Clears this buffer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.clear = function() {\n this.data = '';\n this.read = 0;\n return this;\n};\n\n/**\n * Shortens this buffer by triming bytes off of the end of this buffer.\n *\n * @param count the number of bytes to trim off.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.truncate = function(count) {\n var len = Math.max(0, this.length() - count);\n this.data = this.data.substr(this.read, len);\n this.read = 0;\n return this;\n};\n\n/**\n * Converts this buffer to a hexadecimal string.\n *\n * @return a hexadecimal string.\n */\nutil.ByteStringBuffer.prototype.toHex = function() {\n var rval = '';\n for(var i = this.read; i < this.data.length; ++i) {\n var b = this.data.charCodeAt(i);\n if(b < 16) {\n rval += '0';\n }\n rval += b.toString(16);\n }\n return rval;\n};\n\n/**\n * Converts this buffer to a UTF-16 string (standard JavaScript string).\n *\n * @return a UTF-16 string.\n */\nutil.ByteStringBuffer.prototype.toString = function() {\n return util.decodeUtf8(this.bytes());\n};\n\n/** End Buffer w/BinaryString backing */\n\n/** Buffer w/UInt8Array backing */\n\n/**\n * FIXME: Experimental. Do not use yet.\n *\n * Constructor for an ArrayBuffer-backed byte buffer.\n *\n * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a\n * TypedArray.\n *\n * If a string is given, its encoding should be provided as an option,\n * otherwise it will default to 'binary'. A 'binary' string is encoded such\n * that each character is one byte in length and size.\n *\n * If an ArrayBuffer, DataView, or TypedArray is given, it will be used\n * *directly* without any copying. Note that, if a write to the buffer requires\n * more space, the buffer will allocate a new backing ArrayBuffer to\n * accommodate. The starting read and write offsets for the buffer may be\n * given as options.\n *\n * @param [b] the initial bytes for this buffer.\n * @param options the options to use:\n * [readOffset] the starting read offset to use (default: 0).\n * [writeOffset] the starting write offset to use (default: the\n * length of the first parameter).\n * [growSize] the minimum amount, in bytes, to grow the buffer by to\n * accommodate writes (default: 1024).\n * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the\n * first parameter, if it is a string (default: 'binary').\n */\nfunction DataBuffer(b, options) {\n // default options\n options = options || {};\n\n // pointers for read from/write to buffer\n this.read = options.readOffset || 0;\n this.growSize = options.growSize || 1024;\n\n var isArrayBuffer = util.isArrayBuffer(b);\n var isArrayBufferView = util.isArrayBufferView(b);\n if(isArrayBuffer || isArrayBufferView) {\n // use ArrayBuffer directly\n if(isArrayBuffer) {\n this.data = new DataView(b);\n } else {\n // TODO: adjust read/write offset based on the type of view\n // or specify that this must be done in the options ... that the\n // offsets are byte-based\n this.data = new DataView(b.buffer, b.byteOffset, b.byteLength);\n }\n this.write = ('writeOffset' in options ?\n options.writeOffset : this.data.byteLength);\n return;\n }\n\n // initialize to empty array buffer and add any given bytes using putBytes\n this.data = new DataView(new ArrayBuffer(0));\n this.write = 0;\n\n if(b !== null && b !== undefined) {\n this.putBytes(b);\n }\n\n if('writeOffset' in options) {\n this.write = options.writeOffset;\n }\n}\nutil.DataBuffer = DataBuffer;\n\n/**\n * Gets the number of bytes in this buffer.\n *\n * @return the number of bytes in this buffer.\n */\nutil.DataBuffer.prototype.length = function() {\n return this.write - this.read;\n};\n\n/**\n * Gets whether or not this buffer is empty.\n *\n * @return true if this buffer is empty, false if not.\n */\nutil.DataBuffer.prototype.isEmpty = function() {\n return this.length() <= 0;\n};\n\n/**\n * Ensures this buffer has enough empty space to accommodate the given number\n * of bytes. An optional parameter may be given that indicates a minimum\n * amount to grow the buffer if necessary. If the parameter is not given,\n * the buffer will be grown by some previously-specified default amount\n * or heuristic.\n *\n * @param amount the number of bytes to accommodate.\n * @param [growSize] the minimum amount, in bytes, to grow the buffer by if\n * necessary.\n */\nutil.DataBuffer.prototype.accommodate = function(amount, growSize) {\n if(this.length() >= amount) {\n return this;\n }\n growSize = Math.max(growSize || this.growSize, amount);\n\n // grow buffer\n var src = new Uint8Array(\n this.data.buffer, this.data.byteOffset, this.data.byteLength);\n var dst = new Uint8Array(this.length() + growSize);\n dst.set(src);\n this.data = new DataView(dst.buffer);\n\n return this;\n};\n\n/**\n * Puts a byte in this buffer.\n *\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putByte = function(b) {\n this.accommodate(1);\n this.data.setUint8(this.write++, b);\n return this;\n};\n\n/**\n * Puts a byte in this buffer N times.\n *\n * @param b the byte to put.\n * @param n the number of bytes of value b to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.fillWithByte = function(b, n) {\n this.accommodate(n);\n for(var i = 0; i < n; ++i) {\n this.data.setUint8(b);\n }\n return this;\n};\n\n/**\n * Puts bytes in this buffer. The bytes may be given as a string, an\n * ArrayBuffer, a DataView, or a TypedArray.\n *\n * @param bytes the bytes to put.\n * @param [encoding] the encoding for the first parameter ('binary', 'utf8',\n * 'utf16', 'hex'), if it is a string (default: 'binary').\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putBytes = function(bytes, encoding) {\n if(util.isArrayBufferView(bytes)) {\n var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n var len = src.byteLength - src.byteOffset;\n this.accommodate(len);\n var dst = new Uint8Array(this.data.buffer, this.write);\n dst.set(src);\n this.write += len;\n return this;\n }\n\n if(util.isArrayBuffer(bytes)) {\n var src = new Uint8Array(bytes);\n this.accommodate(src.byteLength);\n var dst = new Uint8Array(this.data.buffer);\n dst.set(src, this.write);\n this.write += src.byteLength;\n return this;\n }\n\n // bytes is a util.DataBuffer or equivalent\n if(bytes instanceof util.DataBuffer ||\n (typeof bytes === 'object' &&\n typeof bytes.read === 'number' && typeof bytes.write === 'number' &&\n util.isArrayBufferView(bytes.data))) {\n var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length());\n this.accommodate(src.byteLength);\n var dst = new Uint8Array(bytes.data.byteLength, this.write);\n dst.set(src);\n this.write += src.byteLength;\n return this;\n }\n\n if(bytes instanceof util.ByteStringBuffer) {\n // copy binary string and process as the same as a string parameter below\n bytes = bytes.data;\n encoding = 'binary';\n }\n\n // string conversion\n encoding = encoding || 'binary';\n if(typeof bytes === 'string') {\n var view;\n\n // decode from string\n if(encoding === 'hex') {\n this.accommodate(Math.ceil(bytes.length / 2));\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.hex.decode(bytes, view, this.write);\n return this;\n }\n if(encoding === 'base64') {\n this.accommodate(Math.ceil(bytes.length / 4) * 3);\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.base64.decode(bytes, view, this.write);\n return this;\n }\n\n // encode text as UTF-8 bytes\n if(encoding === 'utf8') {\n // encode as UTF-8 then decode string as raw binary\n bytes = util.encodeUtf8(bytes);\n encoding = 'binary';\n }\n\n // decode string as raw binary\n if(encoding === 'binary' || encoding === 'raw') {\n // one byte per character\n this.accommodate(bytes.length);\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.raw.decode(view);\n return this;\n }\n\n // encode text as UTF-16 bytes\n if(encoding === 'utf16') {\n // two bytes per character\n this.accommodate(bytes.length * 2);\n view = new Uint16Array(this.data.buffer, this.write);\n this.write += util.text.utf16.encode(view);\n return this;\n }\n\n throw new Error('Invalid encoding: ' + encoding);\n }\n\n throw Error('Invalid parameter: ' + bytes);\n};\n\n/**\n * Puts the given buffer into this buffer.\n *\n * @param buffer the buffer to put into this one.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putBuffer = function(buffer) {\n this.putBytes(buffer);\n buffer.clear();\n return this;\n};\n\n/**\n * Puts a string into this buffer.\n *\n * @param str the string to put.\n * @param [encoding] the encoding for the string (default: 'utf16').\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putString = function(str) {\n return this.putBytes(str, 'utf16');\n};\n\n/**\n * Puts a 16-bit integer in this buffer in big-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt16 = function(i) {\n this.accommodate(2);\n this.data.setInt16(this.write, i);\n this.write += 2;\n return this;\n};\n\n/**\n * Puts a 24-bit integer in this buffer in big-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt24 = function(i) {\n this.accommodate(3);\n this.data.setInt16(this.write, i >> 8 & 0xFFFF);\n this.data.setInt8(this.write, i >> 16 & 0xFF);\n this.write += 3;\n return this;\n};\n\n/**\n * Puts a 32-bit integer in this buffer in big-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt32 = function(i) {\n this.accommodate(4);\n this.data.setInt32(this.write, i);\n this.write += 4;\n return this;\n};\n\n/**\n * Puts a 16-bit integer in this buffer in little-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt16Le = function(i) {\n this.accommodate(2);\n this.data.setInt16(this.write, i, true);\n this.write += 2;\n return this;\n};\n\n/**\n * Puts a 24-bit integer in this buffer in little-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt24Le = function(i) {\n this.accommodate(3);\n this.data.setInt8(this.write, i >> 16 & 0xFF);\n this.data.setInt16(this.write, i >> 8 & 0xFFFF, true);\n this.write += 3;\n return this;\n};\n\n/**\n * Puts a 32-bit integer in this buffer in little-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt32Le = function(i) {\n this.accommodate(4);\n this.data.setInt32(this.write, i, true);\n this.write += 4;\n return this;\n};\n\n/**\n * Puts an n-bit integer in this buffer in big-endian order.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt = function(i, n) {\n _checkBitsParam(n);\n this.accommodate(n / 8);\n do {\n n -= 8;\n this.data.setInt8(this.write++, (i >> n) & 0xFF);\n } while(n > 0);\n return this;\n};\n\n/**\n * Puts a signed n-bit integer in this buffer in big-endian order. Two's\n * complement representation is used.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putSignedInt = function(i, n) {\n _checkBitsParam(n);\n this.accommodate(n / 8);\n if(i < 0) {\n i += 2 << (n - 1);\n }\n return this.putInt(i, n);\n};\n\n/**\n * Gets a byte from this buffer and advances the read pointer by 1.\n *\n * @return the byte.\n */\nutil.DataBuffer.prototype.getByte = function() {\n return this.data.getInt8(this.read++);\n};\n\n/**\n * Gets a uint16 from this buffer in big-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.DataBuffer.prototype.getInt16 = function() {\n var rval = this.data.getInt16(this.read);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in big-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.DataBuffer.prototype.getInt24 = function() {\n var rval = (\n this.data.getInt16(this.read) << 8 ^\n this.data.getInt8(this.read + 2));\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in big-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.DataBuffer.prototype.getInt32 = function() {\n var rval = this.data.getInt32(this.read);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets a uint16 from this buffer in little-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.DataBuffer.prototype.getInt16Le = function() {\n var rval = this.data.getInt16(this.read, true);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in little-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.DataBuffer.prototype.getInt24Le = function() {\n var rval = (\n this.data.getInt8(this.read) ^\n this.data.getInt16(this.read + 1, true) << 8);\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in little-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.DataBuffer.prototype.getInt32Le = function() {\n var rval = this.data.getInt32(this.read, true);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets an n-bit integer from this buffer in big-endian order and advances the\n * read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.DataBuffer.prototype.getInt = function(n) {\n _checkBitsParam(n);\n var rval = 0;\n do {\n // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.\n rval = (rval << 8) + this.data.getInt8(this.read++);\n n -= 8;\n } while(n > 0);\n return rval;\n};\n\n/**\n * Gets a signed n-bit integer from this buffer in big-endian order, using\n * two's complement, and advances the read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.DataBuffer.prototype.getSignedInt = function(n) {\n // getInt checks n\n var x = this.getInt(n);\n var max = 2 << (n - 2);\n if(x >= max) {\n x -= max << 1;\n }\n return x;\n};\n\n/**\n * Reads bytes out as a binary encoded string and clears them from the\n * buffer.\n *\n * @param count the number of bytes to read, undefined or null for all.\n *\n * @return a binary encoded string of bytes.\n */\nutil.DataBuffer.prototype.getBytes = function(count) {\n // TODO: deprecate this method, it is poorly named and\n // this.toString('binary') replaces it\n // add a toTypedArray()/toArrayBuffer() function\n var rval;\n if(count) {\n // read count bytes\n count = Math.min(this.length(), count);\n rval = this.data.slice(this.read, this.read + count);\n this.read += count;\n } else if(count === 0) {\n rval = '';\n } else {\n // read all bytes, optimize to only copy when needed\n rval = (this.read === 0) ? this.data : this.data.slice(this.read);\n this.clear();\n }\n return rval;\n};\n\n/**\n * Gets a binary encoded string of the bytes from this buffer without\n * modifying the read pointer.\n *\n * @param count the number of bytes to get, omit to get all.\n *\n * @return a string full of binary encoded characters.\n */\nutil.DataBuffer.prototype.bytes = function(count) {\n // TODO: deprecate this method, it is poorly named, add \"getString()\"\n return (typeof(count) === 'undefined' ?\n this.data.slice(this.read) :\n this.data.slice(this.read, this.read + count));\n};\n\n/**\n * Gets a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n *\n * @return the byte.\n */\nutil.DataBuffer.prototype.at = function(i) {\n return this.data.getUint8(this.read + i);\n};\n\n/**\n * Puts a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.setAt = function(i, b) {\n this.data.setUint8(i, b);\n return this;\n};\n\n/**\n * Gets the last byte without modifying the read pointer.\n *\n * @return the last byte.\n */\nutil.DataBuffer.prototype.last = function() {\n return this.data.getUint8(this.write - 1);\n};\n\n/**\n * Creates a copy of this buffer.\n *\n * @return the copy.\n */\nutil.DataBuffer.prototype.copy = function() {\n return new util.DataBuffer(this);\n};\n\n/**\n * Compacts this buffer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.compact = function() {\n if(this.read > 0) {\n var src = new Uint8Array(this.data.buffer, this.read);\n var dst = new Uint8Array(src.byteLength);\n dst.set(src);\n this.data = new DataView(dst);\n this.write -= this.read;\n this.read = 0;\n }\n return this;\n};\n\n/**\n * Clears this buffer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.clear = function() {\n this.data = new DataView(new ArrayBuffer(0));\n this.read = this.write = 0;\n return this;\n};\n\n/**\n * Shortens this buffer by triming bytes off of the end of this buffer.\n *\n * @param count the number of bytes to trim off.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.truncate = function(count) {\n this.write = Math.max(0, this.length() - count);\n this.read = Math.min(this.read, this.write);\n return this;\n};\n\n/**\n * Converts this buffer to a hexadecimal string.\n *\n * @return a hexadecimal string.\n */\nutil.DataBuffer.prototype.toHex = function() {\n var rval = '';\n for(var i = this.read; i < this.data.byteLength; ++i) {\n var b = this.data.getUint8(i);\n if(b < 16) {\n rval += '0';\n }\n rval += b.toString(16);\n }\n return rval;\n};\n\n/**\n * Converts this buffer to a string, using the given encoding. If no\n * encoding is given, 'utf8' (UTF-8) is used.\n *\n * @param [encoding] the encoding to use: 'binary', 'utf8', 'utf16', 'hex',\n * 'base64' (default: 'utf8').\n *\n * @return a string representation of the bytes in this buffer.\n */\nutil.DataBuffer.prototype.toString = function(encoding) {\n var view = new Uint8Array(this.data, this.read, this.length());\n encoding = encoding || 'utf8';\n\n // encode to string\n if(encoding === 'binary' || encoding === 'raw') {\n return util.binary.raw.encode(view);\n }\n if(encoding === 'hex') {\n return util.binary.hex.encode(view);\n }\n if(encoding === 'base64') {\n return util.binary.base64.encode(view);\n }\n\n // decode to text\n if(encoding === 'utf8') {\n return util.text.utf8.decode(view);\n }\n if(encoding === 'utf16') {\n return util.text.utf16.decode(view);\n }\n\n throw new Error('Invalid encoding: ' + encoding);\n};\n\n/** End Buffer w/UInt8Array backing */\n\n/**\n * Creates a buffer that stores bytes. A value may be given to populate the\n * buffer with data. This value can either be string of encoded bytes or a\n * regular string of characters. When passing a string of binary encoded\n * bytes, the encoding `raw` should be given. This is also the default. When\n * passing a string of characters, the encoding `utf8` should be given.\n *\n * @param [input] a string with encoded bytes to store in the buffer.\n * @param [encoding] (default: 'raw', other: 'utf8').\n */\nutil.createBuffer = function(input, encoding) {\n // TODO: deprecate, use new ByteBuffer() instead\n encoding = encoding || 'raw';\n if(input !== undefined && encoding === 'utf8') {\n input = util.encodeUtf8(input);\n }\n return new util.ByteBuffer(input);\n};\n\n/**\n * Fills a string with a particular value. If you want the string to be a byte\n * string, pass in String.fromCharCode(theByte).\n *\n * @param c the character to fill the string with, use String.fromCharCode\n * to fill the string with a byte value.\n * @param n the number of characters of value c to fill with.\n *\n * @return the filled string.\n */\nutil.fillString = function(c, n) {\n var s = '';\n while(n > 0) {\n if(n & 1) {\n s += c;\n }\n n >>>= 1;\n if(n > 0) {\n c += c;\n }\n }\n return s;\n};\n\n/**\n * Performs a per byte XOR between two byte strings and returns the result as a\n * string of bytes.\n *\n * @param s1 first string of bytes.\n * @param s2 second string of bytes.\n * @param n the number of bytes to XOR.\n *\n * @return the XOR'd result.\n */\nutil.xorBytes = function(s1, s2, n) {\n var s3 = '';\n var b = '';\n var t = '';\n var i = 0;\n var c = 0;\n for(; n > 0; --n, ++i) {\n b = s1.charCodeAt(i) ^ s2.charCodeAt(i);\n if(c >= 10) {\n s3 += t;\n t = '';\n c = 0;\n }\n t += String.fromCharCode(b);\n ++c;\n }\n s3 += t;\n return s3;\n};\n\n/**\n * Converts a hex string into a 'binary' encoded string of bytes.\n *\n * @param hex the hexadecimal string to convert.\n *\n * @return the binary-encoded string of bytes.\n */\nutil.hexToBytes = function(hex) {\n // TODO: deprecate: \"Deprecated. Use util.binary.hex.decode instead.\"\n var rval = '';\n var i = 0;\n if(hex.length & 1 == 1) {\n // odd number of characters, convert first character alone\n i = 1;\n rval += String.fromCharCode(parseInt(hex[0], 16));\n }\n // convert 2 characters (1 byte) at a time\n for(; i < hex.length; i += 2) {\n rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16));\n }\n return rval;\n};\n\n/**\n * Converts a 'binary' encoded string of bytes to hex.\n *\n * @param bytes the byte string to convert.\n *\n * @return the string of hexadecimal characters.\n */\nutil.bytesToHex = function(bytes) {\n // TODO: deprecate: \"Deprecated. Use util.binary.hex.encode instead.\"\n return util.createBuffer(bytes).toHex();\n};\n\n/**\n * Converts an 32-bit integer to 4-big-endian byte string.\n *\n * @param i the integer.\n *\n * @return the byte string.\n */\nutil.int32ToBytes = function(i) {\n return (\n String.fromCharCode(i >> 24 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n// base64 characters, reverse mapping\nvar _base64 =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\nvar _base64Idx = [\n/*43 -43 = 0*/\n/*'+', 1, 2, 3,'/' */\n 62, -1, -1, -1, 63,\n\n/*'0','1','2','3','4','5','6','7','8','9' */\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,\n\n/*15, 16, 17,'=', 19, 20, 21 */\n -1, -1, -1, 64, -1, -1, -1,\n\n/*65 - 43 = 22*/\n/*'A','B','C','D','E','F','G','H','I','J','K','L','M', */\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,\n\n/*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */\n 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,\n\n/*91 - 43 = 48 */\n/*48, 49, 50, 51, 52, 53 */\n -1, -1, -1, -1, -1, -1,\n\n/*97 - 43 = 54*/\n/*'a','b','c','d','e','f','g','h','i','j','k','l','m' */\n 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,\n\n/*'n','o','p','q','r','s','t','u','v','w','x','y','z' */\n 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51\n];\n\n// base58 characters (Bitcoin alphabet)\nvar _base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Base64 encodes a 'binary' encoded string of bytes.\n *\n * @param input the binary encoded string of bytes to base64-encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the base64-encoded output.\n */\nutil.encode64 = function(input, maxline) {\n // TODO: deprecate: \"Deprecated. Use util.binary.base64.encode instead.\"\n var line = '';\n var output = '';\n var chr1, chr2, chr3;\n var i = 0;\n while(i < input.length) {\n chr1 = input.charCodeAt(i++);\n chr2 = input.charCodeAt(i++);\n chr3 = input.charCodeAt(i++);\n\n // encode 4 character group\n line += _base64.charAt(chr1 >> 2);\n line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));\n if(isNaN(chr2)) {\n line += '==';\n } else {\n line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));\n line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);\n }\n\n if(maxline && line.length > maxline) {\n output += line.substr(0, maxline) + '\\r\\n';\n line = line.substr(maxline);\n }\n }\n output += line;\n return output;\n};\n\n/**\n * Base64 decodes a string into a 'binary' encoded string of bytes.\n *\n * @param input the base64-encoded input.\n *\n * @return the binary encoded string.\n */\nutil.decode64 = function(input) {\n // TODO: deprecate: \"Deprecated. Use util.binary.base64.decode instead.\"\n\n // remove all non-base64 characters\n input = input.replace(/[^A-Za-z0-9\\+\\/\\=]/g, '');\n\n var output = '';\n var enc1, enc2, enc3, enc4;\n var i = 0;\n\n while(i < input.length) {\n enc1 = _base64Idx[input.charCodeAt(i++) - 43];\n enc2 = _base64Idx[input.charCodeAt(i++) - 43];\n enc3 = _base64Idx[input.charCodeAt(i++) - 43];\n enc4 = _base64Idx[input.charCodeAt(i++) - 43];\n\n output += String.fromCharCode((enc1 << 2) | (enc2 >> 4));\n if(enc3 !== 64) {\n // decoded at least 2 bytes\n output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2));\n if(enc4 !== 64) {\n // decoded 3 bytes\n output += String.fromCharCode(((enc3 & 3) << 6) | enc4);\n }\n }\n }\n\n return output;\n};\n\n/**\n * Encodes the given string of characters (a standard JavaScript\n * string) as a binary encoded string where the bytes represent\n * a UTF-8 encoded string of characters. Non-ASCII characters will be\n * encoded as multiple bytes according to UTF-8.\n *\n * @param str a standard string of characters to encode.\n *\n * @return the binary encoded string.\n */\nutil.encodeUtf8 = function(str) {\n return unescape(encodeURIComponent(str));\n};\n\n/**\n * Decodes a binary encoded string that contains bytes that\n * represent a UTF-8 encoded string of characters -- into a\n * string of characters (a standard JavaScript string).\n *\n * @param str the binary encoded string to decode.\n *\n * @return the resulting standard string of characters.\n */\nutil.decodeUtf8 = function(str) {\n return decodeURIComponent(escape(str));\n};\n\n// binary encoding/decoding tools\n// FIXME: Experimental. Do not use yet.\nutil.binary = {\n raw: {},\n hex: {},\n base64: {},\n base58: {},\n baseN : {\n encode: baseN.encode,\n decode: baseN.decode\n }\n};\n\n/**\n * Encodes a Uint8Array as a binary-encoded string. This encoding uses\n * a value between 0 and 255 for each character.\n *\n * @param bytes the Uint8Array to encode.\n *\n * @return the binary-encoded string.\n */\nutil.binary.raw.encode = function(bytes) {\n return String.fromCharCode.apply(null, bytes);\n};\n\n/**\n * Decodes a binary-encoded string to a Uint8Array. This encoding uses\n * a value between 0 and 255 for each character.\n *\n * @param str the binary-encoded string to decode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.raw.decode = function(str, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length);\n }\n offset = offset || 0;\n var j = offset;\n for(var i = 0; i < str.length; ++i) {\n out[j++] = str.charCodeAt(i);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Encodes a 'binary' string, ArrayBuffer, DataView, TypedArray, or\n * ByteBuffer as a string of hexadecimal characters.\n *\n * @param bytes the bytes to convert.\n *\n * @return the string of hexadecimal characters.\n */\nutil.binary.hex.encode = util.bytesToHex;\n\n/**\n * Decodes a hex-encoded string to a Uint8Array.\n *\n * @param hex the hexadecimal string to convert.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.hex.decode = function(hex, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(Math.ceil(hex.length / 2));\n }\n offset = offset || 0;\n var i = 0, j = offset;\n if(hex.length & 1) {\n // odd number of characters, convert first character alone\n i = 1;\n out[j++] = parseInt(hex[0], 16);\n }\n // convert 2 characters (1 byte) at a time\n for(; i < hex.length; i += 2) {\n out[j++] = parseInt(hex.substr(i, 2), 16);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Base64-encodes a Uint8Array.\n *\n * @param input the Uint8Array to encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the base64-encoded output string.\n */\nutil.binary.base64.encode = function(input, maxline) {\n var line = '';\n var output = '';\n var chr1, chr2, chr3;\n var i = 0;\n while(i < input.byteLength) {\n chr1 = input[i++];\n chr2 = input[i++];\n chr3 = input[i++];\n\n // encode 4 character group\n line += _base64.charAt(chr1 >> 2);\n line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));\n if(isNaN(chr2)) {\n line += '==';\n } else {\n line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));\n line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);\n }\n\n if(maxline && line.length > maxline) {\n output += line.substr(0, maxline) + '\\r\\n';\n line = line.substr(maxline);\n }\n }\n output += line;\n return output;\n};\n\n/**\n * Decodes a base64-encoded string to a Uint8Array.\n *\n * @param input the base64-encoded input string.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.base64.decode = function(input, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(Math.ceil(input.length / 4) * 3);\n }\n\n // remove all non-base64 characters\n input = input.replace(/[^A-Za-z0-9\\+\\/\\=]/g, '');\n\n offset = offset || 0;\n var enc1, enc2, enc3, enc4;\n var i = 0, j = offset;\n\n while(i < input.length) {\n enc1 = _base64Idx[input.charCodeAt(i++) - 43];\n enc2 = _base64Idx[input.charCodeAt(i++) - 43];\n enc3 = _base64Idx[input.charCodeAt(i++) - 43];\n enc4 = _base64Idx[input.charCodeAt(i++) - 43];\n\n out[j++] = (enc1 << 2) | (enc2 >> 4);\n if(enc3 !== 64) {\n // decoded at least 2 bytes\n out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2);\n if(enc4 !== 64) {\n // decoded 3 bytes\n out[j++] = ((enc3 & 3) << 6) | enc4;\n }\n }\n }\n\n // make sure result is the exact decoded length\n return output ? (j - offset) : out.subarray(0, j);\n};\n\n// add support for base58 encoding/decoding with Bitcoin alphabet\nutil.binary.base58.encode = function(input, maxline) {\n return util.binary.baseN.encode(input, _base58, maxline);\n};\nutil.binary.base58.decode = function(input, maxline) {\n return util.binary.baseN.decode(input, _base58, maxline);\n};\n\n// text encoding/decoding tools\n// FIXME: Experimental. Do not use yet.\nutil.text = {\n utf8: {},\n utf16: {}\n};\n\n/**\n * Encodes the given string as UTF-8 in a Uint8Array.\n *\n * @param str the string to encode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.text.utf8.encode = function(str, output, offset) {\n str = util.encodeUtf8(str);\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length);\n }\n offset = offset || 0;\n var j = offset;\n for(var i = 0; i < str.length; ++i) {\n out[j++] = str.charCodeAt(i);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Decodes the UTF-8 contents from a Uint8Array.\n *\n * @param bytes the Uint8Array to decode.\n *\n * @return the resulting string.\n */\nutil.text.utf8.decode = function(bytes) {\n return util.decodeUtf8(String.fromCharCode.apply(null, bytes));\n};\n\n/**\n * Encodes the given string as UTF-16 in a Uint8Array.\n *\n * @param str the string to encode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.text.utf16.encode = function(str, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length * 2);\n }\n var view = new Uint16Array(out.buffer);\n offset = offset || 0;\n var j = offset;\n var k = offset;\n for(var i = 0; i < str.length; ++i) {\n view[k++] = str.charCodeAt(i);\n j += 2;\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Decodes the UTF-16 contents from a Uint8Array.\n *\n * @param bytes the Uint8Array to decode.\n *\n * @return the resulting string.\n */\nutil.text.utf16.decode = function(bytes) {\n return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer));\n};\n\n/**\n * Deflates the given data using a flash interface.\n *\n * @param api the flash interface.\n * @param bytes the data.\n * @param raw true to return only raw deflate data, false to include zlib\n * header and trailer.\n *\n * @return the deflated data as a string.\n */\nutil.deflate = function(api, bytes, raw) {\n bytes = util.decode64(api.deflate(util.encode64(bytes)).rval);\n\n // strip zlib header and trailer if necessary\n if(raw) {\n // zlib header is 2 bytes (CMF,FLG) where FLG indicates that\n // there is a 4-byte DICT (alder-32) block before the data if\n // its 5th bit is set\n var start = 2;\n var flg = bytes.charCodeAt(1);\n if(flg & 0x20) {\n start = 6;\n }\n // zlib trailer is 4 bytes of adler-32\n bytes = bytes.substring(start, bytes.length - 4);\n }\n\n return bytes;\n};\n\n/**\n * Inflates the given data using a flash interface.\n *\n * @param api the flash interface.\n * @param bytes the data.\n * @param raw true if the incoming data has no zlib header or trailer and is\n * raw DEFLATE data.\n *\n * @return the inflated data as a string, null on error.\n */\nutil.inflate = function(api, bytes, raw) {\n // TODO: add zlib header and trailer if necessary/possible\n var rval = api.inflate(util.encode64(bytes)).rval;\n return (rval === null) ? null : util.decode64(rval);\n};\n\n/**\n * Sets a storage object.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param obj the storage object, null to remove.\n */\nvar _setStorageObject = function(api, id, obj) {\n if(!api) {\n throw new Error('WebStorage not available.');\n }\n\n var rval;\n if(obj === null) {\n rval = api.removeItem(id);\n } else {\n // json-encode and base64-encode object\n obj = util.encode64(JSON.stringify(obj));\n rval = api.setItem(id, obj);\n }\n\n // handle potential flash error\n if(typeof(rval) !== 'undefined' && rval.rval !== true) {\n var error = new Error(rval.error.message);\n error.id = rval.error.id;\n error.name = rval.error.name;\n throw error;\n }\n};\n\n/**\n * Gets a storage object.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n *\n * @return the storage object entry or null if none exists.\n */\nvar _getStorageObject = function(api, id) {\n if(!api) {\n throw new Error('WebStorage not available.');\n }\n\n // get the existing entry\n var rval = api.getItem(id);\n\n /* Note: We check api.init because we can't do (api == localStorage)\n on IE because of \"Class doesn't support Automation\" exception. Only\n the flash api has an init method so this works too, but we need a\n better solution in the future. */\n\n // flash returns item wrapped in an object, handle special case\n if(api.init) {\n if(rval.rval === null) {\n if(rval.error) {\n var error = new Error(rval.error.message);\n error.id = rval.error.id;\n error.name = rval.error.name;\n throw error;\n }\n // no error, but also no item\n rval = null;\n } else {\n rval = rval.rval;\n }\n }\n\n // handle decoding\n if(rval !== null) {\n // base64-decode and json-decode data\n rval = JSON.parse(util.decode64(rval));\n }\n\n return rval;\n};\n\n/**\n * Stores an item in local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param data the data for the item (any javascript object/primitive).\n */\nvar _setItem = function(api, id, key, data) {\n // get storage object\n var obj = _getStorageObject(api, id);\n if(obj === null) {\n // create a new storage object\n obj = {};\n }\n // update key\n obj[key] = data;\n\n // set storage object\n _setStorageObject(api, id, obj);\n};\n\n/**\n * Gets an item from local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n *\n * @return the item.\n */\nvar _getItem = function(api, id, key) {\n // get storage object\n var rval = _getStorageObject(api, id);\n if(rval !== null) {\n // return data at key\n rval = (key in rval) ? rval[key] : null;\n }\n\n return rval;\n};\n\n/**\n * Removes an item from local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n */\nvar _removeItem = function(api, id, key) {\n // get storage object\n var obj = _getStorageObject(api, id);\n if(obj !== null && key in obj) {\n // remove key\n delete obj[key];\n\n // see if entry has no keys remaining\n var empty = true;\n for(var prop in obj) {\n empty = false;\n break;\n }\n if(empty) {\n // remove entry entirely if no keys are left\n obj = null;\n }\n\n // set storage object\n _setStorageObject(api, id, obj);\n }\n};\n\n/**\n * Clears the local disk storage identified by the given ID.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n */\nvar _clearItems = function(api, id) {\n _setStorageObject(api, id, null);\n};\n\n/**\n * Calls a storage function.\n *\n * @param func the function to call.\n * @param args the arguments for the function.\n * @param location the location argument.\n *\n * @return the return value from the function.\n */\nvar _callStorageFunction = function(func, args, location) {\n var rval = null;\n\n // default storage types\n if(typeof(location) === 'undefined') {\n location = ['web', 'flash'];\n }\n\n // apply storage types in order of preference\n var type;\n var done = false;\n var exception = null;\n for(var idx in location) {\n type = location[idx];\n try {\n if(type === 'flash' || type === 'both') {\n if(args[0] === null) {\n throw new Error('Flash local storage not available.');\n }\n rval = func.apply(this, args);\n done = (type === 'flash');\n }\n if(type === 'web' || type === 'both') {\n args[0] = localStorage;\n rval = func.apply(this, args);\n done = true;\n }\n } catch(ex) {\n exception = ex;\n }\n if(done) {\n break;\n }\n }\n\n if(!done) {\n throw exception;\n }\n\n return rval;\n};\n\n/**\n * Stores an item on local disk.\n *\n * The available types of local storage include 'flash', 'web', and 'both'.\n *\n * The type 'flash' refers to flash local storage (SharedObject). In order\n * to use flash local storage, the 'api' parameter must be valid. The type\n * 'web' refers to WebStorage, if supported by the browser. The type 'both'\n * refers to storing using both 'flash' and 'web', not just one or the\n * other.\n *\n * The location array should list the storage types to use in order of\n * preference:\n *\n * ['flash']: flash only storage\n * ['web']: web only storage\n * ['both']: try to store in both\n * ['flash','web']: store in flash first, but if not available, 'web'\n * ['web','flash']: store in web first, but if not available, 'flash'\n *\n * The location array defaults to: ['web', 'flash']\n *\n * @param api the flash interface, null to use only WebStorage.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param data the data for the item (any javascript object/primitive).\n * @param location an array with the preferred types of storage to use.\n */\nutil.setItem = function(api, id, key, data, location) {\n _callStorageFunction(_setItem, arguments, location);\n};\n\n/**\n * Gets an item on local disk.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface, null to use only WebStorage.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param location an array with the preferred types of storage to use.\n *\n * @return the item.\n */\nutil.getItem = function(api, id, key, location) {\n return _callStorageFunction(_getItem, arguments, location);\n};\n\n/**\n * Removes an item on local disk.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param location an array with the preferred types of storage to use.\n */\nutil.removeItem = function(api, id, key, location) {\n _callStorageFunction(_removeItem, arguments, location);\n};\n\n/**\n * Clears the local disk storage identified by the given ID.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface if flash is available.\n * @param id the storage ID to use.\n * @param location an array with the preferred types of storage to use.\n */\nutil.clearItems = function(api, id, location) {\n _callStorageFunction(_clearItems, arguments, location);\n};\n\n/**\n * Check if an object is empty.\n *\n * Taken from:\n * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#679937\n *\n * @param object the object to check.\n */\nutil.isEmpty = function(obj) {\n for(var prop in obj) {\n if(obj.hasOwnProperty(prop)) {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Format with simple printf-style interpolation.\n *\n * %%: literal '%'\n * %s,%o: convert next argument into a string.\n *\n * @param format the string to format.\n * @param ... arguments to interpolate into the format string.\n */\nutil.format = function(format) {\n var re = /%./g;\n // current match\n var match;\n // current part\n var part;\n // current arg index\n var argi = 0;\n // collected parts to recombine later\n var parts = [];\n // last index found\n var last = 0;\n // loop while matches remain\n while((match = re.exec(format))) {\n part = format.substring(last, re.lastIndex - 2);\n // don't add empty strings (ie, parts between %s%s)\n if(part.length > 0) {\n parts.push(part);\n }\n last = re.lastIndex;\n // switch on % code\n var code = match[0][1];\n switch(code) {\n case 's':\n case 'o':\n // check if enough arguments were given\n if(argi < arguments.length) {\n parts.push(arguments[argi++ + 1]);\n } else {\n parts.push('<?>');\n }\n break;\n // FIXME: do proper formating for numbers, etc\n //case 'f':\n //case 'd':\n case '%':\n parts.push('%');\n break;\n default:\n parts.push('<%' + code + '?>');\n }\n }\n // add trailing part of format string\n parts.push(format.substring(last));\n return parts.join('');\n};\n\n/**\n * Formats a number.\n *\n * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/\n */\nutil.formatNumber = function(number, decimals, dec_point, thousands_sep) {\n // http://kevin.vanzonneveld.net\n // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)\n // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)\n // + bugfix by: Michael White (http://crestidg.com)\n // + bugfix by: Benjamin Lupton\n // + bugfix by: Allan Jensen (http://www.winternet.no)\n // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)\n // * example 1: number_format(1234.5678, 2, '.', '');\n // * returns 1: 1234.57\n\n var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;\n var d = dec_point === undefined ? ',' : dec_point;\n var t = thousands_sep === undefined ?\n '.' : thousands_sep, s = n < 0 ? '-' : '';\n var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + '';\n var j = (i.length > 3) ? i.length % 3 : 0;\n return s + (j ? i.substr(0, j) + t : '') +\n i.substr(j).replace(/(\\d{3})(?=\\d)/g, '$1' + t) +\n (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');\n};\n\n/**\n * Formats a byte size.\n *\n * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/\n */\nutil.formatSize = function(size) {\n if(size >= 1073741824) {\n size = util.formatNumber(size / 1073741824, 2, '.', '') + ' GiB';\n } else if(size >= 1048576) {\n size = util.formatNumber(size / 1048576, 2, '.', '') + ' MiB';\n } else if(size >= 1024) {\n size = util.formatNumber(size / 1024, 0) + ' KiB';\n } else {\n size = util.formatNumber(size, 0) + ' bytes';\n }\n return size;\n};\n\n/**\n * Converts an IPv4 or IPv6 string representation into bytes (in network order).\n *\n * @param ip the IPv4 or IPv6 address to convert.\n *\n * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't\n * be parsed.\n */\nutil.bytesFromIP = function(ip) {\n if(ip.indexOf('.') !== -1) {\n return util.bytesFromIPv4(ip);\n }\n if(ip.indexOf(':') !== -1) {\n return util.bytesFromIPv6(ip);\n }\n return null;\n};\n\n/**\n * Converts an IPv4 string representation into bytes (in network order).\n *\n * @param ip the IPv4 address to convert.\n *\n * @return the 4-byte address or null if the address can't be parsed.\n */\nutil.bytesFromIPv4 = function(ip) {\n ip = ip.split('.');\n if(ip.length !== 4) {\n return null;\n }\n var b = util.createBuffer();\n for(var i = 0; i < ip.length; ++i) {\n var num = parseInt(ip[i], 10);\n if(isNaN(num)) {\n return null;\n }\n b.putByte(num);\n }\n return b.getBytes();\n};\n\n/**\n * Converts an IPv6 string representation into bytes (in network order).\n *\n * @param ip the IPv6 address to convert.\n *\n * @return the 16-byte address or null if the address can't be parsed.\n */\nutil.bytesFromIPv6 = function(ip) {\n var blanks = 0;\n ip = ip.split(':').filter(function(e) {\n if(e.length === 0) ++blanks;\n return true;\n });\n var zeros = (8 - ip.length + blanks) * 2;\n var b = util.createBuffer();\n for(var i = 0; i < 8; ++i) {\n if(!ip[i] || ip[i].length === 0) {\n b.fillWithByte(0, zeros);\n zeros = 0;\n continue;\n }\n var bytes = util.hexToBytes(ip[i]);\n if(bytes.length < 2) {\n b.putByte(0);\n }\n b.putBytes(bytes);\n }\n return b.getBytes();\n};\n\n/**\n * Converts 4-bytes into an IPv4 string representation or 16-bytes into\n * an IPv6 string representation. The bytes must be in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv4 or IPv6 string representation if 4 or 16 bytes,\n * respectively, are given, otherwise null.\n */\nutil.bytesToIP = function(bytes) {\n if(bytes.length === 4) {\n return util.bytesToIPv4(bytes);\n }\n if(bytes.length === 16) {\n return util.bytesToIPv6(bytes);\n }\n return null;\n};\n\n/**\n * Converts 4-bytes into an IPv4 string representation. The bytes must be\n * in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv4 string representation or null for an invalid # of bytes.\n */\nutil.bytesToIPv4 = function(bytes) {\n if(bytes.length !== 4) {\n return null;\n }\n var ip = [];\n for(var i = 0; i < bytes.length; ++i) {\n ip.push(bytes.charCodeAt(i));\n }\n return ip.join('.');\n};\n\n/**\n * Converts 16-bytes into an IPv16 string representation. The bytes must be\n * in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv16 string representation or null for an invalid # of bytes.\n */\nutil.bytesToIPv6 = function(bytes) {\n if(bytes.length !== 16) {\n return null;\n }\n var ip = [];\n var zeroGroups = [];\n var zeroMaxGroup = 0;\n for(var i = 0; i < bytes.length; i += 2) {\n var hex = util.bytesToHex(bytes[i] + bytes[i + 1]);\n // canonicalize zero representation\n while(hex[0] === '0' && hex !== '0') {\n hex = hex.substr(1);\n }\n if(hex === '0') {\n var last = zeroGroups[zeroGroups.length - 1];\n var idx = ip.length;\n if(!last || idx !== last.end + 1) {\n zeroGroups.push({start: idx, end: idx});\n } else {\n last.end = idx;\n if((last.end - last.start) >\n (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) {\n zeroMaxGroup = zeroGroups.length - 1;\n }\n }\n }\n ip.push(hex);\n }\n if(zeroGroups.length > 0) {\n var group = zeroGroups[zeroMaxGroup];\n // only shorten group of length > 0\n if(group.end - group.start > 0) {\n ip.splice(group.start, group.end - group.start + 1, '');\n if(group.start === 0) {\n ip.unshift('');\n }\n if(group.end === 7) {\n ip.push('');\n }\n }\n }\n return ip.join(':');\n};\n\n/**\n * Estimates the number of processes that can be run concurrently. If\n * creating Web Workers, keep in mind that the main JavaScript process needs\n * its own core.\n *\n * @param options the options to use:\n * update true to force an update (not use the cached value).\n * @param callback(err, max) called once the operation completes.\n */\nutil.estimateCores = function(options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n if('cores' in util && !options.update) {\n return callback(null, util.cores);\n }\n if(typeof navigator !== 'undefined' &&\n 'hardwareConcurrency' in navigator &&\n navigator.hardwareConcurrency > 0) {\n util.cores = navigator.hardwareConcurrency;\n return callback(null, util.cores);\n }\n if(typeof Worker === 'undefined') {\n // workers not available\n util.cores = 1;\n return callback(null, util.cores);\n }\n if(typeof Blob === 'undefined') {\n // can't estimate, default to 2\n util.cores = 2;\n return callback(null, util.cores);\n }\n\n // create worker concurrency estimation code as blob\n var blobUrl = URL.createObjectURL(new Blob(['(',\n function() {\n self.addEventListener('message', function(e) {\n // run worker for 4 ms\n var st = Date.now();\n var et = st + 4;\n while(Date.now() < et);\n self.postMessage({st: st, et: et});\n });\n }.toString(),\n ')()'], {type: 'application/javascript'}));\n\n // take 5 samples using 16 workers\n sample([], 5, 16);\n\n function sample(max, samples, numWorkers) {\n if(samples === 0) {\n // get overlap average\n var avg = Math.floor(max.reduce(function(avg, x) {\n return avg + x;\n }, 0) / max.length);\n util.cores = Math.max(1, avg);\n URL.revokeObjectURL(blobUrl);\n return callback(null, util.cores);\n }\n map(numWorkers, function(err, results) {\n max.push(reduce(numWorkers, results));\n sample(max, samples - 1, numWorkers);\n });\n }\n\n function map(numWorkers, callback) {\n var workers = [];\n var results = [];\n for(var i = 0; i < numWorkers; ++i) {\n var worker = new Worker(blobUrl);\n worker.addEventListener('message', function(e) {\n results.push(e.data);\n if(results.length === numWorkers) {\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].terminate();\n }\n callback(null, results);\n }\n });\n workers.push(worker);\n }\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].postMessage(i);\n }\n }\n\n function reduce(numWorkers, results) {\n // find overlapping time windows\n var overlaps = [];\n for(var n = 0; n < numWorkers; ++n) {\n var r1 = results[n];\n var overlap = overlaps[n] = [];\n for(var i = 0; i < numWorkers; ++i) {\n if(n === i) {\n continue;\n }\n var r2 = results[i];\n if((r1.st > r2.st && r1.st < r2.et) ||\n (r2.st > r1.st && r2.st < r1.et)) {\n overlap.push(i);\n }\n }\n }\n // get maximum overlaps ... don't include overlapping worker itself\n // as the main JS process was also being scheduled during the work and\n // would have to be subtracted from the estimate anyway\n return overlaps.reduce(function(max, overlap) {\n return Math.max(max, overlap.length);\n }, 0);\n }\n};\n","/**\n * Cipher base API.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nmodule.exports = forge.cipher = forge.cipher || {};\n\n// registered algorithms\nforge.cipher.algorithms = forge.cipher.algorithms || {};\n\n/**\n * Creates a cipher object that can be used to encrypt data using the given\n * algorithm and key. The algorithm may be provided as a string value for a\n * previously registered algorithm or it may be given as a cipher algorithm\n * API object.\n *\n * @param algorithm the algorithm to use, either a string or an algorithm API\n * object.\n * @param key the key to use, as a binary-encoded string of bytes or a\n * byte buffer.\n *\n * @return the cipher.\n */\nforge.cipher.createCipher = function(algorithm, key) {\n var api = algorithm;\n if(typeof api === 'string') {\n api = forge.cipher.getAlgorithm(api);\n if(api) {\n api = api();\n }\n }\n if(!api) {\n throw new Error('Unsupported algorithm: ' + algorithm);\n }\n\n // assume block cipher\n return new forge.cipher.BlockCipher({\n algorithm: api,\n key: key,\n decrypt: false\n });\n};\n\n/**\n * Creates a decipher object that can be used to decrypt data using the given\n * algorithm and key. The algorithm may be provided as a string value for a\n * previously registered algorithm or it may be given as a cipher algorithm\n * API object.\n *\n * @param algorithm the algorithm to use, either a string or an algorithm API\n * object.\n * @param key the key to use, as a binary-encoded string of bytes or a\n * byte buffer.\n *\n * @return the cipher.\n */\nforge.cipher.createDecipher = function(algorithm, key) {\n var api = algorithm;\n if(typeof api === 'string') {\n api = forge.cipher.getAlgorithm(api);\n if(api) {\n api = api();\n }\n }\n if(!api) {\n throw new Error('Unsupported algorithm: ' + algorithm);\n }\n\n // assume block cipher\n return new forge.cipher.BlockCipher({\n algorithm: api,\n key: key,\n decrypt: true\n });\n};\n\n/**\n * Registers an algorithm by name. If the name was already registered, the\n * algorithm API object will be overwritten.\n *\n * @param name the name of the algorithm.\n * @param algorithm the algorithm API object.\n */\nforge.cipher.registerAlgorithm = function(name, algorithm) {\n name = name.toUpperCase();\n forge.cipher.algorithms[name] = algorithm;\n};\n\n/**\n * Gets a registered algorithm by name.\n *\n * @param name the name of the algorithm.\n *\n * @return the algorithm, if found, null if not.\n */\nforge.cipher.getAlgorithm = function(name) {\n name = name.toUpperCase();\n if(name in forge.cipher.algorithms) {\n return forge.cipher.algorithms[name];\n }\n return null;\n};\n\nvar BlockCipher = forge.cipher.BlockCipher = function(options) {\n this.algorithm = options.algorithm;\n this.mode = this.algorithm.mode;\n this.blockSize = this.mode.blockSize;\n this._finish = false;\n this._input = null;\n this.output = null;\n this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt;\n this._decrypt = options.decrypt;\n this.algorithm.initialize(options);\n};\n\n/**\n * Starts or restarts the encryption or decryption process, whichever\n * was previously configured.\n *\n * For non-GCM mode, the IV may be a binary-encoded string of bytes, an array\n * of bytes, a byte buffer, or an array of 32-bit integers. If the IV is in\n * bytes, then it must be Nb (16) bytes in length. If the IV is given in as\n * 32-bit integers, then it must be 4 integers long.\n *\n * Note: an IV is not required or used in ECB mode.\n *\n * For GCM-mode, the IV must be given as a binary-encoded string of bytes or\n * a byte buffer. The number of bytes should be 12 (96 bits) as recommended\n * by NIST SP-800-38D but another length may be given.\n *\n * @param options the options to use:\n * iv the initialization vector to use as a binary-encoded string of\n * bytes, null to reuse the last ciphered block from a previous\n * update() (this \"residue\" method is for legacy support only).\n * additionalData additional authentication data as a binary-encoded\n * string of bytes, for 'GCM' mode, (default: none).\n * tagLength desired length of authentication tag, in bits, for\n * 'GCM' mode (0-128, default: 128).\n * tag the authentication tag to check if decrypting, as a\n * binary-encoded string of bytes.\n * output the output the buffer to write to, null to create one.\n */\nBlockCipher.prototype.start = function(options) {\n options = options || {};\n var opts = {};\n for(var key in options) {\n opts[key] = options[key];\n }\n opts.decrypt = this._decrypt;\n this._finish = false;\n this._input = forge.util.createBuffer();\n this.output = options.output || forge.util.createBuffer();\n this.mode.start(opts);\n};\n\n/**\n * Updates the next block according to the cipher mode.\n *\n * @param input the buffer to read from.\n */\nBlockCipher.prototype.update = function(input) {\n if(input) {\n // input given, so empty it into the input buffer\n this._input.putBuffer(input);\n }\n\n // do cipher operation until it needs more input and not finished\n while(!this._op.call(this.mode, this._input, this.output, this._finish) &&\n !this._finish) {}\n\n // free consumed memory from input buffer\n this._input.compact();\n};\n\n/**\n * Finishes encrypting or decrypting.\n *\n * @param pad a padding function to use in CBC mode, null for default,\n * signature(blockSize, buffer, decrypt).\n *\n * @return true if successful, false on error.\n */\nBlockCipher.prototype.finish = function(pad) {\n // backwards-compatibility w/deprecated padding API\n // Note: will overwrite padding functions even after another start() call\n if(pad && (this.mode.name === 'ECB' || this.mode.name === 'CBC')) {\n this.mode.pad = function(input) {\n return pad(this.blockSize, input, false);\n };\n this.mode.unpad = function(output) {\n return pad(this.blockSize, output, true);\n };\n }\n\n // build options for padding and afterFinish functions\n var options = {};\n options.decrypt = this._decrypt;\n\n // get # of bytes that won't fill a block\n options.overflow = this._input.length() % this.blockSize;\n\n if(!this._decrypt && this.mode.pad) {\n if(!this.mode.pad(this._input, options)) {\n return false;\n }\n }\n\n // do final update\n this._finish = true;\n this.update();\n\n if(this._decrypt && this.mode.unpad) {\n if(!this.mode.unpad(this.output, options)) {\n return false;\n }\n }\n\n if(this.mode.afterFinish) {\n if(!this.mode.afterFinish(this.output, options)) {\n return false;\n }\n }\n\n return true;\n};\n","/**\n * Supported cipher modes.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nforge.cipher = forge.cipher || {};\n\n// supported cipher modes\nvar modes = module.exports = forge.cipher.modes = forge.cipher.modes || {};\n\n/** Electronic codebook (ECB) (Don't use this; it's not secure) **/\n\nmodes.ecb = function(options) {\n options = options || {};\n this.name = 'ECB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n};\n\nmodes.ecb.prototype.start = function(options) {};\n\nmodes.ecb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // write output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n};\n\nmodes.ecb.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // decrypt block\n this.cipher.decrypt(this._inBlock, this._outBlock);\n\n // write output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n};\n\nmodes.ecb.prototype.pad = function(input, options) {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (input.length() === this.blockSize ?\n this.blockSize : (this.blockSize - input.length()));\n input.fillWithByte(padding, padding);\n return true;\n};\n\nmodes.ecb.prototype.unpad = function(output, options) {\n // check for error: input data not a multiple of blockSize\n if(options.overflow > 0) {\n return false;\n }\n\n // ensure padding byte count is valid\n var len = output.length();\n var count = output.at(len - 1);\n if(count > (this.blockSize << 2)) {\n return false;\n }\n\n // trim off padding bytes\n output.truncate(count);\n return true;\n};\n\n/** Cipher-block Chaining (CBC) **/\n\nmodes.cbc = function(options) {\n options = options || {};\n this.name = 'CBC';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n};\n\nmodes.cbc.prototype.start = function(options) {\n // Note: legacy support for using IV residue (has security flaws)\n // if IV is null, reuse block from previous processing\n if(options.iv === null) {\n // must have a previous block\n if(!this._prev) {\n throw new Error('Invalid IV parameter.');\n }\n this._iv = this._prev.slice(0);\n } else if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n } else {\n // save IV as \"previous\" block\n this._iv = transformIV(options.iv, this.blockSize);\n this._prev = this._iv.slice(0);\n }\n};\n\nmodes.cbc.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n // CBC XOR's IV (or previous block) with plaintext\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._prev[i] ^ input.getInt32();\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // write output, save previous block\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n this._prev = this._outBlock;\n};\n\nmodes.cbc.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // decrypt block\n this.cipher.decrypt(this._inBlock, this._outBlock);\n\n // write output, save previous ciphered block\n // CBC XOR's IV (or previous block) with ciphertext\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._prev[i] ^ this._outBlock[i]);\n }\n this._prev = this._inBlock.slice(0);\n};\n\nmodes.cbc.prototype.pad = function(input, options) {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (input.length() === this.blockSize ?\n this.blockSize : (this.blockSize - input.length()));\n input.fillWithByte(padding, padding);\n return true;\n};\n\nmodes.cbc.prototype.unpad = function(output, options) {\n // check for error: input data not a multiple of blockSize\n if(options.overflow > 0) {\n return false;\n }\n\n // ensure padding byte count is valid\n var len = output.length();\n var count = output.at(len - 1);\n if(count > (this.blockSize << 2)) {\n return false;\n }\n\n // trim off padding bytes\n output.truncate(count);\n return true;\n};\n\n/** Cipher feedback (CFB) **/\n\nmodes.cfb = function(options) {\n options = options || {};\n this.name = 'CFB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output, write input as output\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32() ^ this._outBlock[i];\n output.putInt32(this._inBlock[i]);\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output, write input as partial output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialBlock[i] = input.getInt32() ^ this._outBlock[i];\n this._partialOutput.putInt32(this._partialBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._partialBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block (CFB always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output, write input as output\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n output.putInt32(this._inBlock[i] ^ this._outBlock[i]);\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output, write input as partial output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialBlock[i] = input.getInt32();\n this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._partialBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\n/** Output feedback (OFB) **/\n\nmodes.ofb = function(options) {\n options = options || {};\n this.name = 'OFB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(input.length() === 0) {\n return true;\n }\n\n // encrypt block (OFB always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output and update next input\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(input.getInt32() ^ this._outBlock[i]);\n this._inBlock[i] = this._outBlock[i];\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._outBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt;\n\n/** Counter (CTR) **/\n\nmodes.ctr = function(options) {\n options = options || {};\n this.name = 'CTR';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.ctr.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.ctr.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block (CTR always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n } else {\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n }\n\n // block complete, increment counter (input block)\n inc32(this._inBlock);\n};\n\nmodes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt;\n\n/** Galois/Counter Mode (GCM) **/\n\nmodes.gcm = function(options) {\n options = options || {};\n this.name = 'GCM';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n\n // R is actually this value concatenated with 120 more zero bits, but\n // we only XOR against R so the other zeros have no effect -- we just\n // apply this value to the first integer in a block\n this._R = 0xE1000000;\n};\n\nmodes.gcm.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // ensure IV is a byte buffer\n var iv = forge.util.createBuffer(options.iv);\n\n // no ciphered data processed yet\n this._cipherLength = 0;\n\n // default additional data is none\n var additionalData;\n if('additionalData' in options) {\n additionalData = forge.util.createBuffer(options.additionalData);\n } else {\n additionalData = forge.util.createBuffer();\n }\n\n // default tag length is 128 bits\n if('tagLength' in options) {\n this._tagLength = options.tagLength;\n } else {\n this._tagLength = 128;\n }\n\n // if tag is given, ensure tag matches tag length\n this._tag = null;\n if(options.decrypt) {\n // save tag to check later\n this._tag = forge.util.createBuffer(options.tag).getBytes();\n if(this._tag.length !== (this._tagLength / 8)) {\n throw new Error('Authentication tag does not match tag length.');\n }\n }\n\n // create tmp storage for hash calculation\n this._hashBlock = new Array(this._ints);\n\n // no tag generated yet\n this.tag = null;\n\n // generate hash subkey\n // (apply block cipher to \"zero\" block)\n this._hashSubkey = new Array(this._ints);\n this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey);\n\n // generate table M\n // use 4-bit tables (32 component decomposition of a 16 byte value)\n // 8-bit tables take more space and are known to have security\n // vulnerabilities (in native implementations)\n this.componentBits = 4;\n this._m = this.generateHashTable(this._hashSubkey, this.componentBits);\n\n // Note: support IV length different from 96 bits? (only supporting\n // 96 bits is recommended by NIST SP-800-38D)\n // generate J_0\n var ivLength = iv.length();\n if(ivLength === 12) {\n // 96-bit IV\n this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1];\n } else {\n // IV is NOT 96-bits\n this._j0 = [0, 0, 0, 0];\n while(iv.length() > 0) {\n this._j0 = this.ghash(\n this._hashSubkey, this._j0,\n [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]);\n }\n this._j0 = this.ghash(\n this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8)));\n }\n\n // generate ICB (initial counter block)\n this._inBlock = this._j0.slice(0);\n inc32(this._inBlock);\n this._partialBytes = 0;\n\n // consume authentication data\n additionalData = forge.util.createBuffer(additionalData);\n // save additional data length as a BE 64-bit number\n this._aDataLength = from64To32(additionalData.length() * 8);\n // pad additional data to 128 bit (16 byte) block size\n var overflow = additionalData.length() % this.blockSize;\n if(overflow) {\n additionalData.fillWithByte(0, this.blockSize - overflow);\n }\n this._s = [0, 0, 0, 0];\n while(additionalData.length() > 0) {\n this._s = this.ghash(this._hashSubkey, this._s, [\n additionalData.getInt32(),\n additionalData.getInt32(),\n additionalData.getInt32(),\n additionalData.getInt32()\n ]);\n }\n};\n\nmodes.gcm.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i] ^= input.getInt32());\n }\n this._cipherLength += this.blockSize;\n } else {\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes <= 0 || finish) {\n // handle overflow prior to hashing\n if(finish) {\n // get block overflow\n var overflow = inputLength % this.blockSize;\n this._cipherLength += overflow;\n // truncate for hash function\n this._partialOutput.truncate(this.blockSize - overflow);\n } else {\n this._cipherLength += this.blockSize;\n }\n\n // get output block for hashing\n for(var i = 0; i < this._ints; ++i) {\n this._outBlock[i] = this._partialOutput.getInt32();\n }\n this._partialOutput.read -= this.blockSize;\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n // block still incomplete, restore input buffer, get partial output,\n // and return early\n input.read -= this.blockSize;\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n }\n\n // update hash block S\n this._s = this.ghash(this._hashSubkey, this._s, this._outBlock);\n\n // increment counter (input block)\n inc32(this._inBlock);\n};\n\nmodes.gcm.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n var inputLength = input.length();\n if(inputLength < this.blockSize && !(finish && inputLength > 0)) {\n return true;\n }\n\n // encrypt block (GCM always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // increment counter (input block)\n inc32(this._inBlock);\n\n // update hash block S\n this._hashBlock[0] = input.getInt32();\n this._hashBlock[1] = input.getInt32();\n this._hashBlock[2] = input.getInt32();\n this._hashBlock[3] = input.getInt32();\n this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock);\n\n // XOR hash input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i] ^ this._hashBlock[i]);\n }\n\n // increment cipher data length\n if(inputLength < this.blockSize) {\n this._cipherLength += inputLength % this.blockSize;\n } else {\n this._cipherLength += this.blockSize;\n }\n};\n\nmodes.gcm.prototype.afterFinish = function(output, options) {\n var rval = true;\n\n // handle overflow\n if(options.decrypt && options.overflow) {\n output.truncate(this.blockSize - options.overflow);\n }\n\n // handle authentication tag\n this.tag = forge.util.createBuffer();\n\n // concatenate additional data length with cipher length\n var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8));\n\n // include lengths in hash\n this._s = this.ghash(this._hashSubkey, this._s, lengths);\n\n // do GCTR(J_0, S)\n var tag = [];\n this.cipher.encrypt(this._j0, tag);\n for(var i = 0; i < this._ints; ++i) {\n this.tag.putInt32(this._s[i] ^ tag[i]);\n }\n\n // trim tag to length\n this.tag.truncate(this.tag.length() % (this._tagLength / 8));\n\n // check authentication tag\n if(options.decrypt && this.tag.bytes() !== this._tag) {\n rval = false;\n }\n\n return rval;\n};\n\n/**\n * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois\n * field multiplication. The field, GF(2^128), is defined by the polynomial:\n *\n * x^128 + x^7 + x^2 + x + 1\n *\n * Which is represented in little-endian binary form as: 11100001 (0xe1). When\n * the value of a coefficient is 1, a bit is set. The value R, is the\n * concatenation of this value and 120 zero bits, yielding a 128-bit value\n * which matches the block size.\n *\n * This function will multiply two elements (vectors of bytes), X and Y, in\n * the field GF(2^128). The result is initialized to zero. For each bit of\n * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd)\n * by the current value of Y. For each bit, the value of Y will be raised by\n * a power of x (multiplied by the polynomial x). This can be achieved by\n * shifting Y once to the right. If the current value of Y, prior to being\n * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial.\n * Otherwise, we must divide by R after shifting to find the remainder.\n *\n * @param x the first block to multiply by the second.\n * @param y the second block to multiply by the first.\n *\n * @return the block result of the multiplication.\n */\nmodes.gcm.prototype.multiply = function(x, y) {\n var z_i = [0, 0, 0, 0];\n var v_i = y.slice(0);\n\n // calculate Z_128 (block has 128 bits)\n for(var i = 0; i < 128; ++i) {\n // if x_i is 0, Z_{i+1} = Z_i (unchanged)\n // else Z_{i+1} = Z_i ^ V_i\n // get x_i by finding 32-bit int position, then left shift 1 by remainder\n var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32));\n if(x_i) {\n z_i[0] ^= v_i[0];\n z_i[1] ^= v_i[1];\n z_i[2] ^= v_i[2];\n z_i[3] ^= v_i[3];\n }\n\n // if LSB(V_i) is 1, V_i = V_i >> 1\n // else V_i = (V_i >> 1) ^ R\n this.pow(v_i, v_i);\n }\n\n return z_i;\n};\n\nmodes.gcm.prototype.pow = function(x, out) {\n // if LSB(x) is 1, x = x >>> 1\n // else x = (x >>> 1) ^ R\n var lsb = x[3] & 1;\n\n // always do x >>> 1:\n // starting with the rightmost integer, shift each integer to the right\n // one bit, pulling in the bit from the integer to the left as its top\n // most bit (do this for the last 3 integers)\n for(var i = 3; i > 0; --i) {\n out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31);\n }\n // shift the first integer normally\n out[0] = x[0] >>> 1;\n\n // if lsb was not set, then polynomial had a degree of 127 and doesn't\n // need to divided; otherwise, XOR with R to find the remainder; we only\n // need to XOR the first integer since R technically ends w/120 zero bits\n if(lsb) {\n out[0] ^= this._R;\n }\n};\n\nmodes.gcm.prototype.tableMultiply = function(x) {\n // assumes 4-bit tables are used\n var z = [0, 0, 0, 0];\n for(var i = 0; i < 32; ++i) {\n var idx = (i / 8) | 0;\n var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF;\n var ah = this._m[i][x_i];\n z[0] ^= ah[0];\n z[1] ^= ah[1];\n z[2] ^= ah[2];\n z[3] ^= ah[3];\n }\n return z;\n};\n\n/**\n * A continuing version of the GHASH algorithm that operates on a single\n * block. The hash block, last hash value (Ym) and the new block to hash\n * are given.\n *\n * @param h the hash block.\n * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash.\n * @param x the block to hash.\n *\n * @return the hashed value (Ym).\n */\nmodes.gcm.prototype.ghash = function(h, y, x) {\n y[0] ^= x[0];\n y[1] ^= x[1];\n y[2] ^= x[2];\n y[3] ^= x[3];\n return this.tableMultiply(y);\n //return this.multiply(y, h);\n};\n\n/**\n * Precomputes a table for multiplying against the hash subkey. This\n * mechanism provides a substantial speed increase over multiplication\n * performed without a table. The table-based multiplication this table is\n * for solves X * H by multiplying each component of X by H and then\n * composing the results together using XOR.\n *\n * This function can be used to generate tables with different bit sizes\n * for the components, however, this implementation assumes there are\n * 32 components of X (which is a 16 byte vector), therefore each component\n * takes 4-bits (so the table is constructed with bits=4).\n *\n * @param h the hash subkey.\n * @param bits the bit size for a component.\n */\nmodes.gcm.prototype.generateHashTable = function(h, bits) {\n // TODO: There are further optimizations that would use only the\n // first table M_0 (or some variant) along with a remainder table;\n // this can be explored in the future\n var multiplier = 8 / bits;\n var perInt = 4 * multiplier;\n var size = 16 * multiplier;\n var m = new Array(size);\n for(var i = 0; i < size; ++i) {\n var tmp = [0, 0, 0, 0];\n var idx = (i / perInt) | 0;\n var shft = ((perInt - 1 - (i % perInt)) * bits);\n tmp[idx] = (1 << (bits - 1)) << shft;\n m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits);\n }\n return m;\n};\n\n/**\n * Generates a table for multiplying against the hash subkey for one\n * particular component (out of all possible component values).\n *\n * @param mid the pre-multiplied value for the middle key of the table.\n * @param bits the bit size for a component.\n */\nmodes.gcm.prototype.generateSubHashTable = function(mid, bits) {\n // compute the table quickly by minimizing the number of\n // POW operations -- they only need to be performed for powers of 2,\n // all other entries can be composed from those powers using XOR\n var size = 1 << bits;\n var half = size >>> 1;\n var m = new Array(size);\n m[half] = mid.slice(0);\n var i = half >>> 1;\n while(i > 0) {\n // raise m0[2 * i] and store in m0[i]\n this.pow(m[2 * i], m[i] = []);\n i >>= 1;\n }\n i = 2;\n while(i < half) {\n for(var j = 1; j < i; ++j) {\n var m_i = m[i];\n var m_j = m[j];\n m[i + j] = [\n m_i[0] ^ m_j[0],\n m_i[1] ^ m_j[1],\n m_i[2] ^ m_j[2],\n m_i[3] ^ m_j[3]\n ];\n }\n i *= 2;\n }\n m[0] = [0, 0, 0, 0];\n /* Note: We could avoid storing these by doing composition during multiply\n calculate top half using composition by speed is preferred. */\n for(i = half + 1; i < size; ++i) {\n var c = m[i ^ half];\n m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]];\n }\n return m;\n};\n\n/** Utility functions */\n\nfunction transformIV(iv, blockSize) {\n if(typeof iv === 'string') {\n // convert iv string into byte buffer\n iv = forge.util.createBuffer(iv);\n }\n\n if(forge.util.isArray(iv) && iv.length > 4) {\n // convert iv byte array into byte buffer\n var tmp = iv;\n iv = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n iv.putByte(tmp[i]);\n }\n }\n\n if(iv.length() < blockSize) {\n throw new Error(\n 'Invalid IV length; got ' + iv.length() +\n ' bytes and expected ' + blockSize + ' bytes.');\n }\n\n if(!forge.util.isArray(iv)) {\n // convert iv byte buffer into 32-bit integer array\n var ints = [];\n var blocks = blockSize / 4;\n for(var i = 0; i < blocks; ++i) {\n ints.push(iv.getInt32());\n }\n iv = ints;\n }\n\n return iv;\n}\n\nfunction inc32(block) {\n // increment last 32 bits of block only\n block[block.length - 1] = (block[block.length - 1] + 1) & 0xFFFFFFFF;\n}\n\nfunction from64To32(num) {\n // convert 64-bit number to two BE Int32s\n return [(num / 0x100000000) | 0, num & 0xFFFFFFFF];\n}\n","/**\n * Advanced Encryption Standard (AES) implementation.\n *\n * This implementation is based on the public domain library 'jscrypto' which\n * was written by:\n *\n * Emily Stark (estark@stanford.edu)\n * Mike Hamburg (mhamburg@stanford.edu)\n * Dan Boneh (dabo@cs.stanford.edu)\n *\n * Parts of this code are based on the OpenSSL implementation of AES:\n * http://www.openssl.org\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./cipher');\nrequire('./cipherModes');\nrequire('./util');\n\n/* AES API */\nmodule.exports = forge.aes = forge.aes || {};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('AES-<mode>', key);\n * cipher.start({iv: iv});\n *\n * Creates an AES cipher object to encrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as a string of bytes, an array of bytes,\n * a byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.startEncrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: false,\n mode: mode\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('AES-<mode>', key);\n *\n * Creates an AES cipher object to encrypt data using the given symmetric key.\n *\n * The key may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.createEncryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: false,\n mode: mode\n });\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('AES-<mode>', key);\n * decipher.start({iv: iv});\n *\n * Creates an AES cipher object to decrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as a string of bytes, an array of bytes,\n * a byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.startDecrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: true,\n mode: mode\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('AES-<mode>', key);\n *\n * Creates an AES cipher object to decrypt data using the given symmetric key.\n *\n * The key may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.createDecryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: true,\n mode: mode\n });\n};\n\n/**\n * Creates a new AES cipher algorithm object.\n *\n * @param name the name of the algorithm.\n * @param mode the mode factory function.\n *\n * @return the AES algorithm object.\n */\nforge.aes.Algorithm = function(name, mode) {\n if(!init) {\n initialize();\n }\n var self = this;\n self.name = name;\n self.mode = new mode({\n blockSize: 16,\n cipher: {\n encrypt: function(inBlock, outBlock) {\n return _updateBlock(self._w, inBlock, outBlock, false);\n },\n decrypt: function(inBlock, outBlock) {\n return _updateBlock(self._w, inBlock, outBlock, true);\n }\n }\n });\n self._init = false;\n};\n\n/**\n * Initializes this AES algorithm by expanding its key.\n *\n * @param options the options to use.\n * key the key to use with this algorithm.\n * decrypt true if the algorithm should be initialized for decryption,\n * false for encryption.\n */\nforge.aes.Algorithm.prototype.initialize = function(options) {\n if(this._init) {\n return;\n }\n\n var key = options.key;\n var tmp;\n\n /* Note: The key may be a string of bytes, an array of bytes, a byte\n buffer, or an array of 32-bit integers. If the key is in bytes, then\n it must be 16, 24, or 32 bytes in length. If it is in 32-bit\n integers, it must be 4, 6, or 8 integers long. */\n\n if(typeof key === 'string' &&\n (key.length === 16 || key.length === 24 || key.length === 32)) {\n // convert key string into byte buffer\n key = forge.util.createBuffer(key);\n } else if(forge.util.isArray(key) &&\n (key.length === 16 || key.length === 24 || key.length === 32)) {\n // convert key integer array into byte buffer\n tmp = key;\n key = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n key.putByte(tmp[i]);\n }\n }\n\n // convert key byte buffer into 32-bit integer array\n if(!forge.util.isArray(key)) {\n tmp = key;\n key = [];\n\n // key lengths of 16, 24, 32 bytes allowed\n var len = tmp.length();\n if(len === 16 || len === 24 || len === 32) {\n len = len >>> 2;\n for(var i = 0; i < len; ++i) {\n key.push(tmp.getInt32());\n }\n }\n }\n\n // key must be an array of 32-bit integers by now\n if(!forge.util.isArray(key) ||\n !(key.length === 4 || key.length === 6 || key.length === 8)) {\n throw new Error('Invalid key parameter.');\n }\n\n // encryption operation is always used for these modes\n var mode = this.mode.name;\n var encryptOp = (['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1);\n\n // do key expansion\n this._w = _expandKey(key, options.decrypt && !encryptOp);\n this._init = true;\n};\n\n/**\n * Expands a key. Typically only used for testing.\n *\n * @param key the symmetric key to expand, as an array of 32-bit words.\n * @param decrypt true to expand for decryption, false for encryption.\n *\n * @return the expanded key.\n */\nforge.aes._expandKey = function(key, decrypt) {\n if(!init) {\n initialize();\n }\n return _expandKey(key, decrypt);\n};\n\n/**\n * Updates a single block. Typically only used for testing.\n *\n * @param w the expanded key to use.\n * @param input an array of block-size 32-bit words.\n * @param output an array of block-size 32-bit words.\n * @param decrypt true to decrypt, false to encrypt.\n */\nforge.aes._updateBlock = _updateBlock;\n\n/** Register AES algorithms **/\n\nregisterAlgorithm('AES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('AES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('AES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('AES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('AES-CTR', forge.cipher.modes.ctr);\nregisterAlgorithm('AES-GCM', forge.cipher.modes.gcm);\n\nfunction registerAlgorithm(name, mode) {\n var factory = function() {\n return new forge.aes.Algorithm(name, mode);\n };\n forge.cipher.registerAlgorithm(name, factory);\n}\n\n/** AES implementation **/\n\nvar init = false; // not yet initialized\nvar Nb = 4; // number of words comprising the state (AES = 4)\nvar sbox; // non-linear substitution table used in key expansion\nvar isbox; // inversion of sbox\nvar rcon; // round constant word array\nvar mix; // mix-columns table\nvar imix; // inverse mix-columns table\n\n/**\n * Performs initialization, ie: precomputes tables to optimize for speed.\n *\n * One way to understand how AES works is to imagine that 'addition' and\n * 'multiplication' are interfaces that require certain mathematical\n * properties to hold true (ie: they are associative) but they might have\n * different implementations and produce different kinds of results ...\n * provided that their mathematical properties remain true. AES defines\n * its own methods of addition and multiplication but keeps some important\n * properties the same, ie: associativity and distributivity. The\n * explanation below tries to shed some light on how AES defines addition\n * and multiplication of bytes and 32-bit words in order to perform its\n * encryption and decryption algorithms.\n *\n * The basics:\n *\n * The AES algorithm views bytes as binary representations of polynomials\n * that have either 1 or 0 as the coefficients. It defines the addition\n * or subtraction of two bytes as the XOR operation. It also defines the\n * multiplication of two bytes as a finite field referred to as GF(2^8)\n * (Note: 'GF' means \"Galois Field\" which is a field that contains a finite\n * number of elements so GF(2^8) has 256 elements).\n *\n * This means that any two bytes can be represented as binary polynomials;\n * when they multiplied together and modularly reduced by an irreducible\n * polynomial of the 8th degree, the results are the field GF(2^8). The\n * specific irreducible polynomial that AES uses in hexadecimal is 0x11b.\n * This multiplication is associative with 0x01 as the identity:\n *\n * (b * 0x01 = GF(b, 0x01) = b).\n *\n * The operation GF(b, 0x02) can be performed at the byte level by left\n * shifting b once and then XOR'ing it (to perform the modular reduction)\n * with 0x11b if b is >= 128. Repeated application of the multiplication\n * of 0x02 can be used to implement the multiplication of any two bytes.\n *\n * For instance, multiplying 0x57 and 0x13, denoted as GF(0x57, 0x13), can\n * be performed by factoring 0x13 into 0x01, 0x02, and 0x10. Then these\n * factors can each be multiplied by 0x57 and then added together. To do\n * the multiplication, values for 0x57 multiplied by each of these 3 factors\n * can be precomputed and stored in a table. To add them, the values from\n * the table are XOR'd together.\n *\n * AES also defines addition and multiplication of words, that is 4-byte\n * numbers represented as polynomials of 3 degrees where the coefficients\n * are the values of the bytes.\n *\n * The word [a0, a1, a2, a3] is a polynomial a3x^3 + a2x^2 + a1x + a0.\n *\n * Addition is performed by XOR'ing like powers of x. Multiplication\n * is performed in two steps, the first is an algebriac expansion as\n * you would do normally (where addition is XOR). But the result is\n * a polynomial larger than 3 degrees and thus it cannot fit in a word. So\n * next the result is modularly reduced by an AES-specific polynomial of\n * degree 4 which will always produce a polynomial of less than 4 degrees\n * such that it will fit in a word. In AES, this polynomial is x^4 + 1.\n *\n * The modular product of two polynomials 'a' and 'b' is thus:\n *\n * d(x) = d3x^3 + d2x^2 + d1x + d0\n * with\n * d0 = GF(a0, b0) ^ GF(a3, b1) ^ GF(a2, b2) ^ GF(a1, b3)\n * d1 = GF(a1, b0) ^ GF(a0, b1) ^ GF(a3, b2) ^ GF(a2, b3)\n * d2 = GF(a2, b0) ^ GF(a1, b1) ^ GF(a0, b2) ^ GF(a3, b3)\n * d3 = GF(a3, b0) ^ GF(a2, b1) ^ GF(a1, b2) ^ GF(a0, b3)\n *\n * As a matrix:\n *\n * [d0] = [a0 a3 a2 a1][b0]\n * [d1] [a1 a0 a3 a2][b1]\n * [d2] [a2 a1 a0 a3][b2]\n * [d3] [a3 a2 a1 a0][b3]\n *\n * Special polynomials defined by AES (0x02 == {02}):\n * a(x) = {03}x^3 + {01}x^2 + {01}x + {02}\n * a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}.\n *\n * These polynomials are used in the MixColumns() and InverseMixColumns()\n * operations, respectively, to cause each element in the state to affect\n * the output (referred to as diffusing).\n *\n * RotWord() uses: a0 = a1 = a2 = {00} and a3 = {01}, which is the\n * polynomial x3.\n *\n * The ShiftRows() method modifies the last 3 rows in the state (where\n * the state is 4 words with 4 bytes per word) by shifting bytes cyclically.\n * The 1st byte in the second row is moved to the end of the row. The 1st\n * and 2nd bytes in the third row are moved to the end of the row. The 1st,\n * 2nd, and 3rd bytes are moved in the fourth row.\n *\n * More details on how AES arithmetic works:\n *\n * In the polynomial representation of binary numbers, XOR performs addition\n * and subtraction and multiplication in GF(2^8) denoted as GF(a, b)\n * corresponds with the multiplication of polynomials modulo an irreducible\n * polynomial of degree 8. In other words, for AES, GF(a, b) will multiply\n * polynomial 'a' with polynomial 'b' and then do a modular reduction by\n * an AES-specific irreducible polynomial of degree 8.\n *\n * A polynomial is irreducible if its only divisors are one and itself. For\n * the AES algorithm, this irreducible polynomial is:\n *\n * m(x) = x^8 + x^4 + x^3 + x + 1,\n *\n * or {01}{1b} in hexadecimal notation, where each coefficient is a bit:\n * 100011011 = 283 = 0x11b.\n *\n * For example, GF(0x57, 0x83) = 0xc1 because\n *\n * 0x57 = 87 = 01010111 = x^6 + x^4 + x^2 + x + 1\n * 0x85 = 131 = 10000101 = x^7 + x + 1\n *\n * (x^6 + x^4 + x^2 + x + 1) * (x^7 + x + 1)\n * = x^13 + x^11 + x^9 + x^8 + x^7 +\n * x^7 + x^5 + x^3 + x^2 + x +\n * x^6 + x^4 + x^2 + x + 1\n * = x^13 + x^11 + x^9 + x^8 + x^6 + x^5 + x^4 + x^3 + 1 = y\n * y modulo (x^8 + x^4 + x^3 + x + 1)\n * = x^7 + x^6 + 1.\n *\n * The modular reduction by m(x) guarantees the result will be a binary\n * polynomial of less than degree 8, so that it can fit in a byte.\n *\n * The operation to multiply a binary polynomial b with x (the polynomial\n * x in binary representation is 00000010) is:\n *\n * b_7x^8 + b_6x^7 + b_5x^6 + b_4x^5 + b_3x^4 + b_2x^3 + b_1x^2 + b_0x^1\n *\n * To get GF(b, x) we must reduce that by m(x). If b_7 is 0 (that is the\n * most significant bit is 0 in b) then the result is already reduced. If\n * it is 1, then we can reduce it by subtracting m(x) via an XOR.\n *\n * It follows that multiplication by x (00000010 or 0x02) can be implemented\n * by performing a left shift followed by a conditional bitwise XOR with\n * 0x1b. This operation on bytes is denoted by xtime(). Multiplication by\n * higher powers of x can be implemented by repeated application of xtime().\n *\n * By adding intermediate results, multiplication by any constant can be\n * implemented. For instance:\n *\n * GF(0x57, 0x13) = 0xfe because:\n *\n * xtime(b) = (b & 128) ? (b << 1 ^ 0x11b) : (b << 1)\n *\n * Note: We XOR with 0x11b instead of 0x1b because in javascript our\n * datatype for b can be larger than 1 byte, so a left shift will not\n * automatically eliminate bits that overflow a byte ... by XOR'ing the\n * overflow bit with 1 (the extra one from 0x11b) we zero it out.\n *\n * GF(0x57, 0x02) = xtime(0x57) = 0xae\n * GF(0x57, 0x04) = xtime(0xae) = 0x47\n * GF(0x57, 0x08) = xtime(0x47) = 0x8e\n * GF(0x57, 0x10) = xtime(0x8e) = 0x07\n *\n * GF(0x57, 0x13) = GF(0x57, (0x01 ^ 0x02 ^ 0x10))\n *\n * And by the distributive property (since XOR is addition and GF() is\n * multiplication):\n *\n * = GF(0x57, 0x01) ^ GF(0x57, 0x02) ^ GF(0x57, 0x10)\n * = 0x57 ^ 0xae ^ 0x07\n * = 0xfe.\n */\nfunction initialize() {\n init = true;\n\n /* Populate the Rcon table. These are the values given by\n [x^(i-1),{00},{00},{00}] where x^(i-1) are powers of x (and x = 0x02)\n in the field of GF(2^8), where i starts at 1.\n\n rcon[0] = [0x00, 0x00, 0x00, 0x00]\n rcon[1] = [0x01, 0x00, 0x00, 0x00] 2^(1-1) = 2^0 = 1\n rcon[2] = [0x02, 0x00, 0x00, 0x00] 2^(2-1) = 2^1 = 2\n ...\n rcon[9] = [0x1B, 0x00, 0x00, 0x00] 2^(9-1) = 2^8 = 0x1B\n rcon[10] = [0x36, 0x00, 0x00, 0x00] 2^(10-1) = 2^9 = 0x36\n\n We only store the first byte because it is the only one used.\n */\n rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36];\n\n // compute xtime table which maps i onto GF(i, 0x02)\n var xtime = new Array(256);\n for(var i = 0; i < 128; ++i) {\n xtime[i] = i << 1;\n xtime[i + 128] = (i + 128) << 1 ^ 0x11B;\n }\n\n // compute all other tables\n sbox = new Array(256);\n isbox = new Array(256);\n mix = new Array(4);\n imix = new Array(4);\n for(var i = 0; i < 4; ++i) {\n mix[i] = new Array(256);\n imix[i] = new Array(256);\n }\n var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime;\n for(var i = 0; i < 256; ++i) {\n /* We need to generate the SubBytes() sbox and isbox tables so that\n we can perform byte substitutions. This requires us to traverse\n all of the elements in GF, find their multiplicative inverses,\n and apply to each the following affine transformation:\n\n bi' = bi ^ b(i + 4) mod 8 ^ b(i + 5) mod 8 ^ b(i + 6) mod 8 ^\n b(i + 7) mod 8 ^ ci\n for 0 <= i < 8, where bi is the ith bit of the byte, and ci is the\n ith bit of a byte c with the value {63} or {01100011}.\n\n It is possible to traverse every possible value in a Galois field\n using what is referred to as a 'generator'. There are many\n generators (128 out of 256): 3,5,6,9,11,82 to name a few. To fully\n traverse GF we iterate 255 times, multiplying by our generator\n each time.\n\n On each iteration we can determine the multiplicative inverse for\n the current element.\n\n Suppose there is an element in GF 'e'. For a given generator 'g',\n e = g^x. The multiplicative inverse of e is g^(255 - x). It turns\n out that if use the inverse of a generator as another generator\n it will produce all of the corresponding multiplicative inverses\n at the same time. For this reason, we choose 5 as our inverse\n generator because it only requires 2 multiplies and 1 add and its\n inverse, 82, requires relatively few operations as well.\n\n In order to apply the affine transformation, the multiplicative\n inverse 'ei' of 'e' can be repeatedly XOR'd (4 times) with a\n bit-cycling of 'ei'. To do this 'ei' is first stored in 's' and\n 'x'. Then 's' is left shifted and the high bit of 's' is made the\n low bit. The resulting value is stored in 's'. Then 'x' is XOR'd\n with 's' and stored in 'x'. On each subsequent iteration the same\n operation is performed. When 4 iterations are complete, 'x' is\n XOR'd with 'c' (0x63) and the transformed value is stored in 'x'.\n For example:\n\n s = 01000001\n x = 01000001\n\n iteration 1: s = 10000010, x ^= s\n iteration 2: s = 00000101, x ^= s\n iteration 3: s = 00001010, x ^= s\n iteration 4: s = 00010100, x ^= s\n x ^= 0x63\n\n This can be done with a loop where s = (s << 1) | (s >> 7). However,\n it can also be done by using a single 16-bit (in this case 32-bit)\n number 'sx'. Since XOR is an associative operation, we can set 'sx'\n to 'ei' and then XOR it with 'sx' left-shifted 1,2,3, and 4 times.\n The most significant bits will flow into the high 8 bit positions\n and be correctly XOR'd with one another. All that remains will be\n to cycle the high 8 bits by XOR'ing them all with the lower 8 bits\n afterwards.\n\n At the same time we're populating sbox and isbox we can precompute\n the multiplication we'll need to do to do MixColumns() later.\n */\n\n // apply affine transformation\n sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4);\n sx = (sx >> 8) ^ (sx & 255) ^ 0x63;\n\n // update tables\n sbox[e] = sx;\n isbox[sx] = e;\n\n /* Mixing columns is done using matrix multiplication. The columns\n that are to be mixed are each a single word in the current state.\n The state has Nb columns (4 columns). Therefore each column is a\n 4 byte word. So to mix the columns in a single column 'c' where\n its rows are r0, r1, r2, and r3, we use the following matrix\n multiplication:\n\n [2 3 1 1]*[r0,c]=[r'0,c]\n [1 2 3 1] [r1,c] [r'1,c]\n [1 1 2 3] [r2,c] [r'2,c]\n [3 1 1 2] [r3,c] [r'3,c]\n\n r0, r1, r2, and r3 are each 1 byte of one of the words in the\n state (a column). To do matrix multiplication for each mixed\n column c' we multiply the corresponding row from the left matrix\n with the corresponding column from the right matrix. In total, we\n get 4 equations:\n\n r0,c' = 2*r0,c + 3*r1,c + 1*r2,c + 1*r3,c\n r1,c' = 1*r0,c + 2*r1,c + 3*r2,c + 1*r3,c\n r2,c' = 1*r0,c + 1*r1,c + 2*r2,c + 3*r3,c\n r3,c' = 3*r0,c + 1*r1,c + 1*r2,c + 2*r3,c\n\n As usual, the multiplication is as previously defined and the\n addition is XOR. In order to optimize mixing columns we can store\n the multiplication results in tables. If you think of the whole\n column as a word (it might help to visualize by mentally rotating\n the equations above by counterclockwise 90 degrees) then you can\n see that it would be useful to map the multiplications performed on\n each byte (r0, r1, r2, r3) onto a word as well. For instance, we\n could map 2*r0,1*r0,1*r0,3*r0 onto a word by storing 2*r0 in the\n highest 8 bits and 3*r0 in the lowest 8 bits (with the other two\n respectively in the middle). This means that a table can be\n constructed that uses r0 as an index to the word. We can do the\n same with r1, r2, and r3, creating a total of 4 tables.\n\n To construct a full c', we can just look up each byte of c in\n their respective tables and XOR the results together.\n\n Also, to build each table we only have to calculate the word\n for 2,1,1,3 for every byte ... which we can do on each iteration\n of this loop since we will iterate over every byte. After we have\n calculated 2,1,1,3 we can get the results for the other tables\n by cycling the byte at the end to the beginning. For instance\n we can take the result of table 2,1,1,3 and produce table 3,2,1,1\n by moving the right most byte to the left most position just like\n how you can imagine the 3 moved out of 2,1,1,3 and to the front\n to produce 3,2,1,1.\n\n There is another optimization in that the same multiples of\n the current element we need in order to advance our generator\n to the next iteration can be reused in performing the 2,1,1,3\n calculation. We also calculate the inverse mix column tables,\n with e,9,d,b being the inverse of 2,1,1,3.\n\n When we're done, and we need to actually mix columns, the first\n byte of each state word should be put through mix[0] (2,1,1,3),\n the second through mix[1] (3,2,1,1) and so forth. Then they should\n be XOR'd together to produce the fully mixed column.\n */\n\n // calculate mix and imix table values\n sx2 = xtime[sx];\n e2 = xtime[e];\n e4 = xtime[e2];\n e8 = xtime[e4];\n me =\n (sx2 << 24) ^ // 2\n (sx << 16) ^ // 1\n (sx << 8) ^ // 1\n (sx ^ sx2); // 3\n ime =\n (e2 ^ e4 ^ e8) << 24 ^ // E (14)\n (e ^ e8) << 16 ^ // 9\n (e ^ e4 ^ e8) << 8 ^ // D (13)\n (e ^ e2 ^ e8); // B (11)\n // produce each of the mix tables by rotating the 2,1,1,3 value\n for(var n = 0; n < 4; ++n) {\n mix[n][e] = me;\n imix[n][sx] = ime;\n // cycle the right most byte to the left most position\n // ie: 2,1,1,3 becomes 3,2,1,1\n me = me << 24 | me >>> 8;\n ime = ime << 24 | ime >>> 8;\n }\n\n // get next element and inverse\n if(e === 0) {\n // 1 is the inverse of 1\n e = ei = 1;\n } else {\n // e = 2e + 2*2*2*(10e)) = multiply e by 82 (chosen generator)\n // ei = ei + 2*2*ei = multiply ei by 5 (inverse generator)\n e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]];\n ei ^= xtime[xtime[ei]];\n }\n }\n}\n\n/**\n * Generates a key schedule using the AES key expansion algorithm.\n *\n * The AES algorithm takes the Cipher Key, K, and performs a Key Expansion\n * routine to generate a key schedule. The Key Expansion generates a total\n * of Nb*(Nr + 1) words: the algorithm requires an initial set of Nb words,\n * and each of the Nr rounds requires Nb words of key data. The resulting\n * key schedule consists of a linear array of 4-byte words, denoted [wi ],\n * with i in the range 0 <= i < Nb(Nr + 1).\n *\n * KeyExpansion(byte key[4*Nk], word w[Nb*(Nr+1)], Nk)\n * AES-128 (Nb=4, Nk=4, Nr=10)\n * AES-192 (Nb=4, Nk=6, Nr=12)\n * AES-256 (Nb=4, Nk=8, Nr=14)\n * Note: Nr=Nk+6.\n *\n * Nb is the number of columns (32-bit words) comprising the State (or\n * number of bytes in a block). For AES, Nb=4.\n *\n * @param key the key to schedule (as an array of 32-bit words).\n * @param decrypt true to modify the key schedule to decrypt, false not to.\n *\n * @return the generated key schedule.\n */\nfunction _expandKey(key, decrypt) {\n // copy the key's words to initialize the key schedule\n var w = key.slice(0);\n\n /* RotWord() will rotate a word, moving the first byte to the last\n byte's position (shifting the other bytes left).\n\n We will be getting the value of Rcon at i / Nk. 'i' will iterate\n from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in\n a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from\n 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will\n increase by 1. We use a counter iNk to keep track of this.\n */\n\n // go through the rounds expanding the key\n var temp, iNk = 1;\n var Nk = w.length;\n var Nr1 = Nk + 6 + 1;\n var end = Nb * Nr1;\n for(var i = Nk; i < end; ++i) {\n temp = w[i - 1];\n if(i % Nk === 0) {\n // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk]\n temp =\n sbox[temp >>> 16 & 255] << 24 ^\n sbox[temp >>> 8 & 255] << 16 ^\n sbox[temp & 255] << 8 ^\n sbox[temp >>> 24] ^ (rcon[iNk] << 24);\n iNk++;\n } else if(Nk > 6 && (i % Nk === 4)) {\n // temp = SubWord(temp)\n temp =\n sbox[temp >>> 24] << 24 ^\n sbox[temp >>> 16 & 255] << 16 ^\n sbox[temp >>> 8 & 255] << 8 ^\n sbox[temp & 255];\n }\n w[i] = w[i - Nk] ^ temp;\n }\n\n /* When we are updating a cipher block we always use the code path for\n encryption whether we are decrypting or not (to shorten code and\n simplify the generation of look up tables). However, because there\n are differences in the decryption algorithm, other than just swapping\n in different look up tables, we must transform our key schedule to\n account for these changes:\n\n 1. The decryption algorithm gets its key rounds in reverse order.\n 2. The decryption algorithm adds the round key before mixing columns\n instead of afterwards.\n\n We don't need to modify our key schedule to handle the first case,\n we can just traverse the key schedule in reverse order when decrypting.\n\n The second case requires a little work.\n\n The tables we built for performing rounds will take an input and then\n perform SubBytes() and MixColumns() or, for the decrypt version,\n InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires\n us to AddRoundKey() before InvMixColumns(). This means we'll need to\n apply some transformations to the round key to inverse-mix its columns\n so they'll be correct for moving AddRoundKey() to after the state has\n had its columns inverse-mixed.\n\n To inverse-mix the columns of the state when we're decrypting we use a\n lookup table that will apply InvSubBytes() and InvMixColumns() at the\n same time. However, the round key's bytes are not inverse-substituted\n in the decryption algorithm. To get around this problem, we can first\n substitute the bytes in the round key so that when we apply the\n transformation via the InvSubBytes()+InvMixColumns() table, it will\n undo our substitution leaving us with the original value that we\n want -- and then inverse-mix that value.\n\n This change will correctly alter our key schedule so that we can XOR\n each round key with our already transformed decryption state. This\n allows us to use the same code path as the encryption algorithm.\n\n We make one more change to the decryption key. Since the decryption\n algorithm runs in reverse from the encryption algorithm, we reverse\n the order of the round keys to avoid having to iterate over the key\n schedule backwards when running the encryption algorithm later in\n decryption mode. In addition to reversing the order of the round keys,\n we also swap each round key's 2nd and 4th rows. See the comments\n section where rounds are performed for more details about why this is\n done. These changes are done inline with the other substitution\n described above.\n */\n if(decrypt) {\n var tmp;\n var m0 = imix[0];\n var m1 = imix[1];\n var m2 = imix[2];\n var m3 = imix[3];\n var wnew = w.slice(0);\n end = w.length;\n for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) {\n // do not sub the first or last round key (round keys are Nb\n // words) as no column mixing is performed before they are added,\n // but do change the key order\n if(i === 0 || i === (end - Nb)) {\n wnew[i] = w[wi];\n wnew[i + 1] = w[wi + 3];\n wnew[i + 2] = w[wi + 2];\n wnew[i + 3] = w[wi + 1];\n } else {\n // substitute each round key byte because the inverse-mix\n // table will inverse-substitute it (effectively cancel the\n // substitution because round key bytes aren't sub'd in\n // decryption mode) and swap indexes 3 and 1\n for(var n = 0; n < Nb; ++n) {\n tmp = w[wi + n];\n wnew[i + (3&-n)] =\n m0[sbox[tmp >>> 24]] ^\n m1[sbox[tmp >>> 16 & 255]] ^\n m2[sbox[tmp >>> 8 & 255]] ^\n m3[sbox[tmp & 255]];\n }\n }\n }\n w = wnew;\n }\n\n return w;\n}\n\n/**\n * Updates a single block (16 bytes) using AES. The update will either\n * encrypt or decrypt the block.\n *\n * @param w the key schedule.\n * @param input the input block (an array of 32-bit words).\n * @param output the updated output block.\n * @param decrypt true to decrypt the block, false to encrypt it.\n */\nfunction _updateBlock(w, input, output, decrypt) {\n /*\n Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])\n begin\n byte state[4,Nb]\n state = in\n AddRoundKey(state, w[0, Nb-1])\n for round = 1 step 1 to Nr-1\n SubBytes(state)\n ShiftRows(state)\n MixColumns(state)\n AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])\n end for\n SubBytes(state)\n ShiftRows(state)\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n out = state\n end\n\n InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])\n begin\n byte state[4,Nb]\n state = in\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n for round = Nr-1 step -1 downto 1\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])\n InvMixColumns(state)\n end for\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[0, Nb-1])\n out = state\n end\n */\n\n // Encrypt: AddRoundKey(state, w[0, Nb-1])\n // Decrypt: AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n var Nr = w.length / 4 - 1;\n var m0, m1, m2, m3, sub;\n if(decrypt) {\n m0 = imix[0];\n m1 = imix[1];\n m2 = imix[2];\n m3 = imix[3];\n sub = isbox;\n } else {\n m0 = mix[0];\n m1 = mix[1];\n m2 = mix[2];\n m3 = mix[3];\n sub = sbox;\n }\n var a, b, c, d, a2, b2, c2;\n a = input[0] ^ w[0];\n b = input[decrypt ? 3 : 1] ^ w[1];\n c = input[2] ^ w[2];\n d = input[decrypt ? 1 : 3] ^ w[3];\n var i = 3;\n\n /* In order to share code we follow the encryption algorithm when both\n encrypting and decrypting. To account for the changes required in the\n decryption algorithm, we use different lookup tables when decrypting\n and use a modified key schedule to account for the difference in the\n order of transformations applied when performing rounds. We also get\n key rounds in reverse order (relative to encryption). */\n for(var round = 1; round < Nr; ++round) {\n /* As described above, we'll be using table lookups to perform the\n column mixing. Each column is stored as a word in the state (the\n array 'input' has one column as a word at each index). In order to\n mix a column, we perform these transformations on each row in c,\n which is 1 byte in each word. The new column for c0 is c'0:\n\n m0 m1 m2 m3\n r0,c'0 = 2*r0,c0 + 3*r1,c0 + 1*r2,c0 + 1*r3,c0\n r1,c'0 = 1*r0,c0 + 2*r1,c0 + 3*r2,c0 + 1*r3,c0\n r2,c'0 = 1*r0,c0 + 1*r1,c0 + 2*r2,c0 + 3*r3,c0\n r3,c'0 = 3*r0,c0 + 1*r1,c0 + 1*r2,c0 + 2*r3,c0\n\n So using mix tables where c0 is a word with r0 being its upper\n 8 bits and r3 being its lower 8 bits:\n\n m0[c0 >> 24] will yield this word: [2*r0,1*r0,1*r0,3*r0]\n ...\n m3[c0 & 255] will yield this word: [1*r3,1*r3,3*r3,2*r3]\n\n Therefore to mix the columns in each word in the state we\n do the following (& 255 omitted for brevity):\n c'0,r0 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r1 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r2 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r3 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n\n However, before mixing, the algorithm requires us to perform\n ShiftRows(). The ShiftRows() transformation cyclically shifts the\n last 3 rows of the state over different offsets. The first row\n (r = 0) is not shifted.\n\n s'_r,c = s_r,(c + shift(r, Nb) mod Nb\n for 0 < r < 4 and 0 <= c < Nb and\n shift(1, 4) = 1\n shift(2, 4) = 2\n shift(3, 4) = 3.\n\n This causes the first byte in r = 1 to be moved to the end of\n the row, the first 2 bytes in r = 2 to be moved to the end of\n the row, the first 3 bytes in r = 3 to be moved to the end of\n the row:\n\n r1: [c0 c1 c2 c3] => [c1 c2 c3 c0]\n r2: [c0 c1 c2 c3] [c2 c3 c0 c1]\n r3: [c0 c1 c2 c3] [c3 c0 c1 c2]\n\n We can make these substitutions inline with our column mixing to\n generate an updated set of equations to produce each word in the\n state (note the columns have changed positions):\n\n c0 c1 c2 c3 => c0 c1 c2 c3\n c0 c1 c2 c3 c1 c2 c3 c0 (cycled 1 byte)\n c0 c1 c2 c3 c2 c3 c0 c1 (cycled 2 bytes)\n c0 c1 c2 c3 c3 c0 c1 c2 (cycled 3 bytes)\n\n Therefore:\n\n c'0 = 2*r0,c0 + 3*r1,c1 + 1*r2,c2 + 1*r3,c3\n c'0 = 1*r0,c0 + 2*r1,c1 + 3*r2,c2 + 1*r3,c3\n c'0 = 1*r0,c0 + 1*r1,c1 + 2*r2,c2 + 3*r3,c3\n c'0 = 3*r0,c0 + 1*r1,c1 + 1*r2,c2 + 2*r3,c3\n\n c'1 = 2*r0,c1 + 3*r1,c2 + 1*r2,c3 + 1*r3,c0\n c'1 = 1*r0,c1 + 2*r1,c2 + 3*r2,c3 + 1*r3,c0\n c'1 = 1*r0,c1 + 1*r1,c2 + 2*r2,c3 + 3*r3,c0\n c'1 = 3*r0,c1 + 1*r1,c2 + 1*r2,c3 + 2*r3,c0\n\n ... and so forth for c'2 and c'3. The important distinction is\n that the columns are cycling, with c0 being used with the m0\n map when calculating c0, but c1 being used with the m0 map when\n calculating c1 ... and so forth.\n\n When performing the inverse we transform the mirror image and\n skip the bottom row, instead of the top one, and move upwards:\n\n c3 c2 c1 c0 => c0 c3 c2 c1 (cycled 3 bytes) *same as encryption\n c3 c2 c1 c0 c1 c0 c3 c2 (cycled 2 bytes)\n c3 c2 c1 c0 c2 c1 c0 c3 (cycled 1 byte) *same as encryption\n c3 c2 c1 c0 c3 c2 c1 c0\n\n If you compare the resulting matrices for ShiftRows()+MixColumns()\n and for InvShiftRows()+InvMixColumns() the 2nd and 4th columns are\n different (in encrypt mode vs. decrypt mode). So in order to use\n the same code to handle both encryption and decryption, we will\n need to do some mapping.\n\n If in encryption mode we let a=c0, b=c1, c=c2, d=c3, and r<N> be\n a row number in the state, then the resulting matrix in encryption\n mode for applying the above transformations would be:\n\n r1: a b c d\n r2: b c d a\n r3: c d a b\n r4: d a b c\n\n If we did the same in decryption mode we would get:\n\n r1: a d c b\n r2: b a d c\n r3: c b a d\n r4: d c b a\n\n If instead we swap d and b (set b=c3 and d=c1), then we get:\n\n r1: a b c d\n r2: d a b c\n r3: c d a b\n r4: b c d a\n\n Now the 1st and 3rd rows are the same as the encryption matrix. All\n we need to do then to make the mapping exactly the same is to swap\n the 2nd and 4th rows when in decryption mode. To do this without\n having to do it on each iteration, we swapped the 2nd and 4th rows\n in the decryption key schedule. We also have to do the swap above\n when we first pull in the input and when we set the final output. */\n a2 =\n m0[a >>> 24] ^\n m1[b >>> 16 & 255] ^\n m2[c >>> 8 & 255] ^\n m3[d & 255] ^ w[++i];\n b2 =\n m0[b >>> 24] ^\n m1[c >>> 16 & 255] ^\n m2[d >>> 8 & 255] ^\n m3[a & 255] ^ w[++i];\n c2 =\n m0[c >>> 24] ^\n m1[d >>> 16 & 255] ^\n m2[a >>> 8 & 255] ^\n m3[b & 255] ^ w[++i];\n d =\n m0[d >>> 24] ^\n m1[a >>> 16 & 255] ^\n m2[b >>> 8 & 255] ^\n m3[c & 255] ^ w[++i];\n a = a2;\n b = b2;\n c = c2;\n }\n\n /*\n Encrypt:\n SubBytes(state)\n ShiftRows(state)\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n\n Decrypt:\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[0, Nb-1])\n */\n // Note: rows are shifted inline\n output[0] =\n (sub[a >>> 24] << 24) ^\n (sub[b >>> 16 & 255] << 16) ^\n (sub[c >>> 8 & 255] << 8) ^\n (sub[d & 255]) ^ w[++i];\n output[decrypt ? 3 : 1] =\n (sub[b >>> 24] << 24) ^\n (sub[c >>> 16 & 255] << 16) ^\n (sub[d >>> 8 & 255] << 8) ^\n (sub[a & 255]) ^ w[++i];\n output[2] =\n (sub[c >>> 24] << 24) ^\n (sub[d >>> 16 & 255] << 16) ^\n (sub[a >>> 8 & 255] << 8) ^\n (sub[b & 255]) ^ w[++i];\n output[decrypt ? 1 : 3] =\n (sub[d >>> 24] << 24) ^\n (sub[a >>> 16 & 255] << 16) ^\n (sub[b >>> 8 & 255] << 8) ^\n (sub[c & 255]) ^ w[++i];\n}\n\n/**\n * Deprecated. Instead, use:\n *\n * forge.cipher.createCipher('AES-<mode>', key);\n * forge.cipher.createDecipher('AES-<mode>', key);\n *\n * Creates a deprecated AES cipher object. This object's mode will default to\n * CBC (cipher-block-chaining).\n *\n * The key and iv may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param options the options to use.\n * key the symmetric key to use.\n * output the buffer to write to.\n * decrypt true for decryption, false for encryption.\n * mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nfunction _createCipher(options) {\n options = options || {};\n var mode = (options.mode || 'CBC').toUpperCase();\n var algorithm = 'AES-' + mode;\n\n var cipher;\n if(options.decrypt) {\n cipher = forge.cipher.createDecipher(algorithm, options.key);\n } else {\n cipher = forge.cipher.createCipher(algorithm, options.key);\n }\n\n // backwards compatible start API\n var start = cipher.start;\n cipher.start = function(iv, options) {\n // backwards compatibility: support second arg as output buffer\n var output = null;\n if(options instanceof forge.util.ByteBuffer) {\n output = options;\n options = {};\n }\n options = options || {};\n options.output = output;\n options.iv = iv;\n start.call(cipher, options);\n };\n\n return cipher;\n}\n","/**\n * Object IDs for ASN.1.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\n\nforge.pki = forge.pki || {};\nvar oids = module.exports = forge.pki.oids = forge.oids = forge.oids || {};\n\n// set id to name mapping and name to id mapping\nfunction _IN(id, name) {\n oids[id] = name;\n oids[name] = id;\n}\n// set id to name mapping only\nfunction _I_(id, name) {\n oids[id] = name;\n}\n\n// algorithm OIDs\n_IN('1.2.840.113549.1.1.1', 'rsaEncryption');\n// Note: md2 & md4 not implemented\n//_IN('1.2.840.113549.1.1.2', 'md2WithRSAEncryption');\n//_IN('1.2.840.113549.1.1.3', 'md4WithRSAEncryption');\n_IN('1.2.840.113549.1.1.4', 'md5WithRSAEncryption');\n_IN('1.2.840.113549.1.1.5', 'sha1WithRSAEncryption');\n_IN('1.2.840.113549.1.1.7', 'RSAES-OAEP');\n_IN('1.2.840.113549.1.1.8', 'mgf1');\n_IN('1.2.840.113549.1.1.9', 'pSpecified');\n_IN('1.2.840.113549.1.1.10', 'RSASSA-PSS');\n_IN('1.2.840.113549.1.1.11', 'sha256WithRSAEncryption');\n_IN('1.2.840.113549.1.1.12', 'sha384WithRSAEncryption');\n_IN('1.2.840.113549.1.1.13', 'sha512WithRSAEncryption');\n// Edwards-curve Digital Signature Algorithm (EdDSA) Ed25519\n_IN('1.3.101.112', 'EdDSA25519');\n\n_IN('1.2.840.10040.4.3', 'dsa-with-sha1');\n\n_IN('1.3.14.3.2.7', 'desCBC');\n\n_IN('1.3.14.3.2.26', 'sha1');\n// Deprecated equivalent of sha1WithRSAEncryption\n_IN('1.3.14.3.2.29', 'sha1WithRSASignature');\n_IN('2.16.840.1.101.3.4.2.1', 'sha256');\n_IN('2.16.840.1.101.3.4.2.2', 'sha384');\n_IN('2.16.840.1.101.3.4.2.3', 'sha512');\n_IN('2.16.840.1.101.3.4.2.4', 'sha224');\n_IN('2.16.840.1.101.3.4.2.5', 'sha512-224');\n_IN('2.16.840.1.101.3.4.2.6', 'sha512-256');\n_IN('1.2.840.113549.2.2', 'md2');\n_IN('1.2.840.113549.2.5', 'md5');\n\n// pkcs#7 content types\n_IN('1.2.840.113549.1.7.1', 'data');\n_IN('1.2.840.113549.1.7.2', 'signedData');\n_IN('1.2.840.113549.1.7.3', 'envelopedData');\n_IN('1.2.840.113549.1.7.4', 'signedAndEnvelopedData');\n_IN('1.2.840.113549.1.7.5', 'digestedData');\n_IN('1.2.840.113549.1.7.6', 'encryptedData');\n\n// pkcs#9 oids\n_IN('1.2.840.113549.1.9.1', 'emailAddress');\n_IN('1.2.840.113549.1.9.2', 'unstructuredName');\n_IN('1.2.840.113549.1.9.3', 'contentType');\n_IN('1.2.840.113549.1.9.4', 'messageDigest');\n_IN('1.2.840.113549.1.9.5', 'signingTime');\n_IN('1.2.840.113549.1.9.6', 'counterSignature');\n_IN('1.2.840.113549.1.9.7', 'challengePassword');\n_IN('1.2.840.113549.1.9.8', 'unstructuredAddress');\n_IN('1.2.840.113549.1.9.14', 'extensionRequest');\n\n_IN('1.2.840.113549.1.9.20', 'friendlyName');\n_IN('1.2.840.113549.1.9.21', 'localKeyId');\n_IN('1.2.840.113549.1.9.22.1', 'x509Certificate');\n\n// pkcs#12 safe bags\n_IN('1.2.840.113549.1.12.10.1.1', 'keyBag');\n_IN('1.2.840.113549.1.12.10.1.2', 'pkcs8ShroudedKeyBag');\n_IN('1.2.840.113549.1.12.10.1.3', 'certBag');\n_IN('1.2.840.113549.1.12.10.1.4', 'crlBag');\n_IN('1.2.840.113549.1.12.10.1.5', 'secretBag');\n_IN('1.2.840.113549.1.12.10.1.6', 'safeContentsBag');\n\n// password-based-encryption for pkcs#12\n_IN('1.2.840.113549.1.5.13', 'pkcs5PBES2');\n_IN('1.2.840.113549.1.5.12', 'pkcs5PBKDF2');\n\n_IN('1.2.840.113549.1.12.1.1', 'pbeWithSHAAnd128BitRC4');\n_IN('1.2.840.113549.1.12.1.2', 'pbeWithSHAAnd40BitRC4');\n_IN('1.2.840.113549.1.12.1.3', 'pbeWithSHAAnd3-KeyTripleDES-CBC');\n_IN('1.2.840.113549.1.12.1.4', 'pbeWithSHAAnd2-KeyTripleDES-CBC');\n_IN('1.2.840.113549.1.12.1.5', 'pbeWithSHAAnd128BitRC2-CBC');\n_IN('1.2.840.113549.1.12.1.6', 'pbewithSHAAnd40BitRC2-CBC');\n\n// hmac OIDs\n_IN('1.2.840.113549.2.7', 'hmacWithSHA1');\n_IN('1.2.840.113549.2.8', 'hmacWithSHA224');\n_IN('1.2.840.113549.2.9', 'hmacWithSHA256');\n_IN('1.2.840.113549.2.10', 'hmacWithSHA384');\n_IN('1.2.840.113549.2.11', 'hmacWithSHA512');\n\n// symmetric key algorithm oids\n_IN('1.2.840.113549.3.7', 'des-EDE3-CBC');\n_IN('2.16.840.1.101.3.4.1.2', 'aes128-CBC');\n_IN('2.16.840.1.101.3.4.1.22', 'aes192-CBC');\n_IN('2.16.840.1.101.3.4.1.42', 'aes256-CBC');\n\n// certificate issuer/subject OIDs\n_IN('2.5.4.3', 'commonName');\n_IN('2.5.4.4', 'surname');\n_IN('2.5.4.5', 'serialNumber');\n_IN('2.5.4.6', 'countryName');\n_IN('2.5.4.7', 'localityName');\n_IN('2.5.4.8', 'stateOrProvinceName');\n_IN('2.5.4.9', 'streetAddress');\n_IN('2.5.4.10', 'organizationName');\n_IN('2.5.4.11', 'organizationalUnitName');\n_IN('2.5.4.12', 'title');\n_IN('2.5.4.13', 'description');\n_IN('2.5.4.15', 'businessCategory');\n_IN('2.5.4.17', 'postalCode');\n_IN('2.5.4.42', 'givenName');\n_IN('1.3.6.1.4.1.311.60.2.1.2', 'jurisdictionOfIncorporationStateOrProvinceName');\n_IN('1.3.6.1.4.1.311.60.2.1.3', 'jurisdictionOfIncorporationCountryName');\n\n// X.509 extension OIDs\n_IN('2.16.840.1.113730.1.1', 'nsCertType');\n_IN('2.16.840.1.113730.1.13', 'nsComment'); // deprecated in theory; still widely used\n_I_('2.5.29.1', 'authorityKeyIdentifier'); // deprecated, use .35\n_I_('2.5.29.2', 'keyAttributes'); // obsolete use .37 or .15\n_I_('2.5.29.3', 'certificatePolicies'); // deprecated, use .32\n_I_('2.5.29.4', 'keyUsageRestriction'); // obsolete use .37 or .15\n_I_('2.5.29.5', 'policyMapping'); // deprecated use .33\n_I_('2.5.29.6', 'subtreesConstraint'); // obsolete use .30\n_I_('2.5.29.7', 'subjectAltName'); // deprecated use .17\n_I_('2.5.29.8', 'issuerAltName'); // deprecated use .18\n_I_('2.5.29.9', 'subjectDirectoryAttributes');\n_I_('2.5.29.10', 'basicConstraints'); // deprecated use .19\n_I_('2.5.29.11', 'nameConstraints'); // deprecated use .30\n_I_('2.5.29.12', 'policyConstraints'); // deprecated use .36\n_I_('2.5.29.13', 'basicConstraints'); // deprecated use .19\n_IN('2.5.29.14', 'subjectKeyIdentifier');\n_IN('2.5.29.15', 'keyUsage');\n_I_('2.5.29.16', 'privateKeyUsagePeriod');\n_IN('2.5.29.17', 'subjectAltName');\n_IN('2.5.29.18', 'issuerAltName');\n_IN('2.5.29.19', 'basicConstraints');\n_I_('2.5.29.20', 'cRLNumber');\n_I_('2.5.29.21', 'cRLReason');\n_I_('2.5.29.22', 'expirationDate');\n_I_('2.5.29.23', 'instructionCode');\n_I_('2.5.29.24', 'invalidityDate');\n_I_('2.5.29.25', 'cRLDistributionPoints'); // deprecated use .31\n_I_('2.5.29.26', 'issuingDistributionPoint'); // deprecated use .28\n_I_('2.5.29.27', 'deltaCRLIndicator');\n_I_('2.5.29.28', 'issuingDistributionPoint');\n_I_('2.5.29.29', 'certificateIssuer');\n_I_('2.5.29.30', 'nameConstraints');\n_IN('2.5.29.31', 'cRLDistributionPoints');\n_IN('2.5.29.32', 'certificatePolicies');\n_I_('2.5.29.33', 'policyMappings');\n_I_('2.5.29.34', 'policyConstraints'); // deprecated use .36\n_IN('2.5.29.35', 'authorityKeyIdentifier');\n_I_('2.5.29.36', 'policyConstraints');\n_IN('2.5.29.37', 'extKeyUsage');\n_I_('2.5.29.46', 'freshestCRL');\n_I_('2.5.29.54', 'inhibitAnyPolicy');\n\n// extKeyUsage purposes\n_IN('1.3.6.1.4.1.11129.2.4.2', 'timestampList');\n_IN('1.3.6.1.5.5.7.1.1', 'authorityInfoAccess');\n_IN('1.3.6.1.5.5.7.3.1', 'serverAuth');\n_IN('1.3.6.1.5.5.7.3.2', 'clientAuth');\n_IN('1.3.6.1.5.5.7.3.3', 'codeSigning');\n_IN('1.3.6.1.5.5.7.3.4', 'emailProtection');\n_IN('1.3.6.1.5.5.7.3.8', 'timeStamping');\n","/**\n * Javascript implementation of Abstract Syntax Notation Number One.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n *\n * An API for storing data using the Abstract Syntax Notation Number One\n * format using DER (Distinguished Encoding Rules) encoding. This encoding is\n * commonly used to store data for PKI, i.e. X.509 Certificates, and this\n * implementation exists for that purpose.\n *\n * Abstract Syntax Notation Number One (ASN.1) is used to define the abstract\n * syntax of information without restricting the way the information is encoded\n * for transmission. It provides a standard that allows for open systems\n * communication. ASN.1 defines the syntax of information data and a number of\n * simple data types as well as a notation for describing them and specifying\n * values for them.\n *\n * The RSA algorithm creates public and private keys that are often stored in\n * X.509 or PKCS#X formats -- which use ASN.1 (encoded in DER format). This\n * class provides the most basic functionality required to store and load DSA\n * keys that are encoded according to ASN.1.\n *\n * The most common binary encodings for ASN.1 are BER (Basic Encoding Rules)\n * and DER (Distinguished Encoding Rules). DER is just a subset of BER that\n * has stricter requirements for how data must be encoded.\n *\n * Each ASN.1 structure has a tag (a byte identifying the ASN.1 structure type)\n * and a byte array for the value of this ASN1 structure which may be data or a\n * list of ASN.1 structures.\n *\n * Each ASN.1 structure using BER is (Tag-Length-Value):\n *\n * | byte 0 | bytes X | bytes Y |\n * |--------|---------|----------\n * | tag | length | value |\n *\n * ASN.1 allows for tags to be of \"High-tag-number form\" which allows a tag to\n * be two or more octets, but that is not supported by this class. A tag is\n * only 1 byte. Bits 1-5 give the tag number (ie the data type within a\n * particular 'class'), 6 indicates whether or not the ASN.1 value is\n * constructed from other ASN.1 values, and bits 7 and 8 give the 'class'. If\n * bits 7 and 8 are both zero, the class is UNIVERSAL. If only bit 7 is set,\n * then the class is APPLICATION. If only bit 8 is set, then the class is\n * CONTEXT_SPECIFIC. If both bits 7 and 8 are set, then the class is PRIVATE.\n * The tag numbers for the data types for the class UNIVERSAL are listed below:\n *\n * UNIVERSAL 0 Reserved for use by the encoding rules\n * UNIVERSAL 1 Boolean type\n * UNIVERSAL 2 Integer type\n * UNIVERSAL 3 Bitstring type\n * UNIVERSAL 4 Octetstring type\n * UNIVERSAL 5 Null type\n * UNIVERSAL 6 Object identifier type\n * UNIVERSAL 7 Object descriptor type\n * UNIVERSAL 8 External type and Instance-of type\n * UNIVERSAL 9 Real type\n * UNIVERSAL 10 Enumerated type\n * UNIVERSAL 11 Embedded-pdv type\n * UNIVERSAL 12 UTF8String type\n * UNIVERSAL 13 Relative object identifier type\n * UNIVERSAL 14-15 Reserved for future editions\n * UNIVERSAL 16 Sequence and Sequence-of types\n * UNIVERSAL 17 Set and Set-of types\n * UNIVERSAL 18-22, 25-30 Character string types\n * UNIVERSAL 23-24 Time types\n *\n * The length of an ASN.1 structure is specified after the tag identifier.\n * There is a definite form and an indefinite form. The indefinite form may\n * be used if the encoding is constructed and not all immediately available.\n * The indefinite form is encoded using a length byte with only the 8th bit\n * set. The end of the constructed object is marked using end-of-contents\n * octets (two zero bytes).\n *\n * The definite form looks like this:\n *\n * The length may take up 1 or more bytes, it depends on the length of the\n * value of the ASN.1 structure. DER encoding requires that if the ASN.1\n * structure has a value that has a length greater than 127, more than 1 byte\n * will be used to store its length, otherwise just one byte will be used.\n * This is strict.\n *\n * In the case that the length of the ASN.1 value is less than 127, 1 octet\n * (byte) is used to store the \"short form\" length. The 8th bit has a value of\n * 0 indicating the length is \"short form\" and not \"long form\" and bits 7-1\n * give the length of the data. (The 8th bit is the left-most, most significant\n * bit: also known as big endian or network format).\n *\n * In the case that the length of the ASN.1 value is greater than 127, 2 to\n * 127 octets (bytes) are used to store the \"long form\" length. The first\n * byte's 8th bit is set to 1 to indicate the length is \"long form.\" Bits 7-1\n * give the number of additional octets. All following octets are in base 256\n * with the most significant digit first (typical big-endian binary unsigned\n * integer storage). So, for instance, if the length of a value was 257, the\n * first byte would be set to:\n *\n * 10000010 = 130 = 0x82.\n *\n * This indicates there are 2 octets (base 256) for the length. The second and\n * third bytes (the octets just mentioned) would store the length in base 256:\n *\n * octet 2: 00000001 = 1 * 256^1 = 256\n * octet 3: 00000001 = 1 * 256^0 = 1\n * total = 257\n *\n * The algorithm for converting a js integer value of 257 to base-256 is:\n *\n * var value = 257;\n * var bytes = [];\n * bytes[0] = (value >>> 8) & 0xFF; // most significant byte first\n * bytes[1] = value & 0xFF; // least significant byte last\n *\n * On the ASN.1 UNIVERSAL Object Identifier (OID) type:\n *\n * An OID can be written like: \"value1.value2.value3...valueN\"\n *\n * The DER encoding rules:\n *\n * The first byte has the value 40 * value1 + value2.\n * The following bytes, if any, encode the remaining values. Each value is\n * encoded in base 128, most significant digit first (big endian), with as\n * few digits as possible, and the most significant bit of each byte set\n * to 1 except the last in each value's encoding. For example: Given the\n * OID \"1.2.840.113549\", its DER encoding is (remember each byte except the\n * last one in each encoding is OR'd with 0x80):\n *\n * byte 1: 40 * 1 + 2 = 42 = 0x2A.\n * bytes 2-3: 128 * 6 + 72 = 840 = 6 72 = 6 72 = 0x0648 = 0x8648\n * bytes 4-6: 16384 * 6 + 128 * 119 + 13 = 6 119 13 = 0x06770D = 0x86F70D\n *\n * The final value is: 0x2A864886F70D.\n * The full OID (including ASN.1 tag and length of 6 bytes) is:\n * 0x06062A864886F70D\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./oids');\n\n/* ASN.1 API */\nvar asn1 = module.exports = forge.asn1 = forge.asn1 || {};\n\n/**\n * ASN.1 classes.\n */\nasn1.Class = {\n UNIVERSAL: 0x00,\n APPLICATION: 0x40,\n CONTEXT_SPECIFIC: 0x80,\n PRIVATE: 0xC0\n};\n\n/**\n * ASN.1 types. Not all types are supported by this implementation, only\n * those necessary to implement a simple PKI are implemented.\n */\nasn1.Type = {\n NONE: 0,\n BOOLEAN: 1,\n INTEGER: 2,\n BITSTRING: 3,\n OCTETSTRING: 4,\n NULL: 5,\n OID: 6,\n ODESC: 7,\n EXTERNAL: 8,\n REAL: 9,\n ENUMERATED: 10,\n EMBEDDED: 11,\n UTF8: 12,\n ROID: 13,\n SEQUENCE: 16,\n SET: 17,\n PRINTABLESTRING: 19,\n IA5STRING: 22,\n UTCTIME: 23,\n GENERALIZEDTIME: 24,\n BMPSTRING: 30\n};\n\n/**\n * Creates a new asn1 object.\n *\n * @param tagClass the tag class for the object.\n * @param type the data type (tag number) for the object.\n * @param constructed true if the asn1 object is in constructed form.\n * @param value the value for the object, if it is not constructed.\n * @param [options] the options to use:\n * [bitStringContents] the plain BIT STRING content including padding\n * byte.\n *\n * @return the asn1 object.\n */\nasn1.create = function(tagClass, type, constructed, value, options) {\n /* An asn1 object has a tagClass, a type, a constructed flag, and a\n value. The value's type depends on the constructed flag. If\n constructed, it will contain a list of other asn1 objects. If not,\n it will contain the ASN.1 value as an array of bytes formatted\n according to the ASN.1 data type. */\n\n // remove undefined values\n if(forge.util.isArray(value)) {\n var tmp = [];\n for(var i = 0; i < value.length; ++i) {\n if(value[i] !== undefined) {\n tmp.push(value[i]);\n }\n }\n value = tmp;\n }\n\n var obj = {\n tagClass: tagClass,\n type: type,\n constructed: constructed,\n composed: constructed || forge.util.isArray(value),\n value: value\n };\n if(options && 'bitStringContents' in options) {\n // TODO: copy byte buffer if it's a buffer not a string\n obj.bitStringContents = options.bitStringContents;\n // TODO: add readonly flag to avoid this overhead\n // save copy to detect changes\n obj.original = asn1.copy(obj);\n }\n return obj;\n};\n\n/**\n * Copies an asn1 object.\n *\n * @param obj the asn1 object.\n * @param [options] copy options:\n * [excludeBitStringContents] true to not copy bitStringContents\n *\n * @return the a copy of the asn1 object.\n */\nasn1.copy = function(obj, options) {\n var copy;\n\n if(forge.util.isArray(obj)) {\n copy = [];\n for(var i = 0; i < obj.length; ++i) {\n copy.push(asn1.copy(obj[i], options));\n }\n return copy;\n }\n\n if(typeof obj === 'string') {\n // TODO: copy byte buffer if it's a buffer not a string\n return obj;\n }\n\n copy = {\n tagClass: obj.tagClass,\n type: obj.type,\n constructed: obj.constructed,\n composed: obj.composed,\n value: asn1.copy(obj.value, options)\n };\n if(options && !options.excludeBitStringContents) {\n // TODO: copy byte buffer if it's a buffer not a string\n copy.bitStringContents = obj.bitStringContents;\n }\n return copy;\n};\n\n/**\n * Compares asn1 objects for equality.\n *\n * Note this function does not run in constant time.\n *\n * @param obj1 the first asn1 object.\n * @param obj2 the second asn1 object.\n * @param [options] compare options:\n * [includeBitStringContents] true to compare bitStringContents\n *\n * @return true if the asn1 objects are equal.\n */\nasn1.equals = function(obj1, obj2, options) {\n if(forge.util.isArray(obj1)) {\n if(!forge.util.isArray(obj2)) {\n return false;\n }\n if(obj1.length !== obj2.length) {\n return false;\n }\n for(var i = 0; i < obj1.length; ++i) {\n if(!asn1.equals(obj1[i], obj2[i])) {\n return false;\n }\n }\n return true;\n }\n\n if(typeof obj1 !== typeof obj2) {\n return false;\n }\n\n if(typeof obj1 === 'string') {\n return obj1 === obj2;\n }\n\n var equal = obj1.tagClass === obj2.tagClass &&\n obj1.type === obj2.type &&\n obj1.constructed === obj2.constructed &&\n obj1.composed === obj2.composed &&\n asn1.equals(obj1.value, obj2.value);\n if(options && options.includeBitStringContents) {\n equal = equal && (obj1.bitStringContents === obj2.bitStringContents);\n }\n\n return equal;\n};\n\n/**\n * Gets the length of a BER-encoded ASN.1 value.\n *\n * In case the length is not specified, undefined is returned.\n *\n * @param b the BER-encoded ASN.1 byte buffer, starting with the first\n * length byte.\n *\n * @return the length of the BER-encoded ASN.1 value or undefined.\n */\nasn1.getBerValueLength = function(b) {\n // TODO: move this function and related DER/BER functions to a der.js\n // file; better abstract ASN.1 away from der/ber.\n var b2 = b.getByte();\n if(b2 === 0x80) {\n return undefined;\n }\n\n // see if the length is \"short form\" or \"long form\" (bit 8 set)\n var length;\n var longForm = b2 & 0x80;\n if(!longForm) {\n // length is just the first byte\n length = b2;\n } else {\n // the number of bytes the length is specified in bits 7 through 1\n // and each length byte is in big-endian base-256\n length = b.getInt((b2 & 0x7F) << 3);\n }\n return length;\n};\n\n/**\n * Check if the byte buffer has enough bytes. Throws an Error if not.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the bytes remaining in the current parsing state.\n * @param n the number of bytes the buffer must have.\n */\nfunction _checkBufferLength(bytes, remaining, n) {\n if(n > remaining) {\n var error = new Error('Too few bytes to parse DER.');\n error.available = bytes.length();\n error.remaining = remaining;\n error.requested = n;\n throw error;\n }\n}\n\n/**\n * Gets the length of a BER-encoded ASN.1 value.\n *\n * In case the length is not specified, undefined is returned.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the bytes remaining in the current parsing state.\n *\n * @return the length of the BER-encoded ASN.1 value or undefined.\n */\nvar _getValueLength = function(bytes, remaining) {\n // TODO: move this function and related DER/BER functions to a der.js\n // file; better abstract ASN.1 away from der/ber.\n // fromDer already checked that this byte exists\n var b2 = bytes.getByte();\n remaining--;\n if(b2 === 0x80) {\n return undefined;\n }\n\n // see if the length is \"short form\" or \"long form\" (bit 8 set)\n var length;\n var longForm = b2 & 0x80;\n if(!longForm) {\n // length is just the first byte\n length = b2;\n } else {\n // the number of bytes the length is specified in bits 7 through 1\n // and each length byte is in big-endian base-256\n var longFormBytes = b2 & 0x7F;\n _checkBufferLength(bytes, remaining, longFormBytes);\n length = bytes.getInt(longFormBytes << 3);\n }\n // FIXME: this will only happen for 32 bit getInt with high bit set\n if(length < 0) {\n throw new Error('Negative length: ' + length);\n }\n return length;\n};\n\n/**\n * Parses an asn1 object from a byte buffer in DER format.\n *\n * @param bytes the byte buffer to parse from.\n * @param [strict] true to be strict when checking value lengths, false to\n * allow truncated values (default: true).\n * @param [options] object with options or boolean strict flag\n * [strict] true to be strict when checking value lengths, false to\n * allow truncated values (default: true).\n * [parseAllBytes] true to ensure all bytes are parsed\n * (default: true)\n * [decodeBitStrings] true to attempt to decode the content of\n * BIT STRINGs (not OCTET STRINGs) using strict mode. Note that\n * without schema support to understand the data context this can\n * erroneously decode values that happen to be valid ASN.1. This\n * flag will be deprecated or removed as soon as schema support is\n * available. (default: true)\n *\n * @throws Will throw an error for various malformed input conditions.\n *\n * @return the parsed asn1 object.\n */\nasn1.fromDer = function(bytes, options) {\n if(options === undefined) {\n options = {\n strict: true,\n parseAllBytes: true,\n decodeBitStrings: true\n };\n }\n if(typeof options === 'boolean') {\n options = {\n strict: options,\n parseAllBytes: true,\n decodeBitStrings: true\n };\n }\n if(!('strict' in options)) {\n options.strict = true;\n }\n if(!('parseAllBytes' in options)) {\n options.parseAllBytes = true;\n }\n if(!('decodeBitStrings' in options)) {\n options.decodeBitStrings = true;\n }\n\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n var byteCount = bytes.length();\n var value = _fromDer(bytes, bytes.length(), 0, options);\n if(options.parseAllBytes && bytes.length() !== 0) {\n var error = new Error('Unparsed DER bytes remain after ASN.1 parsing.');\n error.byteCount = byteCount;\n error.remaining = bytes.length();\n throw error;\n }\n return value;\n};\n\n/**\n * Internal function to parse an asn1 object from a byte buffer in DER format.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the number of bytes remaining for this chunk.\n * @param depth the current parsing depth.\n * @param options object with same options as fromDer().\n *\n * @return the parsed asn1 object.\n */\nfunction _fromDer(bytes, remaining, depth, options) {\n // temporary storage for consumption calculations\n var start;\n\n // minimum length for ASN.1 DER structure is 2\n _checkBufferLength(bytes, remaining, 2);\n\n // get the first byte\n var b1 = bytes.getByte();\n // consumed one byte\n remaining--;\n\n // get the tag class\n var tagClass = (b1 & 0xC0);\n\n // get the type (bits 1-5)\n var type = b1 & 0x1F;\n\n // get the variable value length and adjust remaining bytes\n start = bytes.length();\n var length = _getValueLength(bytes, remaining);\n remaining -= start - bytes.length();\n\n // ensure there are enough bytes to get the value\n if(length !== undefined && length > remaining) {\n if(options.strict) {\n var error = new Error('Too few bytes to read ASN.1 value.');\n error.available = bytes.length();\n error.remaining = remaining;\n error.requested = length;\n throw error;\n }\n // Note: be lenient with truncated values and use remaining state bytes\n length = remaining;\n }\n\n // value storage\n var value;\n // possible BIT STRING contents storage\n var bitStringContents;\n\n // constructed flag is bit 6 (32 = 0x20) of the first byte\n var constructed = ((b1 & 0x20) === 0x20);\n if(constructed) {\n // parse child asn1 objects from the value\n value = [];\n if(length === undefined) {\n // asn1 object of indefinite length, read until end tag\n for(;;) {\n _checkBufferLength(bytes, remaining, 2);\n if(bytes.bytes(2) === String.fromCharCode(0, 0)) {\n bytes.getBytes(2);\n remaining -= 2;\n break;\n }\n start = bytes.length();\n value.push(_fromDer(bytes, remaining, depth + 1, options));\n remaining -= start - bytes.length();\n }\n } else {\n // parsing asn1 object of definite length\n while(length > 0) {\n start = bytes.length();\n value.push(_fromDer(bytes, length, depth + 1, options));\n remaining -= start - bytes.length();\n length -= start - bytes.length();\n }\n }\n }\n\n // if a BIT STRING, save the contents including padding\n if(value === undefined && tagClass === asn1.Class.UNIVERSAL &&\n type === asn1.Type.BITSTRING) {\n bitStringContents = bytes.bytes(length);\n }\n\n // determine if a non-constructed value should be decoded as a composed\n // value that contains other ASN.1 objects. BIT STRINGs (and OCTET STRINGs)\n // can be used this way.\n if(value === undefined && options.decodeBitStrings &&\n tagClass === asn1.Class.UNIVERSAL &&\n // FIXME: OCTET STRINGs not yet supported here\n // .. other parts of forge expect to decode OCTET STRINGs manually\n (type === asn1.Type.BITSTRING /*|| type === asn1.Type.OCTETSTRING*/) &&\n length > 1) {\n // save read position\n var savedRead = bytes.read;\n var savedRemaining = remaining;\n var unused = 0;\n if(type === asn1.Type.BITSTRING) {\n /* The first octet gives the number of bits by which the length of the\n bit string is less than the next multiple of eight (this is called\n the \"number of unused bits\").\n\n The second and following octets give the value of the bit string\n converted to an octet string. */\n _checkBufferLength(bytes, remaining, 1);\n unused = bytes.getByte();\n remaining--;\n }\n // if all bits are used, maybe the BIT/OCTET STRING holds ASN.1 objs\n if(unused === 0) {\n try {\n // attempt to parse child asn1 object from the value\n // (stored in array to signal composed value)\n start = bytes.length();\n var subOptions = {\n // enforce strict mode to avoid parsing ASN.1 from plain data\n strict: true,\n decodeBitStrings: true\n };\n var composed = _fromDer(bytes, remaining, depth + 1, subOptions);\n var used = start - bytes.length();\n remaining -= used;\n if(type == asn1.Type.BITSTRING) {\n used++;\n }\n\n // if the data all decoded and the class indicates UNIVERSAL or\n // CONTEXT_SPECIFIC then assume we've got an encapsulated ASN.1 object\n var tc = composed.tagClass;\n if(used === length &&\n (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) {\n value = [composed];\n }\n } catch(ex) {\n }\n }\n if(value === undefined) {\n // restore read position\n bytes.read = savedRead;\n remaining = savedRemaining;\n }\n }\n\n if(value === undefined) {\n // asn1 not constructed or composed, get raw value\n // TODO: do DER to OID conversion and vice-versa in .toDer?\n\n if(length === undefined) {\n if(options.strict) {\n throw new Error('Non-constructed ASN.1 object of indefinite length.');\n }\n // be lenient and use remaining state bytes\n length = remaining;\n }\n\n if(type === asn1.Type.BMPSTRING) {\n value = '';\n for(; length > 0; length -= 2) {\n _checkBufferLength(bytes, remaining, 2);\n value += String.fromCharCode(bytes.getInt16());\n remaining -= 2;\n }\n } else {\n value = bytes.getBytes(length);\n remaining -= length;\n }\n }\n\n // add BIT STRING contents if available\n var asn1Options = bitStringContents === undefined ? null : {\n bitStringContents: bitStringContents\n };\n\n // create and return asn1 object\n return asn1.create(tagClass, type, constructed, value, asn1Options);\n}\n\n/**\n * Converts the given asn1 object to a buffer of bytes in DER format.\n *\n * @param asn1 the asn1 object to convert to bytes.\n *\n * @return the buffer of bytes.\n */\nasn1.toDer = function(obj) {\n var bytes = forge.util.createBuffer();\n\n // build the first byte\n var b1 = obj.tagClass | obj.type;\n\n // for storing the ASN.1 value\n var value = forge.util.createBuffer();\n\n // use BIT STRING contents if available and data not changed\n var useBitStringContents = false;\n if('bitStringContents' in obj) {\n useBitStringContents = true;\n if(obj.original) {\n useBitStringContents = asn1.equals(obj, obj.original);\n }\n }\n\n if(useBitStringContents) {\n value.putBytes(obj.bitStringContents);\n } else if(obj.composed) {\n // if composed, use each child asn1 object's DER bytes as value\n // turn on 6th bit (0x20 = 32) to indicate asn1 is constructed\n // from other asn1 objects\n if(obj.constructed) {\n b1 |= 0x20;\n } else {\n // type is a bit string, add unused bits of 0x00\n value.putByte(0x00);\n }\n\n // add all of the child DER bytes together\n for(var i = 0; i < obj.value.length; ++i) {\n if(obj.value[i] !== undefined) {\n value.putBuffer(asn1.toDer(obj.value[i]));\n }\n }\n } else {\n // use asn1.value directly\n if(obj.type === asn1.Type.BMPSTRING) {\n for(var i = 0; i < obj.value.length; ++i) {\n value.putInt16(obj.value.charCodeAt(i));\n }\n } else {\n // ensure integer is minimally-encoded\n // TODO: should all leading bytes be stripped vs just one?\n // .. ex '00 00 01' => '01'?\n if(obj.type === asn1.Type.INTEGER &&\n obj.value.length > 1 &&\n // leading 0x00 for positive integer\n ((obj.value.charCodeAt(0) === 0 &&\n (obj.value.charCodeAt(1) & 0x80) === 0) ||\n // leading 0xFF for negative integer\n (obj.value.charCodeAt(0) === 0xFF &&\n (obj.value.charCodeAt(1) & 0x80) === 0x80))) {\n value.putBytes(obj.value.substr(1));\n } else {\n value.putBytes(obj.value);\n }\n }\n }\n\n // add tag byte\n bytes.putByte(b1);\n\n // use \"short form\" encoding\n if(value.length() <= 127) {\n // one byte describes the length\n // bit 8 = 0 and bits 7-1 = length\n bytes.putByte(value.length() & 0x7F);\n } else {\n // use \"long form\" encoding\n // 2 to 127 bytes describe the length\n // first byte: bit 8 = 1 and bits 7-1 = # of additional bytes\n // other bytes: length in base 256, big-endian\n var len = value.length();\n var lenBytes = '';\n do {\n lenBytes += String.fromCharCode(len & 0xFF);\n len = len >>> 8;\n } while(len > 0);\n\n // set first byte to # bytes used to store the length and turn on\n // bit 8 to indicate long-form length is used\n bytes.putByte(lenBytes.length | 0x80);\n\n // concatenate length bytes in reverse since they were generated\n // little endian and we need big endian\n for(var i = lenBytes.length - 1; i >= 0; --i) {\n bytes.putByte(lenBytes.charCodeAt(i));\n }\n }\n\n // concatenate value bytes\n bytes.putBuffer(value);\n return bytes;\n};\n\n/**\n * Converts an OID dot-separated string to a byte buffer. The byte buffer\n * contains only the DER-encoded value, not any tag or length bytes.\n *\n * @param oid the OID dot-separated string.\n *\n * @return the byte buffer.\n */\nasn1.oidToDer = function(oid) {\n // split OID into individual values\n var values = oid.split('.');\n var bytes = forge.util.createBuffer();\n\n // first byte is 40 * value1 + value2\n bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10));\n // other bytes are each value in base 128 with 8th bit set except for\n // the last byte for each value\n var last, valueBytes, value, b;\n for(var i = 2; i < values.length; ++i) {\n // produce value bytes in reverse because we don't know how many\n // bytes it will take to store the value\n last = true;\n valueBytes = [];\n value = parseInt(values[i], 10);\n do {\n b = value & 0x7F;\n value = value >>> 7;\n // if value is not last, then turn on 8th bit\n if(!last) {\n b |= 0x80;\n }\n valueBytes.push(b);\n last = false;\n } while(value > 0);\n\n // add value bytes in reverse (needs to be in big endian)\n for(var n = valueBytes.length - 1; n >= 0; --n) {\n bytes.putByte(valueBytes[n]);\n }\n }\n\n return bytes;\n};\n\n/**\n * Converts a DER-encoded byte buffer to an OID dot-separated string. The\n * byte buffer should contain only the DER-encoded value, not any tag or\n * length bytes.\n *\n * @param bytes the byte buffer.\n *\n * @return the OID dot-separated string.\n */\nasn1.derToOid = function(bytes) {\n var oid;\n\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n // first byte is 40 * value1 + value2\n var b = bytes.getByte();\n oid = Math.floor(b / 40) + '.' + (b % 40);\n\n // other bytes are each value in base 128 with 8th bit set except for\n // the last byte for each value\n var value = 0;\n while(bytes.length() > 0) {\n b = bytes.getByte();\n value = value << 7;\n // not the last byte for the value\n if(b & 0x80) {\n value += b & 0x7F;\n } else {\n // last byte\n oid += '.' + (value + b);\n value = 0;\n }\n }\n\n return oid;\n};\n\n/**\n * Converts a UTCTime value to a date.\n *\n * Note: GeneralizedTime has 4 digits for the year and is used for X.509\n * dates past 2049. Parsing that structure hasn't been implemented yet.\n *\n * @param utc the UTCTime value to convert.\n *\n * @return the date.\n */\nasn1.utcTimeToDate = function(utc) {\n /* The following formats can be used:\n\n YYMMDDhhmmZ\n YYMMDDhhmm+hh'mm'\n YYMMDDhhmm-hh'mm'\n YYMMDDhhmmssZ\n YYMMDDhhmmss+hh'mm'\n YYMMDDhhmmss-hh'mm'\n\n Where:\n\n YY is the least significant two digits of the year\n MM is the month (01 to 12)\n DD is the day (01 to 31)\n hh is the hour (00 to 23)\n mm are the minutes (00 to 59)\n ss are the seconds (00 to 59)\n Z indicates that local time is GMT, + indicates that local time is\n later than GMT, and - indicates that local time is earlier than GMT\n hh' is the absolute value of the offset from GMT in hours\n mm' is the absolute value of the offset from GMT in minutes */\n var date = new Date();\n\n // if YY >= 50 use 19xx, if YY < 50 use 20xx\n var year = parseInt(utc.substr(0, 2), 10);\n year = (year >= 50) ? 1900 + year : 2000 + year;\n var MM = parseInt(utc.substr(2, 2), 10) - 1; // use 0-11 for month\n var DD = parseInt(utc.substr(4, 2), 10);\n var hh = parseInt(utc.substr(6, 2), 10);\n var mm = parseInt(utc.substr(8, 2), 10);\n var ss = 0;\n\n // not just YYMMDDhhmmZ\n if(utc.length > 11) {\n // get character after minutes\n var c = utc.charAt(10);\n var end = 10;\n\n // see if seconds are present\n if(c !== '+' && c !== '-') {\n // get seconds\n ss = parseInt(utc.substr(10, 2), 10);\n end += 2;\n }\n }\n\n // update date\n date.setUTCFullYear(year, MM, DD);\n date.setUTCHours(hh, mm, ss, 0);\n\n if(end) {\n // get +/- after end of time\n c = utc.charAt(end);\n if(c === '+' || c === '-') {\n // get hours+minutes offset\n var hhoffset = parseInt(utc.substr(end + 1, 2), 10);\n var mmoffset = parseInt(utc.substr(end + 4, 2), 10);\n\n // calculate offset in milliseconds\n var offset = hhoffset * 60 + mmoffset;\n offset *= 60000;\n\n // apply offset\n if(c === '+') {\n date.setTime(+date - offset);\n } else {\n date.setTime(+date + offset);\n }\n }\n }\n\n return date;\n};\n\n/**\n * Converts a GeneralizedTime value to a date.\n *\n * @param gentime the GeneralizedTime value to convert.\n *\n * @return the date.\n */\nasn1.generalizedTimeToDate = function(gentime) {\n /* The following formats can be used:\n\n YYYYMMDDHHMMSS\n YYYYMMDDHHMMSS.fff\n YYYYMMDDHHMMSSZ\n YYYYMMDDHHMMSS.fffZ\n YYYYMMDDHHMMSS+hh'mm'\n YYYYMMDDHHMMSS.fff+hh'mm'\n YYYYMMDDHHMMSS-hh'mm'\n YYYYMMDDHHMMSS.fff-hh'mm'\n\n Where:\n\n YYYY is the year\n MM is the month (01 to 12)\n DD is the day (01 to 31)\n hh is the hour (00 to 23)\n mm are the minutes (00 to 59)\n ss are the seconds (00 to 59)\n .fff is the second fraction, accurate to three decimal places\n Z indicates that local time is GMT, + indicates that local time is\n later than GMT, and - indicates that local time is earlier than GMT\n hh' is the absolute value of the offset from GMT in hours\n mm' is the absolute value of the offset from GMT in minutes */\n var date = new Date();\n\n var YYYY = parseInt(gentime.substr(0, 4), 10);\n var MM = parseInt(gentime.substr(4, 2), 10) - 1; // use 0-11 for month\n var DD = parseInt(gentime.substr(6, 2), 10);\n var hh = parseInt(gentime.substr(8, 2), 10);\n var mm = parseInt(gentime.substr(10, 2), 10);\n var ss = parseInt(gentime.substr(12, 2), 10);\n var fff = 0;\n var offset = 0;\n var isUTC = false;\n\n if(gentime.charAt(gentime.length - 1) === 'Z') {\n isUTC = true;\n }\n\n var end = gentime.length - 5, c = gentime.charAt(end);\n if(c === '+' || c === '-') {\n // get hours+minutes offset\n var hhoffset = parseInt(gentime.substr(end + 1, 2), 10);\n var mmoffset = parseInt(gentime.substr(end + 4, 2), 10);\n\n // calculate offset in milliseconds\n offset = hhoffset * 60 + mmoffset;\n offset *= 60000;\n\n // apply offset\n if(c === '+') {\n offset *= -1;\n }\n\n isUTC = true;\n }\n\n // check for second fraction\n if(gentime.charAt(14) === '.') {\n fff = parseFloat(gentime.substr(14), 10) * 1000;\n }\n\n if(isUTC) {\n date.setUTCFullYear(YYYY, MM, DD);\n date.setUTCHours(hh, mm, ss, fff);\n\n // apply offset\n date.setTime(+date + offset);\n } else {\n date.setFullYear(YYYY, MM, DD);\n date.setHours(hh, mm, ss, fff);\n }\n\n return date;\n};\n\n/**\n * Converts a date to a UTCTime value.\n *\n * Note: GeneralizedTime has 4 digits for the year and is used for X.509\n * dates past 2049. Converting to a GeneralizedTime hasn't been\n * implemented yet.\n *\n * @param date the date to convert.\n *\n * @return the UTCTime value.\n */\nasn1.dateToUtcTime = function(date) {\n // TODO: validate; currently assumes proper format\n if(typeof date === 'string') {\n return date;\n }\n\n var rval = '';\n\n // create format YYMMDDhhmmssZ\n var format = [];\n format.push(('' + date.getUTCFullYear()).substr(2));\n format.push('' + (date.getUTCMonth() + 1));\n format.push('' + date.getUTCDate());\n format.push('' + date.getUTCHours());\n format.push('' + date.getUTCMinutes());\n format.push('' + date.getUTCSeconds());\n\n // ensure 2 digits are used for each format entry\n for(var i = 0; i < format.length; ++i) {\n if(format[i].length < 2) {\n rval += '0';\n }\n rval += format[i];\n }\n rval += 'Z';\n\n return rval;\n};\n\n/**\n * Converts a date to a GeneralizedTime value.\n *\n * @param date the date to convert.\n *\n * @return the GeneralizedTime value as a string.\n */\nasn1.dateToGeneralizedTime = function(date) {\n // TODO: validate; currently assumes proper format\n if(typeof date === 'string') {\n return date;\n }\n\n var rval = '';\n\n // create format YYYYMMDDHHMMSSZ\n var format = [];\n format.push('' + date.getUTCFullYear());\n format.push('' + (date.getUTCMonth() + 1));\n format.push('' + date.getUTCDate());\n format.push('' + date.getUTCHours());\n format.push('' + date.getUTCMinutes());\n format.push('' + date.getUTCSeconds());\n\n // ensure 2 digits are used for each format entry\n for(var i = 0; i < format.length; ++i) {\n if(format[i].length < 2) {\n rval += '0';\n }\n rval += format[i];\n }\n rval += 'Z';\n\n return rval;\n};\n\n/**\n * Converts a javascript integer to a DER-encoded byte buffer to be used\n * as the value for an INTEGER type.\n *\n * @param x the integer.\n *\n * @return the byte buffer.\n */\nasn1.integerToDer = function(x) {\n var rval = forge.util.createBuffer();\n if(x >= -0x80 && x < 0x80) {\n return rval.putSignedInt(x, 8);\n }\n if(x >= -0x8000 && x < 0x8000) {\n return rval.putSignedInt(x, 16);\n }\n if(x >= -0x800000 && x < 0x800000) {\n return rval.putSignedInt(x, 24);\n }\n if(x >= -0x80000000 && x < 0x80000000) {\n return rval.putSignedInt(x, 32);\n }\n var error = new Error('Integer too large; max is 32-bits.');\n error.integer = x;\n throw error;\n};\n\n/**\n * Converts a DER-encoded byte buffer to a javascript integer. This is\n * typically used to decode the value of an INTEGER type.\n *\n * @param bytes the byte buffer.\n *\n * @return the integer.\n */\nasn1.derToInteger = function(bytes) {\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n var n = bytes.length() * 8;\n if(n > 32) {\n throw new Error('Integer too large; max is 32-bits.');\n }\n return bytes.getSignedInt(n);\n};\n\n/**\n * Validates that the given ASN.1 object is at least a super set of the\n * given ASN.1 structure. Only tag classes and types are checked. An\n * optional map may also be provided to capture ASN.1 values while the\n * structure is checked.\n *\n * To capture an ASN.1 value, set an object in the validator's 'capture'\n * parameter to the key to use in the capture map. To capture the full\n * ASN.1 object, specify 'captureAsn1'. To capture BIT STRING bytes, including\n * the leading unused bits counter byte, specify 'captureBitStringContents'.\n * To capture BIT STRING bytes, without the leading unused bits counter byte,\n * specify 'captureBitStringValue'.\n *\n * Objects in the validator may set a field 'optional' to true to indicate\n * that it isn't necessary to pass validation.\n *\n * @param obj the ASN.1 object to validate.\n * @param v the ASN.1 structure validator.\n * @param capture an optional map to capture values in.\n * @param errors an optional array for storing validation errors.\n *\n * @return true on success, false on failure.\n */\nasn1.validate = function(obj, v, capture, errors) {\n var rval = false;\n\n // ensure tag class and type are the same if specified\n if((obj.tagClass === v.tagClass || typeof(v.tagClass) === 'undefined') &&\n (obj.type === v.type || typeof(v.type) === 'undefined')) {\n // ensure constructed flag is the same if specified\n if(obj.constructed === v.constructed ||\n typeof(v.constructed) === 'undefined') {\n rval = true;\n\n // handle sub values\n if(v.value && forge.util.isArray(v.value)) {\n var j = 0;\n for(var i = 0; rval && i < v.value.length; ++i) {\n rval = v.value[i].optional || false;\n if(obj.value[j]) {\n rval = asn1.validate(obj.value[j], v.value[i], capture, errors);\n if(rval) {\n ++j;\n } else if(v.value[i].optional) {\n rval = true;\n }\n }\n if(!rval && errors) {\n errors.push(\n '[' + v.name + '] ' +\n 'Tag class \"' + v.tagClass + '\", type \"' +\n v.type + '\" expected value length \"' +\n v.value.length + '\", got \"' +\n obj.value.length + '\"');\n }\n }\n }\n\n if(rval && capture) {\n if(v.capture) {\n capture[v.capture] = obj.value;\n }\n if(v.captureAsn1) {\n capture[v.captureAsn1] = obj;\n }\n if(v.captureBitStringContents && 'bitStringContents' in obj) {\n capture[v.captureBitStringContents] = obj.bitStringContents;\n }\n if(v.captureBitStringValue && 'bitStringContents' in obj) {\n var value;\n if(obj.bitStringContents.length < 2) {\n capture[v.captureBitStringValue] = '';\n } else {\n // FIXME: support unused bits with data shifting\n var unused = obj.bitStringContents.charCodeAt(0);\n if(unused !== 0) {\n throw new Error(\n 'captureBitStringValue only supported for zero unused bits');\n }\n capture[v.captureBitStringValue] = obj.bitStringContents.slice(1);\n }\n }\n }\n } else if(errors) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected constructed \"' + v.constructed + '\", got \"' +\n obj.constructed + '\"');\n }\n } else if(errors) {\n if(obj.tagClass !== v.tagClass) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected tag class \"' + v.tagClass + '\", got \"' +\n obj.tagClass + '\"');\n }\n if(obj.type !== v.type) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected type \"' + v.type + '\", got \"' + obj.type + '\"');\n }\n }\n return rval;\n};\n\n// regex for testing for non-latin characters\nvar _nonLatinRegex = /[^\\\\u0000-\\\\u00ff]/;\n\n/**\n * Pretty prints an ASN.1 object to a string.\n *\n * @param obj the object to write out.\n * @param level the level in the tree.\n * @param indentation the indentation to use.\n *\n * @return the string.\n */\nasn1.prettyPrint = function(obj, level, indentation) {\n var rval = '';\n\n // set default level and indentation\n level = level || 0;\n indentation = indentation || 2;\n\n // start new line for deep levels\n if(level > 0) {\n rval += '\\n';\n }\n\n // create indent\n var indent = '';\n for(var i = 0; i < level * indentation; ++i) {\n indent += ' ';\n }\n\n // print class:type\n rval += indent + 'Tag: ';\n switch(obj.tagClass) {\n case asn1.Class.UNIVERSAL:\n rval += 'Universal:';\n break;\n case asn1.Class.APPLICATION:\n rval += 'Application:';\n break;\n case asn1.Class.CONTEXT_SPECIFIC:\n rval += 'Context-Specific:';\n break;\n case asn1.Class.PRIVATE:\n rval += 'Private:';\n break;\n }\n\n if(obj.tagClass === asn1.Class.UNIVERSAL) {\n rval += obj.type;\n\n // known types\n switch(obj.type) {\n case asn1.Type.NONE:\n rval += ' (None)';\n break;\n case asn1.Type.BOOLEAN:\n rval += ' (Boolean)';\n break;\n case asn1.Type.INTEGER:\n rval += ' (Integer)';\n break;\n case asn1.Type.BITSTRING:\n rval += ' (Bit string)';\n break;\n case asn1.Type.OCTETSTRING:\n rval += ' (Octet string)';\n break;\n case asn1.Type.NULL:\n rval += ' (Null)';\n break;\n case asn1.Type.OID:\n rval += ' (Object Identifier)';\n break;\n case asn1.Type.ODESC:\n rval += ' (Object Descriptor)';\n break;\n case asn1.Type.EXTERNAL:\n rval += ' (External or Instance of)';\n break;\n case asn1.Type.REAL:\n rval += ' (Real)';\n break;\n case asn1.Type.ENUMERATED:\n rval += ' (Enumerated)';\n break;\n case asn1.Type.EMBEDDED:\n rval += ' (Embedded PDV)';\n break;\n case asn1.Type.UTF8:\n rval += ' (UTF8)';\n break;\n case asn1.Type.ROID:\n rval += ' (Relative Object Identifier)';\n break;\n case asn1.Type.SEQUENCE:\n rval += ' (Sequence)';\n break;\n case asn1.Type.SET:\n rval += ' (Set)';\n break;\n case asn1.Type.PRINTABLESTRING:\n rval += ' (Printable String)';\n break;\n case asn1.Type.IA5String:\n rval += ' (IA5String (ASCII))';\n break;\n case asn1.Type.UTCTIME:\n rval += ' (UTC time)';\n break;\n case asn1.Type.GENERALIZEDTIME:\n rval += ' (Generalized time)';\n break;\n case asn1.Type.BMPSTRING:\n rval += ' (BMP String)';\n break;\n }\n } else {\n rval += obj.type;\n }\n\n rval += '\\n';\n rval += indent + 'Constructed: ' + obj.constructed + '\\n';\n\n if(obj.composed) {\n var subvalues = 0;\n var sub = '';\n for(var i = 0; i < obj.value.length; ++i) {\n if(obj.value[i] !== undefined) {\n subvalues += 1;\n sub += asn1.prettyPrint(obj.value[i], level + 1, indentation);\n if((i + 1) < obj.value.length) {\n sub += ',';\n }\n }\n }\n rval += indent + 'Sub values: ' + subvalues + sub;\n } else {\n rval += indent + 'Value: ';\n if(obj.type === asn1.Type.OID) {\n var oid = asn1.derToOid(obj.value);\n rval += oid;\n if(forge.pki && forge.pki.oids) {\n if(oid in forge.pki.oids) {\n rval += ' (' + forge.pki.oids[oid] + ') ';\n }\n }\n }\n if(obj.type === asn1.Type.INTEGER) {\n try {\n rval += asn1.derToInteger(obj.value);\n } catch(ex) {\n rval += '0x' + forge.util.bytesToHex(obj.value);\n }\n } else if(obj.type === asn1.Type.BITSTRING) {\n // TODO: shift bits as needed to display without padding\n if(obj.value.length > 1) {\n // remove unused bits field\n rval += '0x' + forge.util.bytesToHex(obj.value.slice(1));\n } else {\n rval += '(none)';\n }\n // show unused bit count\n if(obj.value.length > 0) {\n var unused = obj.value.charCodeAt(0);\n if(unused == 1) {\n rval += ' (1 unused bit shown)';\n } else if(unused > 1) {\n rval += ' (' + unused + ' unused bits shown)';\n }\n }\n } else if(obj.type === asn1.Type.OCTETSTRING) {\n if(!_nonLatinRegex.test(obj.value)) {\n rval += '(' + obj.value + ') ';\n }\n rval += '0x' + forge.util.bytesToHex(obj.value);\n } else if(obj.type === asn1.Type.UTF8) {\n try {\n rval += forge.util.decodeUtf8(obj.value);\n } catch(e) {\n if(e.message === 'URI malformed') {\n rval +=\n '0x' + forge.util.bytesToHex(obj.value) + ' (malformed UTF8)';\n } else {\n throw e;\n }\n }\n } else if(obj.type === asn1.Type.PRINTABLESTRING ||\n obj.type === asn1.Type.IA5String) {\n rval += obj.value;\n } else if(_nonLatinRegex.test(obj.value)) {\n rval += '0x' + forge.util.bytesToHex(obj.value);\n } else if(obj.value.length === 0) {\n rval += '[null]';\n } else {\n rval += obj.value;\n }\n }\n\n return rval;\n};\n","/**\n * Node.js module for Forge message digests.\n *\n * @author Dave Longley\n *\n * Copyright 2011-2017 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\n\nmodule.exports = forge.md = forge.md || {};\nforge.md.algorithms = forge.md.algorithms || {};\n","/**\n * Hash-based Message Authentication Code implementation. Requires a message\n * digest object that can be obtained, for example, from forge.md.sha1 or\n * forge.md.md5.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2012 Digital Bazaar, Inc. All rights reserved.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\n/* HMAC API */\nvar hmac = module.exports = forge.hmac = forge.hmac || {};\n\n/**\n * Creates an HMAC object that uses the given message digest object.\n *\n * @return an HMAC object.\n */\nhmac.create = function() {\n // the hmac key to use\n var _key = null;\n\n // the message digest to use\n var _md = null;\n\n // the inner padding\n var _ipadding = null;\n\n // the outer padding\n var _opadding = null;\n\n // hmac context\n var ctx = {};\n\n /**\n * Starts or restarts the HMAC with the given key and message digest.\n *\n * @param md the message digest to use, null to reuse the previous one,\n * a string to use builtin 'sha1', 'md5', 'sha256'.\n * @param key the key to use as a string, array of bytes, byte buffer,\n * or null to reuse the previous key.\n */\n ctx.start = function(md, key) {\n if(md !== null) {\n if(typeof md === 'string') {\n // create builtin message digest\n md = md.toLowerCase();\n if(md in forge.md.algorithms) {\n _md = forge.md.algorithms[md].create();\n } else {\n throw new Error('Unknown hash algorithm \"' + md + '\"');\n }\n } else {\n // store message digest\n _md = md;\n }\n }\n\n if(key === null) {\n // reuse previous key\n key = _key;\n } else {\n if(typeof key === 'string') {\n // convert string into byte buffer\n key = forge.util.createBuffer(key);\n } else if(forge.util.isArray(key)) {\n // convert byte array into byte buffer\n var tmp = key;\n key = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n key.putByte(tmp[i]);\n }\n }\n\n // if key is longer than blocksize, hash it\n var keylen = key.length();\n if(keylen > _md.blockLength) {\n _md.start();\n _md.update(key.bytes());\n key = _md.digest();\n }\n\n // mix key into inner and outer padding\n // ipadding = [0x36 * blocksize] ^ key\n // opadding = [0x5C * blocksize] ^ key\n _ipadding = forge.util.createBuffer();\n _opadding = forge.util.createBuffer();\n keylen = key.length();\n for(var i = 0; i < keylen; ++i) {\n var tmp = key.at(i);\n _ipadding.putByte(0x36 ^ tmp);\n _opadding.putByte(0x5C ^ tmp);\n }\n\n // if key is shorter than blocksize, add additional padding\n if(keylen < _md.blockLength) {\n var tmp = _md.blockLength - keylen;\n for(var i = 0; i < tmp; ++i) {\n _ipadding.putByte(0x36);\n _opadding.putByte(0x5C);\n }\n }\n _key = key;\n _ipadding = _ipadding.bytes();\n _opadding = _opadding.bytes();\n }\n\n // digest is done like so: hash(opadding | hash(ipadding | message))\n\n // prepare to do inner hash\n // hash(ipadding | message)\n _md.start();\n _md.update(_ipadding);\n };\n\n /**\n * Updates the HMAC with the given message bytes.\n *\n * @param bytes the bytes to update with.\n */\n ctx.update = function(bytes) {\n _md.update(bytes);\n };\n\n /**\n * Produces the Message Authentication Code (MAC).\n *\n * @return a byte buffer containing the digest value.\n */\n ctx.getMac = function() {\n // digest is done like so: hash(opadding | hash(ipadding | message))\n // here we do the outer hashing\n var inner = _md.digest().bytes();\n _md.start();\n _md.update(_opadding);\n _md.update(inner);\n return _md.digest();\n };\n // alias for getMac\n ctx.digest = ctx.getMac;\n\n return ctx;\n};\n","/**\n * Message Digest Algorithm 5 with 128-bit digest (MD5) implementation.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar md5 = module.exports = forge.md5 = forge.md5 || {};\nforge.md.md5 = forge.md.algorithms.md5 = md5;\n\n/**\n * Creates an MD5 message digest object.\n *\n * @return a message digest object.\n */\nmd5.create = function() {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n // MD5 state contains four 32-bit integers\n var _state = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for word storage\n var _w = new Array(16);\n\n // message digest object\n var md = {\n algorithm: 'md5',\n blockLength: 64,\n digestLength: 16,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 8\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength64 for backwards-compatibility)\n md.fullMessageLength = md.messageLength64 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _state = {\n h0: 0x67452301,\n h1: 0xEFCDAB89,\n h2: 0x98BADCFE,\n h3: 0x10325476\n };\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = (len[1] / 0x100000000) >>> 0;\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_state, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate MD5 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 448 mod 512. In other words,\n the data to be digested must be a multiple of 512 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 8 bytes (64\n bits), that means that the last segment of the data must have 56 bytes\n (448 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 448 mod 512 because\n 512 - 128 = 448.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 448 mod 512, then 512 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in little-endian order; since length\n // is stored in bytes we multiply by 8 and add carry\n var bits, carry = 0;\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n bits = md.fullMessageLength[i] * 8 + carry;\n carry = (bits / 0x100000000) >>> 0;\n finalBlock.putInt32Le(bits >>> 0);\n }\n\n var s2 = {\n h0: _state.h0,\n h1: _state.h1,\n h2: _state.h2,\n h3: _state.h3\n };\n _update(s2, _w, finalBlock);\n var rval = forge.util.createBuffer();\n rval.putInt32Le(s2.h0);\n rval.putInt32Le(s2.h1);\n rval.putInt32Le(s2.h2);\n rval.putInt32Le(s2.h3);\n return rval;\n };\n\n return md;\n};\n\n// padding, constant tables for calculating md5\nvar _padding = null;\nvar _g = null;\nvar _r = null;\nvar _k = null;\nvar _initialized = false;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 64);\n\n // g values\n _g = [\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12,\n 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2,\n 0, 7, 14, 5, 12, 3, 10, 1, 8, 15, 6, 13, 4, 11, 2, 9];\n\n // rounds table\n _r = [\n 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,\n 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,\n 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,\n 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21];\n\n // get the result of abs(sin(i + 1)) as a 32-bit integer\n _k = new Array(64);\n for(var i = 0; i < 64; ++i) {\n _k[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 0x100000000);\n }\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates an MD5 state with the given byte buffer.\n *\n * @param s the MD5 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (64 byte) chunks\n var t, a, b, c, d, f, r, i;\n var len = bytes.length();\n while(len >= 64) {\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n\n // round 1\n for(i = 0; i < 16; ++i) {\n w[i] = bytes.getInt32Le();\n f = d ^ (b & (c ^ d));\n t = (a + f + _k[i] + w[i]);\n r = _r[i];\n a = d;\n d = c;\n c = b;\n b += (t << r) | (t >>> (32 - r));\n }\n // round 2\n for(; i < 32; ++i) {\n f = c ^ (d & (b ^ c));\n t = (a + f + _k[i] + w[_g[i]]);\n r = _r[i];\n a = d;\n d = c;\n c = b;\n b += (t << r) | (t >>> (32 - r));\n }\n // round 3\n for(; i < 48; ++i) {\n f = b ^ c ^ d;\n t = (a + f + _k[i] + w[_g[i]]);\n r = _r[i];\n a = d;\n d = c;\n c = b;\n b += (t << r) | (t >>> (32 - r));\n }\n // round 4\n for(; i < 64; ++i) {\n f = c ^ (b | ~d);\n t = (a + f + _k[i] + w[_g[i]]);\n r = _r[i];\n a = d;\n d = c;\n c = b;\n b += (t << r) | (t >>> (32 - r));\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n\n len -= 64;\n }\n}\n","/**\n * Javascript implementation of basic PEM (Privacy Enhanced Mail) algorithms.\n *\n * See: RFC 1421.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2013-2014 Digital Bazaar, Inc.\n *\n * A Forge PEM object has the following fields:\n *\n * type: identifies the type of message (eg: \"RSA PRIVATE KEY\").\n *\n * procType: identifies the type of processing performed on the message,\n * it has two subfields: version and type, eg: 4,ENCRYPTED.\n *\n * contentDomain: identifies the type of content in the message, typically\n * only uses the value: \"RFC822\".\n *\n * dekInfo: identifies the message encryption algorithm and mode and includes\n * any parameters for the algorithm, it has two subfields: algorithm and\n * parameters, eg: DES-CBC,F8143EDE5960C597.\n *\n * headers: contains all other PEM encapsulated headers -- where order is\n * significant (for pairing data like recipient ID + key info).\n *\n * body: the binary-encoded body.\n */\nvar forge = require('./forge');\nrequire('./util');\n\n// shortcut for pem API\nvar pem = module.exports = forge.pem = forge.pem || {};\n\n/**\n * Encodes (serializes) the given PEM object.\n *\n * @param msg the PEM message object to encode.\n * @param options the options to use:\n * maxline the maximum characters per line for the body, (default: 64).\n *\n * @return the PEM-formatted string.\n */\npem.encode = function(msg, options) {\n options = options || {};\n var rval = '-----BEGIN ' + msg.type + '-----\\r\\n';\n\n // encode special headers\n var header;\n if(msg.procType) {\n header = {\n name: 'Proc-Type',\n values: [String(msg.procType.version), msg.procType.type]\n };\n rval += foldHeader(header);\n }\n if(msg.contentDomain) {\n header = {name: 'Content-Domain', values: [msg.contentDomain]};\n rval += foldHeader(header);\n }\n if(msg.dekInfo) {\n header = {name: 'DEK-Info', values: [msg.dekInfo.algorithm]};\n if(msg.dekInfo.parameters) {\n header.values.push(msg.dekInfo.parameters);\n }\n rval += foldHeader(header);\n }\n\n if(msg.headers) {\n // encode all other headers\n for(var i = 0; i < msg.headers.length; ++i) {\n rval += foldHeader(msg.headers[i]);\n }\n }\n\n // terminate header\n if(msg.procType) {\n rval += '\\r\\n';\n }\n\n // add body\n rval += forge.util.encode64(msg.body, options.maxline || 64) + '\\r\\n';\n\n rval += '-----END ' + msg.type + '-----\\r\\n';\n return rval;\n};\n\n/**\n * Decodes (deserializes) all PEM messages found in the given string.\n *\n * @param str the PEM-formatted string to decode.\n *\n * @return the PEM message objects in an array.\n */\npem.decode = function(str) {\n var rval = [];\n\n // split string into PEM messages (be lenient w/EOF on BEGIN line)\n var rMessage = /\\s*-----BEGIN ([A-Z0-9- ]+)-----\\r?\\n?([\\x21-\\x7e\\s]+?(?:\\r?\\n\\r?\\n))?([:A-Za-z0-9+\\/=\\s]+?)-----END \\1-----/g;\n var rHeader = /([\\x21-\\x7e]+):\\s*([\\x21-\\x7e\\s^:]+)/;\n var rCRLF = /\\r?\\n/;\n var match;\n while(true) {\n match = rMessage.exec(str);\n if(!match) {\n break;\n }\n\n // accept \"NEW CERTIFICATE REQUEST\" as \"CERTIFICATE REQUEST\"\n // https://datatracker.ietf.org/doc/html/rfc7468#section-7\n var type = match[1];\n if(type === 'NEW CERTIFICATE REQUEST') {\n type = 'CERTIFICATE REQUEST';\n }\n\n var msg = {\n type: type,\n procType: null,\n contentDomain: null,\n dekInfo: null,\n headers: [],\n body: forge.util.decode64(match[3])\n };\n rval.push(msg);\n\n // no headers\n if(!match[2]) {\n continue;\n }\n\n // parse headers\n var lines = match[2].split(rCRLF);\n var li = 0;\n while(match && li < lines.length) {\n // get line, trim any rhs whitespace\n var line = lines[li].replace(/\\s+$/, '');\n\n // RFC2822 unfold any following folded lines\n for(var nl = li + 1; nl < lines.length; ++nl) {\n var next = lines[nl];\n if(!/\\s/.test(next[0])) {\n break;\n }\n line += next;\n li = nl;\n }\n\n // parse header\n match = line.match(rHeader);\n if(match) {\n var header = {name: match[1], values: []};\n var values = match[2].split(',');\n for(var vi = 0; vi < values.length; ++vi) {\n header.values.push(ltrim(values[vi]));\n }\n\n // Proc-Type must be the first header\n if(!msg.procType) {\n if(header.name !== 'Proc-Type') {\n throw new Error('Invalid PEM formatted message. The first ' +\n 'encapsulated header must be \"Proc-Type\".');\n } else if(header.values.length !== 2) {\n throw new Error('Invalid PEM formatted message. The \"Proc-Type\" ' +\n 'header must have two subfields.');\n }\n msg.procType = {version: values[0], type: values[1]};\n } else if(!msg.contentDomain && header.name === 'Content-Domain') {\n // special-case Content-Domain\n msg.contentDomain = values[0] || '';\n } else if(!msg.dekInfo && header.name === 'DEK-Info') {\n // special-case DEK-Info\n if(header.values.length === 0) {\n throw new Error('Invalid PEM formatted message. The \"DEK-Info\" ' +\n 'header must have at least one subfield.');\n }\n msg.dekInfo = {algorithm: values[0], parameters: values[1] || null};\n } else {\n msg.headers.push(header);\n }\n }\n\n ++li;\n }\n\n if(msg.procType === 'ENCRYPTED' && !msg.dekInfo) {\n throw new Error('Invalid PEM formatted message. The \"DEK-Info\" ' +\n 'header must be present if \"Proc-Type\" is \"ENCRYPTED\".');\n }\n }\n\n if(rval.length === 0) {\n throw new Error('Invalid PEM formatted message.');\n }\n\n return rval;\n};\n\nfunction foldHeader(header) {\n var rval = header.name + ': ';\n\n // ensure values with CRLF are folded\n var values = [];\n var insertSpace = function(match, $1) {\n return ' ' + $1;\n };\n for(var i = 0; i < header.values.length; ++i) {\n values.push(header.values[i].replace(/^(\\S+\\r\\n)/, insertSpace));\n }\n rval += values.join(',') + '\\r\\n';\n\n // do folding\n var length = 0;\n var candidate = -1;\n for(var i = 0; i < rval.length; ++i, ++length) {\n if(length > 65 && candidate !== -1) {\n var insert = rval[candidate];\n if(insert === ',') {\n ++candidate;\n rval = rval.substr(0, candidate) + '\\r\\n ' + rval.substr(candidate);\n } else {\n rval = rval.substr(0, candidate) +\n '\\r\\n' + insert + rval.substr(candidate + 1);\n }\n length = (i - candidate - 1);\n candidate = -1;\n ++i;\n } else if(rval[i] === ' ' || rval[i] === '\\t' || rval[i] === ',') {\n candidate = i;\n }\n }\n\n return rval;\n}\n\nfunction ltrim(str) {\n return str.replace(/^\\s+/, '');\n}\n","/**\n * DES (Data Encryption Standard) implementation.\n *\n * This implementation supports DES as well as 3DES-EDE in ECB and CBC mode.\n * It is based on the BSD-licensed implementation by Paul Tero:\n *\n * Paul Tero, July 2001\n * http://www.tero.co.uk/des/\n *\n * Optimised for performance with large blocks by\n * Michael Hayworth, November 2001\n * http://www.netdealing.com\n *\n * THIS SOFTWARE IS PROVIDED \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * @author Stefan Siegl\n * @author Dave Longley\n *\n * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>\n * Copyright (c) 2012-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./cipher');\nrequire('./cipherModes');\nrequire('./util');\n\n/* DES API */\nmodule.exports = forge.des = forge.des || {};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('DES-<mode>', key);\n * cipher.start({iv: iv});\n *\n * Creates an DES cipher object to encrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as binary-encoded strings of bytes or\n * byte buffers.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC' if IV is\n * given, 'ECB' if null).\n *\n * @return the cipher.\n */\nforge.des.startEncrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: false,\n mode: mode || (iv === null ? 'ECB' : 'CBC')\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('DES-<mode>', key);\n *\n * Creates an DES cipher object to encrypt data using the given symmetric key.\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.des.createEncryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: false,\n mode: mode\n });\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('DES-<mode>', key);\n * decipher.start({iv: iv});\n *\n * Creates an DES cipher object to decrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as binary-encoded strings of bytes or\n * byte buffers.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC' if IV is\n * given, 'ECB' if null).\n *\n * @return the cipher.\n */\nforge.des.startDecrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: true,\n mode: mode || (iv === null ? 'ECB' : 'CBC')\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('DES-<mode>', key);\n *\n * Creates an DES cipher object to decrypt data using the given symmetric key.\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.des.createDecryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: true,\n mode: mode\n });\n};\n\n/**\n * Creates a new DES cipher algorithm object.\n *\n * @param name the name of the algorithm.\n * @param mode the mode factory function.\n *\n * @return the DES algorithm object.\n */\nforge.des.Algorithm = function(name, mode) {\n var self = this;\n self.name = name;\n self.mode = new mode({\n blockSize: 8,\n cipher: {\n encrypt: function(inBlock, outBlock) {\n return _updateBlock(self._keys, inBlock, outBlock, false);\n },\n decrypt: function(inBlock, outBlock) {\n return _updateBlock(self._keys, inBlock, outBlock, true);\n }\n }\n });\n self._init = false;\n};\n\n/**\n * Initializes this DES algorithm by expanding its key.\n *\n * @param options the options to use.\n * key the key to use with this algorithm.\n * decrypt true if the algorithm should be initialized for decryption,\n * false for encryption.\n */\nforge.des.Algorithm.prototype.initialize = function(options) {\n if(this._init) {\n return;\n }\n\n var key = forge.util.createBuffer(options.key);\n if(this.name.indexOf('3DES') === 0) {\n if(key.length() !== 24) {\n throw new Error('Invalid Triple-DES key size: ' + key.length() * 8);\n }\n }\n\n // do key expansion to 16 or 48 subkeys (single or triple DES)\n this._keys = _createKeys(key);\n this._init = true;\n};\n\n/** Register DES algorithms **/\n\nregisterAlgorithm('DES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('DES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('DES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('DES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('DES-CTR', forge.cipher.modes.ctr);\n\nregisterAlgorithm('3DES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('3DES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('3DES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('3DES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('3DES-CTR', forge.cipher.modes.ctr);\n\nfunction registerAlgorithm(name, mode) {\n var factory = function() {\n return new forge.des.Algorithm(name, mode);\n };\n forge.cipher.registerAlgorithm(name, factory);\n}\n\n/** DES implementation **/\n\nvar spfunction1 = [0x1010400,0,0x10000,0x1010404,0x1010004,0x10404,0x4,0x10000,0x400,0x1010400,0x1010404,0x400,0x1000404,0x1010004,0x1000000,0x4,0x404,0x1000400,0x1000400,0x10400,0x10400,0x1010000,0x1010000,0x1000404,0x10004,0x1000004,0x1000004,0x10004,0,0x404,0x10404,0x1000000,0x10000,0x1010404,0x4,0x1010000,0x1010400,0x1000000,0x1000000,0x400,0x1010004,0x10000,0x10400,0x1000004,0x400,0x4,0x1000404,0x10404,0x1010404,0x10004,0x1010000,0x1000404,0x1000004,0x404,0x10404,0x1010400,0x404,0x1000400,0x1000400,0,0x10004,0x10400,0,0x1010004];\nvar spfunction2 = [-0x7fef7fe0,-0x7fff8000,0x8000,0x108020,0x100000,0x20,-0x7fefffe0,-0x7fff7fe0,-0x7fffffe0,-0x7fef7fe0,-0x7fef8000,-0x80000000,-0x7fff8000,0x100000,0x20,-0x7fefffe0,0x108000,0x100020,-0x7fff7fe0,0,-0x80000000,0x8000,0x108020,-0x7ff00000,0x100020,-0x7fffffe0,0,0x108000,0x8020,-0x7fef8000,-0x7ff00000,0x8020,0,0x108020,-0x7fefffe0,0x100000,-0x7fff7fe0,-0x7ff00000,-0x7fef8000,0x8000,-0x7ff00000,-0x7fff8000,0x20,-0x7fef7fe0,0x108020,0x20,0x8000,-0x80000000,0x8020,-0x7fef8000,0x100000,-0x7fffffe0,0x100020,-0x7fff7fe0,-0x7fffffe0,0x100020,0x108000,0,-0x7fff8000,0x8020,-0x80000000,-0x7fefffe0,-0x7fef7fe0,0x108000];\nvar spfunction3 = [0x208,0x8020200,0,0x8020008,0x8000200,0,0x20208,0x8000200,0x20008,0x8000008,0x8000008,0x20000,0x8020208,0x20008,0x8020000,0x208,0x8000000,0x8,0x8020200,0x200,0x20200,0x8020000,0x8020008,0x20208,0x8000208,0x20200,0x20000,0x8000208,0x8,0x8020208,0x200,0x8000000,0x8020200,0x8000000,0x20008,0x208,0x20000,0x8020200,0x8000200,0,0x200,0x20008,0x8020208,0x8000200,0x8000008,0x200,0,0x8020008,0x8000208,0x20000,0x8000000,0x8020208,0x8,0x20208,0x20200,0x8000008,0x8020000,0x8000208,0x208,0x8020000,0x20208,0x8,0x8020008,0x20200];\nvar spfunction4 = [0x802001,0x2081,0x2081,0x80,0x802080,0x800081,0x800001,0x2001,0,0x802000,0x802000,0x802081,0x81,0,0x800080,0x800001,0x1,0x2000,0x800000,0x802001,0x80,0x800000,0x2001,0x2080,0x800081,0x1,0x2080,0x800080,0x2000,0x802080,0x802081,0x81,0x800080,0x800001,0x802000,0x802081,0x81,0,0,0x802000,0x2080,0x800080,0x800081,0x1,0x802001,0x2081,0x2081,0x80,0x802081,0x81,0x1,0x2000,0x800001,0x2001,0x802080,0x800081,0x2001,0x2080,0x800000,0x802001,0x80,0x800000,0x2000,0x802080];\nvar spfunction5 = [0x100,0x2080100,0x2080000,0x42000100,0x80000,0x100,0x40000000,0x2080000,0x40080100,0x80000,0x2000100,0x40080100,0x42000100,0x42080000,0x80100,0x40000000,0x2000000,0x40080000,0x40080000,0,0x40000100,0x42080100,0x42080100,0x2000100,0x42080000,0x40000100,0,0x42000000,0x2080100,0x2000000,0x42000000,0x80100,0x80000,0x42000100,0x100,0x2000000,0x40000000,0x2080000,0x42000100,0x40080100,0x2000100,0x40000000,0x42080000,0x2080100,0x40080100,0x100,0x2000000,0x42080000,0x42080100,0x80100,0x42000000,0x42080100,0x2080000,0,0x40080000,0x42000000,0x80100,0x2000100,0x40000100,0x80000,0,0x40080000,0x2080100,0x40000100];\nvar spfunction6 = [0x20000010,0x20400000,0x4000,0x20404010,0x20400000,0x10,0x20404010,0x400000,0x20004000,0x404010,0x400000,0x20000010,0x400010,0x20004000,0x20000000,0x4010,0,0x400010,0x20004010,0x4000,0x404000,0x20004010,0x10,0x20400010,0x20400010,0,0x404010,0x20404000,0x4010,0x404000,0x20404000,0x20000000,0x20004000,0x10,0x20400010,0x404000,0x20404010,0x400000,0x4010,0x20000010,0x400000,0x20004000,0x20000000,0x4010,0x20000010,0x20404010,0x404000,0x20400000,0x404010,0x20404000,0,0x20400010,0x10,0x4000,0x20400000,0x404010,0x4000,0x400010,0x20004010,0,0x20404000,0x20000000,0x400010,0x20004010];\nvar spfunction7 = [0x200000,0x4200002,0x4000802,0,0x800,0x4000802,0x200802,0x4200800,0x4200802,0x200000,0,0x4000002,0x2,0x4000000,0x4200002,0x802,0x4000800,0x200802,0x200002,0x4000800,0x4000002,0x4200000,0x4200800,0x200002,0x4200000,0x800,0x802,0x4200802,0x200800,0x2,0x4000000,0x200800,0x4000000,0x200800,0x200000,0x4000802,0x4000802,0x4200002,0x4200002,0x2,0x200002,0x4000000,0x4000800,0x200000,0x4200800,0x802,0x200802,0x4200800,0x802,0x4000002,0x4200802,0x4200000,0x200800,0,0x2,0x4200802,0,0x200802,0x4200000,0x800,0x4000002,0x4000800,0x800,0x200002];\nvar spfunction8 = [0x10001040,0x1000,0x40000,0x10041040,0x10000000,0x10001040,0x40,0x10000000,0x40040,0x10040000,0x10041040,0x41000,0x10041000,0x41040,0x1000,0x40,0x10040000,0x10000040,0x10001000,0x1040,0x41000,0x40040,0x10040040,0x10041000,0x1040,0,0,0x10040040,0x10000040,0x10001000,0x41040,0x40000,0x41040,0x40000,0x10041000,0x1000,0x40,0x10040040,0x1000,0x41040,0x10001000,0x40,0x10000040,0x10040000,0x10040040,0x10000000,0x40000,0x10001040,0,0x10041040,0x40040,0x10000040,0x10040000,0x10001000,0x10001040,0,0x10041040,0x41000,0x41000,0x1040,0x1040,0x40040,0x10000000,0x10041000];\n\n/**\n * Create necessary sub keys.\n *\n * @param key the 64-bit or 192-bit key.\n *\n * @return the expanded keys.\n */\nfunction _createKeys(key) {\n var pc2bytes0 = [0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204],\n pc2bytes1 = [0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101],\n pc2bytes2 = [0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808],\n pc2bytes3 = [0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000],\n pc2bytes4 = [0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010],\n pc2bytes5 = [0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420],\n pc2bytes6 = [0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002],\n pc2bytes7 = [0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800],\n pc2bytes8 = [0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002],\n pc2bytes9 = [0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408],\n pc2bytes10 = [0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020],\n pc2bytes11 = [0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200],\n pc2bytes12 = [0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010],\n pc2bytes13 = [0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105];\n\n // how many iterations (1 for des, 3 for triple des)\n // changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys\n var iterations = key.length() > 8 ? 3 : 1;\n\n // stores the return keys\n var keys = [];\n\n // now define the left shifts which need to be done\n var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];\n\n var n = 0, tmp;\n for(var j = 0; j < iterations; j++) {\n var left = key.getInt32();\n var right = key.getInt32();\n\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n tmp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= tmp;\n right ^= (tmp << -16);\n\n tmp = ((left >>> 2) ^ right) & 0x33333333;\n right ^= tmp;\n left ^= (tmp << 2);\n\n tmp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= tmp;\n right ^= (tmp << -16);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n // right needs to be shifted and OR'd with last four bits of left\n tmp = (left << 8) | ((right >>> 20) & 0x000000f0);\n\n // left needs to be put upside down\n left = ((right << 24) | ((right << 8) & 0xff0000) |\n ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0));\n right = tmp;\n\n // now go through and perform these shifts on the left and right keys\n for(var i = 0; i < shifts.length; ++i) {\n //shift the keys either one or two bits to the left\n if(shifts[i]) {\n left = (left << 2) | (left >>> 26);\n right = (right << 2) | (right >>> 26);\n } else {\n left = (left << 1) | (left >>> 27);\n right = (right << 1) | (right >>> 27);\n }\n left &= -0xf;\n right &= -0xf;\n\n // now apply PC-2, in such a way that E is easier when encrypting or\n // decrypting this conversion will look like PC-2 except only the last 6\n // bits of each byte are used rather than 48 consecutive bits and the\n // order of lines will be according to how the S selection functions will\n // be applied: S2, S4, S6, S8, S1, S3, S5, S7\n var lefttmp = (\n pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] |\n pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf] |\n pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] |\n pc2bytes6[(left >>> 4) & 0xf]);\n var righttmp = (\n pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] |\n pc2bytes9[(right >>> 20) & 0xf] | pc2bytes10[(right >>> 16) & 0xf] |\n pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |\n pc2bytes13[(right >>> 4) & 0xf]);\n tmp = ((righttmp >>> 16) ^ lefttmp) & 0x0000ffff;\n keys[n++] = lefttmp ^ tmp;\n keys[n++] = righttmp ^ (tmp << 16);\n }\n }\n\n return keys;\n}\n\n/**\n * Updates a single block (1 byte) using DES. The update will either\n * encrypt or decrypt the block.\n *\n * @param keys the expanded keys.\n * @param input the input block (an array of 32-bit words).\n * @param output the updated output block.\n * @param decrypt true to decrypt the block, false to encrypt it.\n */\nfunction _updateBlock(keys, input, output, decrypt) {\n // set up loops for single or triple DES\n var iterations = keys.length === 32 ? 3 : 9;\n var looping;\n if(iterations === 3) {\n looping = decrypt ? [30, -2, -2] : [0, 32, 2];\n } else {\n looping = (decrypt ?\n [94, 62, -2, 32, 64, 2, 30, -2, -2] :\n [0, 32, 2, 62, 30, -2, 64, 96, 2]);\n }\n\n var tmp;\n\n var left = input[0];\n var right = input[1];\n\n // first each 64 bit chunk of the message must be permuted according to IP\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n tmp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= tmp;\n left ^= (tmp << 16);\n\n tmp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= tmp;\n right ^= (tmp << 2);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n // rotate left 1 bit\n left = ((left << 1) | (left >>> 31));\n right = ((right << 1) | (right >>> 31));\n\n for(var j = 0; j < iterations; j += 3) {\n var endloop = looping[j + 1];\n var loopinc = looping[j + 2];\n\n // now go through and perform the encryption or decryption\n for(var i = looping[j]; i != endloop; i += loopinc) {\n var right1 = right ^ keys[i];\n var right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];\n\n // passing these bytes through the S selection functions\n tmp = left;\n left = right;\n right = tmp ^ (\n spfunction2[(right1 >>> 24) & 0x3f] |\n spfunction4[(right1 >>> 16) & 0x3f] |\n spfunction6[(right1 >>> 8) & 0x3f] |\n spfunction8[right1 & 0x3f] |\n spfunction1[(right2 >>> 24) & 0x3f] |\n spfunction3[(right2 >>> 16) & 0x3f] |\n spfunction5[(right2 >>> 8) & 0x3f] |\n spfunction7[right2 & 0x3f]);\n }\n // unreverse left and right\n tmp = left;\n left = right;\n right = tmp;\n }\n\n // rotate right 1 bit\n left = ((left >>> 1) | (left << 31));\n right = ((right >>> 1) | (right << 31));\n\n // now perform IP-1, which is IP in the opposite direction\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= tmp;\n right ^= (tmp << 2);\n\n tmp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= tmp;\n left ^= (tmp << 16);\n\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n output[0] = left;\n output[1] = right;\n}\n\n/**\n * Deprecated. Instead, use:\n *\n * forge.cipher.createCipher('DES-<mode>', key);\n * forge.cipher.createDecipher('DES-<mode>', key);\n *\n * Creates a deprecated DES cipher object. This object's mode will default to\n * CBC (cipher-block-chaining).\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param options the options to use.\n * key the symmetric key to use (64 or 192 bits).\n * output the buffer to write to.\n * decrypt true for decryption, false for encryption.\n * mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nfunction _createCipher(options) {\n options = options || {};\n var mode = (options.mode || 'CBC').toUpperCase();\n var algorithm = 'DES-' + mode;\n\n var cipher;\n if(options.decrypt) {\n cipher = forge.cipher.createDecipher(algorithm, options.key);\n } else {\n cipher = forge.cipher.createCipher(algorithm, options.key);\n }\n\n // backwards compatible start API\n var start = cipher.start;\n cipher.start = function(iv, options) {\n // backwards compatibility: support second arg as output buffer\n var output = null;\n if(options instanceof forge.util.ByteBuffer) {\n output = options;\n options = {};\n }\n options = options || {};\n options.output = output;\n options.iv = iv;\n start.call(cipher, options);\n };\n\n return cipher;\n}\n","/**\n * Password-Based Key-Derivation Function #2 implementation.\n *\n * See RFC 2898 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./hmac');\nrequire('./md');\nrequire('./util');\n\nvar pkcs5 = forge.pkcs5 = forge.pkcs5 || {};\n\nvar crypto;\nif(forge.util.isNodejs && !forge.options.usePureJavaScript) {\n crypto = require('crypto');\n}\n\n/**\n * Derives a key from a password.\n *\n * @param p the password as a binary-encoded string of bytes.\n * @param s the salt as a binary-encoded string of bytes.\n * @param c the iteration count, a positive integer.\n * @param dkLen the intended length, in bytes, of the derived key,\n * (max: 2^32 - 1) * hash length of the PRF.\n * @param [md] the message digest (or algorithm identifier as a string) to use\n * in the PRF, defaults to SHA-1.\n * @param [callback(err, key)] presence triggers asynchronous version, called\n * once the operation completes.\n *\n * @return the derived key, as a binary-encoded string of bytes, for the\n * synchronous version (if no callback is specified).\n */\nmodule.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function(\n p, s, c, dkLen, md, callback) {\n if(typeof md === 'function') {\n callback = md;\n md = null;\n }\n\n // use native implementation if possible and not disabled, note that\n // some node versions only support SHA-1, others allow digest to be changed\n if(forge.util.isNodejs && !forge.options.usePureJavaScript &&\n crypto.pbkdf2 && (md === null || typeof md !== 'object') &&\n (crypto.pbkdf2Sync.length > 4 || (!md || md === 'sha1'))) {\n if(typeof md !== 'string') {\n // default prf to SHA-1\n md = 'sha1';\n }\n p = Buffer.from(p, 'binary');\n s = Buffer.from(s, 'binary');\n if(!callback) {\n if(crypto.pbkdf2Sync.length === 4) {\n return crypto.pbkdf2Sync(p, s, c, dkLen).toString('binary');\n }\n return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString('binary');\n }\n if(crypto.pbkdf2Sync.length === 4) {\n return crypto.pbkdf2(p, s, c, dkLen, function(err, key) {\n if(err) {\n return callback(err);\n }\n callback(null, key.toString('binary'));\n });\n }\n return crypto.pbkdf2(p, s, c, dkLen, md, function(err, key) {\n if(err) {\n return callback(err);\n }\n callback(null, key.toString('binary'));\n });\n }\n\n if(typeof md === 'undefined' || md === null) {\n // default prf to SHA-1\n md = 'sha1';\n }\n if(typeof md === 'string') {\n if(!(md in forge.md.algorithms)) {\n throw new Error('Unknown hash algorithm: ' + md);\n }\n md = forge.md[md].create();\n }\n\n var hLen = md.digestLength;\n\n /* 1. If dkLen > (2^32 - 1) * hLen, output \"derived key too long\" and\n stop. */\n if(dkLen > (0xFFFFFFFF * hLen)) {\n var err = new Error('Derived key is too long.');\n if(callback) {\n return callback(err);\n }\n throw err;\n }\n\n /* 2. Let len be the number of hLen-octet blocks in the derived key,\n rounding up, and let r be the number of octets in the last\n block:\n\n len = CEIL(dkLen / hLen),\n r = dkLen - (len - 1) * hLen. */\n var len = Math.ceil(dkLen / hLen);\n var r = dkLen - (len - 1) * hLen;\n\n /* 3. For each block of the derived key apply the function F defined\n below to the password P, the salt S, the iteration count c, and\n the block index to compute the block:\n\n T_1 = F(P, S, c, 1),\n T_2 = F(P, S, c, 2),\n ...\n T_len = F(P, S, c, len),\n\n where the function F is defined as the exclusive-or sum of the\n first c iterates of the underlying pseudorandom function PRF\n applied to the password P and the concatenation of the salt S\n and the block index i:\n\n F(P, S, c, i) = u_1 XOR u_2 XOR ... XOR u_c\n\n where\n\n u_1 = PRF(P, S || INT(i)),\n u_2 = PRF(P, u_1),\n ...\n u_c = PRF(P, u_{c-1}).\n\n Here, INT(i) is a four-octet encoding of the integer i, most\n significant octet first. */\n var prf = forge.hmac.create();\n prf.start(md, p);\n var dk = '';\n var xor, u_c, u_c1;\n\n // sync version\n if(!callback) {\n for(var i = 1; i <= len; ++i) {\n // PRF(P, S || INT(i)) (first iteration)\n prf.start(null, null);\n prf.update(s);\n prf.update(forge.util.int32ToBytes(i));\n xor = u_c1 = prf.digest().getBytes();\n\n // PRF(P, u_{c-1}) (other iterations)\n for(var j = 2; j <= c; ++j) {\n prf.start(null, null);\n prf.update(u_c1);\n u_c = prf.digest().getBytes();\n // F(p, s, c, i)\n xor = forge.util.xorBytes(xor, u_c, hLen);\n u_c1 = u_c;\n }\n\n /* 4. Concatenate the blocks and extract the first dkLen octets to\n produce a derived key DK:\n\n DK = T_1 || T_2 || ... || T_len<0..r-1> */\n dk += (i < len) ? xor : xor.substr(0, r);\n }\n /* 5. Output the derived key DK. */\n return dk;\n }\n\n // async version\n var i = 1, j;\n function outer() {\n if(i > len) {\n // done\n return callback(null, dk);\n }\n\n // PRF(P, S || INT(i)) (first iteration)\n prf.start(null, null);\n prf.update(s);\n prf.update(forge.util.int32ToBytes(i));\n xor = u_c1 = prf.digest().getBytes();\n\n // PRF(P, u_{c-1}) (other iterations)\n j = 2;\n inner();\n }\n\n function inner() {\n if(j <= c) {\n prf.start(null, null);\n prf.update(u_c1);\n u_c = prf.digest().getBytes();\n // F(p, s, c, i)\n xor = forge.util.xorBytes(xor, u_c, hLen);\n u_c1 = u_c;\n ++j;\n return forge.util.setImmediate(inner);\n }\n\n /* 4. Concatenate the blocks and extract the first dkLen octets to\n produce a derived key DK:\n\n DK = T_1 || T_2 || ... || T_len<0..r-1> */\n dk += (i < len) ? xor : xor.substr(0, r);\n\n ++i;\n outer();\n }\n\n outer();\n};\n","/**\n * Secure Hash Algorithm with 256-bit digest (SHA-256) implementation.\n *\n * See FIPS 180-2 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha256 = module.exports = forge.sha256 = forge.sha256 || {};\nforge.md.sha256 = forge.md.algorithms.sha256 = sha256;\n\n/**\n * Creates a SHA-256 message digest object.\n *\n * @return a message digest object.\n */\nsha256.create = function() {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n // SHA-256 state contains eight 32-bit integers\n var _state = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for word storage\n var _w = new Array(64);\n\n // message digest object\n var md = {\n algorithm: 'sha256',\n blockLength: 64,\n digestLength: 32,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 8\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength64 for backwards-compatibility)\n md.fullMessageLength = md.messageLength64 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _state = {\n h0: 0x6A09E667,\n h1: 0xBB67AE85,\n h2: 0x3C6EF372,\n h3: 0xA54FF53A,\n h4: 0x510E527F,\n h5: 0x9B05688C,\n h6: 0x1F83D9AB,\n h7: 0x5BE0CD19\n };\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_state, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-256 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 448 mod 512. In other words,\n the data to be digested must be a multiple of 512 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 8 bytes (64\n bits), that means that the last segment of the data must have 56 bytes\n (448 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 448 mod 512 because\n 512 - 128 = 448.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 448 mod 512, then 512 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var s2 = {\n h0: _state.h0,\n h1: _state.h1,\n h2: _state.h2,\n h3: _state.h3,\n h4: _state.h4,\n h5: _state.h5,\n h6: _state.h6,\n h7: _state.h7\n };\n _update(s2, _w, finalBlock);\n var rval = forge.util.createBuffer();\n rval.putInt32(s2.h0);\n rval.putInt32(s2.h1);\n rval.putInt32(s2.h2);\n rval.putInt32(s2.h3);\n rval.putInt32(s2.h4);\n rval.putInt32(s2.h5);\n rval.putInt32(s2.h6);\n rval.putInt32(s2.h7);\n return rval;\n };\n\n return md;\n};\n\n// sha-256 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n// table of constants\nvar _k = null;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 64);\n\n // create K table for SHA-256\n _k = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,\n 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,\n 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,\n 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,\n 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-256 state with the given byte buffer.\n *\n * @param s the SHA-256 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (64 byte) chunks\n var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h;\n var len = bytes.length();\n while(len >= 64) {\n // the w array will be populated with sixteen 32-bit big-endian words\n // and then extended into 64 32-bit words according to SHA-256\n for(i = 0; i < 16; ++i) {\n w[i] = bytes.getInt32();\n }\n for(; i < 64; ++i) {\n // XOR word 2 words ago rot right 17, rot right 19, shft right 10\n t1 = w[i - 2];\n t1 =\n ((t1 >>> 17) | (t1 << 15)) ^\n ((t1 >>> 19) | (t1 << 13)) ^\n (t1 >>> 10);\n // XOR word 15 words ago rot right 7, rot right 18, shft right 3\n t2 = w[i - 15];\n t2 =\n ((t2 >>> 7) | (t2 << 25)) ^\n ((t2 >>> 18) | (t2 << 14)) ^\n (t2 >>> 3);\n // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^32\n w[i] = (t1 + w[i - 7] + t2 + w[i - 16]) | 0;\n }\n\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n e = s.h4;\n f = s.h5;\n g = s.h6;\n h = s.h7;\n\n // round function\n for(i = 0; i < 64; ++i) {\n // Sum1(e)\n s1 =\n ((e >>> 6) | (e << 26)) ^\n ((e >>> 11) | (e << 21)) ^\n ((e >>> 25) | (e << 7));\n // Ch(e, f, g) (optimized the same way as SHA-1)\n ch = g ^ (e & (f ^ g));\n // Sum0(a)\n s0 =\n ((a >>> 2) | (a << 30)) ^\n ((a >>> 13) | (a << 19)) ^\n ((a >>> 22) | (a << 10));\n // Maj(a, b, c) (optimized the same way as SHA-1)\n maj = (a & b) | (c & (a ^ b));\n\n // main algorithm\n t1 = h + s1 + ch + _k[i] + w[i];\n t2 = s0 + maj;\n h = g;\n g = f;\n f = e;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n // can't truncate with `| 0`\n e = (d + t1) >>> 0;\n d = c;\n c = b;\n b = a;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n // can't truncate with `| 0`\n a = (t1 + t2) >>> 0;\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n s.h4 = (s.h4 + e) | 0;\n s.h5 = (s.h5 + f) | 0;\n s.h6 = (s.h6 + g) | 0;\n s.h7 = (s.h7 + h) | 0;\n len -= 64;\n }\n}\n","/**\n * A javascript implementation of a cryptographically-secure\n * Pseudo Random Number Generator (PRNG). The Fortuna algorithm is followed\n * here though the use of SHA-256 is not enforced; when generating an\n * a PRNG context, the hashing algorithm and block cipher used for\n * the generator are specified via a plugin.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nvar _crypto = null;\nif(forge.util.isNodejs && !forge.options.usePureJavaScript &&\n !process.versions['node-webkit']) {\n _crypto = require('crypto');\n}\n\n/* PRNG API */\nvar prng = module.exports = forge.prng = forge.prng || {};\n\n/**\n * Creates a new PRNG context.\n *\n * A PRNG plugin must be passed in that will provide:\n *\n * 1. A function that initializes the key and seed of a PRNG context. It\n * will be given a 16 byte key and a 16 byte seed. Any key expansion\n * or transformation of the seed from a byte string into an array of\n * integers (or similar) should be performed.\n * 2. The cryptographic function used by the generator. It takes a key and\n * a seed.\n * 3. A seed increment function. It takes the seed and returns seed + 1.\n * 4. An api to create a message digest.\n *\n * For an example, see random.js.\n *\n * @param plugin the PRNG plugin to use.\n */\nprng.create = function(plugin) {\n var ctx = {\n plugin: plugin,\n key: null,\n seed: null,\n time: null,\n // number of reseeds so far\n reseeds: 0,\n // amount of data generated so far\n generated: 0,\n // no initial key bytes\n keyBytes: ''\n };\n\n // create 32 entropy pools (each is a message digest)\n var md = plugin.md;\n var pools = new Array(32);\n for(var i = 0; i < 32; ++i) {\n pools[i] = md.create();\n }\n ctx.pools = pools;\n\n // entropy pools are written to cyclically, starting at index 0\n ctx.pool = 0;\n\n /**\n * Generates random bytes. The bytes may be generated synchronously or\n * asynchronously. Web workers must use the asynchronous interface or\n * else the behavior is undefined.\n *\n * @param count the number of random bytes to generate.\n * @param [callback(err, bytes)] called once the operation completes.\n *\n * @return count random bytes as a string.\n */\n ctx.generate = function(count, callback) {\n // do synchronously\n if(!callback) {\n return ctx.generateSync(count);\n }\n\n // simple generator using counter-based CBC\n var cipher = ctx.plugin.cipher;\n var increment = ctx.plugin.increment;\n var formatKey = ctx.plugin.formatKey;\n var formatSeed = ctx.plugin.formatSeed;\n var b = forge.util.createBuffer();\n\n // paranoid deviation from Fortuna:\n // reset key for every request to protect previously\n // generated random bytes should the key be discovered;\n // there is no 100ms based reseeding because of this\n // forced reseed for every `generate` call\n ctx.key = null;\n\n generate();\n\n function generate(err) {\n if(err) {\n return callback(err);\n }\n\n // sufficient bytes generated\n if(b.length() >= count) {\n return callback(null, b.getBytes(count));\n }\n\n // if amount of data generated is greater than 1 MiB, trigger reseed\n if(ctx.generated > 0xfffff) {\n ctx.key = null;\n }\n\n if(ctx.key === null) {\n // prevent stack overflow\n return forge.util.nextTick(function() {\n _reseed(generate);\n });\n }\n\n // generate the random bytes\n var bytes = cipher(ctx.key, ctx.seed);\n ctx.generated += bytes.length;\n b.putBytes(bytes);\n\n // generate bytes for a new key and seed\n ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));\n ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));\n\n forge.util.setImmediate(generate);\n }\n };\n\n /**\n * Generates random bytes synchronously.\n *\n * @param count the number of random bytes to generate.\n *\n * @return count random bytes as a string.\n */\n ctx.generateSync = function(count) {\n // simple generator using counter-based CBC\n var cipher = ctx.plugin.cipher;\n var increment = ctx.plugin.increment;\n var formatKey = ctx.plugin.formatKey;\n var formatSeed = ctx.plugin.formatSeed;\n\n // paranoid deviation from Fortuna:\n // reset key for every request to protect previously\n // generated random bytes should the key be discovered;\n // there is no 100ms based reseeding because of this\n // forced reseed for every `generateSync` call\n ctx.key = null;\n\n var b = forge.util.createBuffer();\n while(b.length() < count) {\n // if amount of data generated is greater than 1 MiB, trigger reseed\n if(ctx.generated > 0xfffff) {\n ctx.key = null;\n }\n\n if(ctx.key === null) {\n _reseedSync();\n }\n\n // generate the random bytes\n var bytes = cipher(ctx.key, ctx.seed);\n ctx.generated += bytes.length;\n b.putBytes(bytes);\n\n // generate bytes for a new key and seed\n ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));\n ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));\n }\n\n return b.getBytes(count);\n };\n\n /**\n * Private function that asynchronously reseeds a generator.\n *\n * @param callback(err) called once the operation completes.\n */\n function _reseed(callback) {\n if(ctx.pools[0].messageLength >= 32) {\n _seed();\n return callback();\n }\n // not enough seed data...\n var needed = (32 - ctx.pools[0].messageLength) << 5;\n ctx.seedFile(needed, function(err, bytes) {\n if(err) {\n return callback(err);\n }\n ctx.collect(bytes);\n _seed();\n callback();\n });\n }\n\n /**\n * Private function that synchronously reseeds a generator.\n */\n function _reseedSync() {\n if(ctx.pools[0].messageLength >= 32) {\n return _seed();\n }\n // not enough seed data...\n var needed = (32 - ctx.pools[0].messageLength) << 5;\n ctx.collect(ctx.seedFileSync(needed));\n _seed();\n }\n\n /**\n * Private function that seeds a generator once enough bytes are available.\n */\n function _seed() {\n // update reseed count\n ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1;\n\n // goal is to update `key` via:\n // key = hash(key + s)\n // where 's' is all collected entropy from selected pools, then...\n\n // create a plugin-based message digest\n var md = ctx.plugin.md.create();\n\n // consume current key bytes\n md.update(ctx.keyBytes);\n\n // digest the entropy of pools whose index k meet the\n // condition 'n mod 2^k == 0' where n is the number of reseeds\n var _2powK = 1;\n for(var k = 0; k < 32; ++k) {\n if(ctx.reseeds % _2powK === 0) {\n md.update(ctx.pools[k].digest().getBytes());\n ctx.pools[k].start();\n }\n _2powK = _2powK << 1;\n }\n\n // get digest for key bytes\n ctx.keyBytes = md.digest().getBytes();\n\n // paranoid deviation from Fortuna:\n // update `seed` via `seed = hash(key)`\n // instead of initializing to zero once and only\n // ever incrementing it\n md.start();\n md.update(ctx.keyBytes);\n var seedBytes = md.digest().getBytes();\n\n // update state\n ctx.key = ctx.plugin.formatKey(ctx.keyBytes);\n ctx.seed = ctx.plugin.formatSeed(seedBytes);\n ctx.generated = 0;\n }\n\n /**\n * The built-in default seedFile. This seedFile is used when entropy\n * is needed immediately.\n *\n * @param needed the number of bytes that are needed.\n *\n * @return the random bytes.\n */\n function defaultSeedFile(needed) {\n // use window.crypto.getRandomValues strong source of entropy if available\n var getRandomValues = null;\n var globalScope = forge.util.globalScope;\n var _crypto = globalScope.crypto || globalScope.msCrypto;\n if(_crypto && _crypto.getRandomValues) {\n getRandomValues = function(arr) {\n return _crypto.getRandomValues(arr);\n };\n }\n\n var b = forge.util.createBuffer();\n if(getRandomValues) {\n while(b.length() < needed) {\n // max byte length is 65536 before QuotaExceededError is thrown\n // http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues\n var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4);\n var entropy = new Uint32Array(Math.floor(count));\n try {\n getRandomValues(entropy);\n for(var i = 0; i < entropy.length; ++i) {\n b.putInt32(entropy[i]);\n }\n } catch(e) {\n /* only ignore QuotaExceededError */\n if(!(typeof QuotaExceededError !== 'undefined' &&\n e instanceof QuotaExceededError)) {\n throw e;\n }\n }\n }\n }\n\n // be sad and add some weak random data\n if(b.length() < needed) {\n /* Draws from Park-Miller \"minimal standard\" 31 bit PRNG,\n implemented with David G. Carta's optimization: with 32 bit math\n and without division (Public Domain). */\n var hi, lo, next;\n var seed = Math.floor(Math.random() * 0x010000);\n while(b.length() < needed) {\n lo = 16807 * (seed & 0xFFFF);\n hi = 16807 * (seed >> 16);\n lo += (hi & 0x7FFF) << 16;\n lo += hi >> 15;\n lo = (lo & 0x7FFFFFFF) + (lo >> 31);\n seed = lo & 0xFFFFFFFF;\n\n // consume lower 3 bytes of seed\n for(var i = 0; i < 3; ++i) {\n // throw in more pseudo random\n next = seed >>> (i << 3);\n next ^= Math.floor(Math.random() * 0x0100);\n b.putByte(next & 0xFF);\n }\n }\n }\n\n return b.getBytes(needed);\n }\n // initialize seed file APIs\n if(_crypto) {\n // use nodejs async API\n ctx.seedFile = function(needed, callback) {\n _crypto.randomBytes(needed, function(err, bytes) {\n if(err) {\n return callback(err);\n }\n callback(null, bytes.toString());\n });\n };\n // use nodejs sync API\n ctx.seedFileSync = function(needed) {\n return _crypto.randomBytes(needed).toString();\n };\n } else {\n ctx.seedFile = function(needed, callback) {\n try {\n callback(null, defaultSeedFile(needed));\n } catch(e) {\n callback(e);\n }\n };\n ctx.seedFileSync = defaultSeedFile;\n }\n\n /**\n * Adds entropy to a prng ctx's accumulator.\n *\n * @param bytes the bytes of entropy as a string.\n */\n ctx.collect = function(bytes) {\n // iterate over pools distributing entropy cyclically\n var count = bytes.length;\n for(var i = 0; i < count; ++i) {\n ctx.pools[ctx.pool].update(bytes.substr(i, 1));\n ctx.pool = (ctx.pool === 31) ? 0 : ctx.pool + 1;\n }\n };\n\n /**\n * Collects an integer of n bits.\n *\n * @param i the integer entropy.\n * @param n the number of bits in the integer.\n */\n ctx.collectInt = function(i, n) {\n var bytes = '';\n for(var x = 0; x < n; x += 8) {\n bytes += String.fromCharCode((i >> x) & 0xFF);\n }\n ctx.collect(bytes);\n };\n\n /**\n * Registers a Web Worker to receive immediate entropy from the main thread.\n * This method is required until Web Workers can access the native crypto\n * API. This method should be called twice for each created worker, once in\n * the main thread, and once in the worker itself.\n *\n * @param worker the worker to register.\n */\n ctx.registerWorker = function(worker) {\n // worker receives random bytes\n if(worker === self) {\n ctx.seedFile = function(needed, callback) {\n function listener(e) {\n var data = e.data;\n if(data.forge && data.forge.prng) {\n self.removeEventListener('message', listener);\n callback(data.forge.prng.err, data.forge.prng.bytes);\n }\n }\n self.addEventListener('message', listener);\n self.postMessage({forge: {prng: {needed: needed}}});\n };\n } else {\n // main thread sends random bytes upon request\n var listener = function(e) {\n var data = e.data;\n if(data.forge && data.forge.prng) {\n ctx.seedFile(data.forge.prng.needed, function(err, bytes) {\n worker.postMessage({forge: {prng: {err: err, bytes: bytes}}});\n });\n }\n };\n // TODO: do we need to remove the event listener when the worker dies?\n worker.addEventListener('message', listener);\n }\n };\n\n return ctx;\n};\n","/**\n * An API for getting cryptographically-secure random bytes. The bytes are\n * generated using the Fortuna algorithm devised by Bruce Schneier and\n * Niels Ferguson.\n *\n * Getting strong random bytes is not yet easy to do in javascript. The only\n * truish random entropy that can be collected is from the mouse, keyboard, or\n * from timing with respect to page loads, etc. This generator makes a poor\n * attempt at providing random bytes when those sources haven't yet provided\n * enough entropy to initially seed or to reseed the PRNG.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2009-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./sha256');\nrequire('./prng');\nrequire('./util');\n\n(function() {\n\n// forge.random already defined\nif(forge.random && forge.random.getBytes) {\n module.exports = forge.random;\n return;\n}\n\n(function(jQuery) {\n\n// the default prng plugin, uses AES-128\nvar prng_aes = {};\nvar _prng_aes_output = new Array(4);\nvar _prng_aes_buffer = forge.util.createBuffer();\nprng_aes.formatKey = function(key) {\n // convert the key into 32-bit integers\n var tmp = forge.util.createBuffer(key);\n key = new Array(4);\n key[0] = tmp.getInt32();\n key[1] = tmp.getInt32();\n key[2] = tmp.getInt32();\n key[3] = tmp.getInt32();\n\n // return the expanded key\n return forge.aes._expandKey(key, false);\n};\nprng_aes.formatSeed = function(seed) {\n // convert seed into 32-bit integers\n var tmp = forge.util.createBuffer(seed);\n seed = new Array(4);\n seed[0] = tmp.getInt32();\n seed[1] = tmp.getInt32();\n seed[2] = tmp.getInt32();\n seed[3] = tmp.getInt32();\n return seed;\n};\nprng_aes.cipher = function(key, seed) {\n forge.aes._updateBlock(key, seed, _prng_aes_output, false);\n _prng_aes_buffer.putInt32(_prng_aes_output[0]);\n _prng_aes_buffer.putInt32(_prng_aes_output[1]);\n _prng_aes_buffer.putInt32(_prng_aes_output[2]);\n _prng_aes_buffer.putInt32(_prng_aes_output[3]);\n return _prng_aes_buffer.getBytes();\n};\nprng_aes.increment = function(seed) {\n // FIXME: do we care about carry or signed issues?\n ++seed[3];\n return seed;\n};\nprng_aes.md = forge.md.sha256;\n\n/**\n * Creates a new PRNG.\n */\nfunction spawnPrng() {\n var ctx = forge.prng.create(prng_aes);\n\n /**\n * Gets random bytes. If a native secure crypto API is unavailable, this\n * method tries to make the bytes more unpredictable by drawing from data that\n * can be collected from the user of the browser, eg: mouse movement.\n *\n * If a callback is given, this method will be called asynchronously.\n *\n * @param count the number of random bytes to get.\n * @param [callback(err, bytes)] called once the operation completes.\n *\n * @return the random bytes in a string.\n */\n ctx.getBytes = function(count, callback) {\n return ctx.generate(count, callback);\n };\n\n /**\n * Gets random bytes asynchronously. If a native secure crypto API is\n * unavailable, this method tries to make the bytes more unpredictable by\n * drawing from data that can be collected from the user of the browser,\n * eg: mouse movement.\n *\n * @param count the number of random bytes to get.\n *\n * @return the random bytes in a string.\n */\n ctx.getBytesSync = function(count) {\n return ctx.generate(count);\n };\n\n return ctx;\n}\n\n// create default prng context\nvar _ctx = spawnPrng();\n\n// add other sources of entropy only if window.crypto.getRandomValues is not\n// available -- otherwise this source will be automatically used by the prng\nvar getRandomValues = null;\nvar globalScope = forge.util.globalScope;\nvar _crypto = globalScope.crypto || globalScope.msCrypto;\nif(_crypto && _crypto.getRandomValues) {\n getRandomValues = function(arr) {\n return _crypto.getRandomValues(arr);\n };\n}\n\nif(forge.options.usePureJavaScript ||\n (!forge.util.isNodejs && !getRandomValues)) {\n // if this is a web worker, do not use weak entropy, instead register to\n // receive strong entropy asynchronously from the main thread\n if(typeof window === 'undefined' || window.document === undefined) {\n // FIXME:\n }\n\n // get load time entropy\n _ctx.collectInt(+new Date(), 32);\n\n // add some entropy from navigator object\n if(typeof(navigator) !== 'undefined') {\n var _navBytes = '';\n for(var key in navigator) {\n try {\n if(typeof(navigator[key]) == 'string') {\n _navBytes += navigator[key];\n }\n } catch(e) {\n /* Some navigator keys might not be accessible, e.g. the geolocation\n attribute throws an exception if touched in Mozilla chrome://\n context.\n\n Silently ignore this and just don't use this as a source of\n entropy. */\n }\n }\n _ctx.collect(_navBytes);\n _navBytes = null;\n }\n\n // add mouse and keyboard collectors if jquery is available\n if(jQuery) {\n // set up mouse entropy capture\n jQuery().mousemove(function(e) {\n // add mouse coords\n _ctx.collectInt(e.clientX, 16);\n _ctx.collectInt(e.clientY, 16);\n });\n\n // set up keyboard entropy capture\n jQuery().keypress(function(e) {\n _ctx.collectInt(e.charCode, 8);\n });\n }\n}\n\n/* Random API */\nif(!forge.random) {\n forge.random = _ctx;\n} else {\n // extend forge.random with _ctx\n for(var key in _ctx) {\n forge.random[key] = _ctx[key];\n }\n}\n\n// expose spawn PRNG\nforge.random.createInstance = spawnPrng;\n\nmodule.exports = forge.random;\n\n})(typeof(jQuery) !== 'undefined' ? jQuery : null);\n\n})();\n","/**\n * RC2 implementation.\n *\n * @author Stefan Siegl\n *\n * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>\n *\n * Information on the RC2 cipher is available from RFC #2268,\n * http://www.ietf.org/rfc/rfc2268.txt\n */\nvar forge = require('./forge');\nrequire('./util');\n\nvar piTable = [\n 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 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 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9,\n 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9,\n 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e,\n 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad\n];\n\nvar s = [1, 2, 3, 5];\n\n/**\n * Rotate a word left by given number of bits.\n *\n * Bits that are shifted out on the left are put back in on the right\n * hand side.\n *\n * @param word The word to shift left.\n * @param bits The number of bits to shift by.\n * @return The rotated word.\n */\nvar rol = function(word, bits) {\n return ((word << bits) & 0xffff) | ((word & 0xffff) >> (16 - bits));\n};\n\n/**\n * Rotate a word right by given number of bits.\n *\n * Bits that are shifted out on the right are put back in on the left\n * hand side.\n *\n * @param word The word to shift right.\n * @param bits The number of bits to shift by.\n * @return The rotated word.\n */\nvar ror = function(word, bits) {\n return ((word & 0xffff) >> bits) | ((word << (16 - bits)) & 0xffff);\n};\n\n/* RC2 API */\nmodule.exports = forge.rc2 = forge.rc2 || {};\n\n/**\n * Perform RC2 key expansion as per RFC #2268, section 2.\n *\n * @param key variable-length user key (between 1 and 128 bytes)\n * @param effKeyBits number of effective key bits (default: 128)\n * @return the expanded RC2 key (ByteBuffer of 128 bytes)\n */\nforge.rc2.expandKey = function(key, effKeyBits) {\n if(typeof key === 'string') {\n key = forge.util.createBuffer(key);\n }\n effKeyBits = effKeyBits || 128;\n\n /* introduce variables that match the names used in RFC #2268 */\n var L = key;\n var T = key.length();\n var T1 = effKeyBits;\n var T8 = Math.ceil(T1 / 8);\n var TM = 0xff >> (T1 & 0x07);\n var i;\n\n for(i = T; i < 128; i++) {\n L.putByte(piTable[(L.at(i - 1) + L.at(i - T)) & 0xff]);\n }\n\n L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]);\n\n for(i = 127 - T8; i >= 0; i--) {\n L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]);\n }\n\n return L;\n};\n\n/**\n * Creates a RC2 cipher object.\n *\n * @param key the symmetric key to use (as base for key generation).\n * @param bits the number of effective key bits.\n * @param encrypt false for decryption, true for encryption.\n *\n * @return the cipher.\n */\nvar createCipher = function(key, bits, encrypt) {\n var _finish = false, _input = null, _output = null, _iv = null;\n var mixRound, mashRound;\n var i, j, K = [];\n\n /* Expand key and fill into K[] Array */\n key = forge.rc2.expandKey(key, bits);\n for(i = 0; i < 64; i++) {\n K.push(key.getInt16Le());\n }\n\n if(encrypt) {\n /**\n * Perform one mixing round \"in place\".\n *\n * @param R Array of four words to perform mixing on.\n */\n mixRound = function(R) {\n for(i = 0; i < 4; i++) {\n R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +\n ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);\n R[i] = rol(R[i], s[i]);\n j++;\n }\n };\n\n /**\n * Perform one mashing round \"in place\".\n *\n * @param R Array of four words to perform mashing on.\n */\n mashRound = function(R) {\n for(i = 0; i < 4; i++) {\n R[i] += K[R[(i + 3) % 4] & 63];\n }\n };\n } else {\n /**\n * Perform one r-mixing round \"in place\".\n *\n * @param R Array of four words to perform mixing on.\n */\n mixRound = function(R) {\n for(i = 3; i >= 0; i--) {\n R[i] = ror(R[i], s[i]);\n R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +\n ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);\n j--;\n }\n };\n\n /**\n * Perform one r-mashing round \"in place\".\n *\n * @param R Array of four words to perform mashing on.\n */\n mashRound = function(R) {\n for(i = 3; i >= 0; i--) {\n R[i] -= K[R[(i + 3) % 4] & 63];\n }\n };\n }\n\n /**\n * Run the specified cipher execution plan.\n *\n * This function takes four words from the input buffer, applies the IV on\n * it (if requested) and runs the provided execution plan.\n *\n * The plan must be put together in form of a array of arrays. Where the\n * outer one is simply a list of steps to perform and the inner one needs\n * to have two elements: the first one telling how many rounds to perform,\n * the second one telling what to do (i.e. the function to call).\n *\n * @param {Array} plan The plan to execute.\n */\n var runPlan = function(plan) {\n var R = [];\n\n /* Get data from input buffer and fill the four words into R */\n for(i = 0; i < 4; i++) {\n var val = _input.getInt16Le();\n\n if(_iv !== null) {\n if(encrypt) {\n /* We're encrypting, apply the IV first. */\n val ^= _iv.getInt16Le();\n } else {\n /* We're decryption, keep cipher text for next block. */\n _iv.putInt16Le(val);\n }\n }\n\n R.push(val & 0xffff);\n }\n\n /* Reset global \"j\" variable as per spec. */\n j = encrypt ? 0 : 63;\n\n /* Run execution plan. */\n for(var ptr = 0; ptr < plan.length; ptr++) {\n for(var ctr = 0; ctr < plan[ptr][0]; ctr++) {\n plan[ptr][1](R);\n }\n }\n\n /* Write back result to output buffer. */\n for(i = 0; i < 4; i++) {\n if(_iv !== null) {\n if(encrypt) {\n /* We're encrypting in CBC-mode, feed back encrypted bytes into\n IV buffer to carry it forward to next block. */\n _iv.putInt16Le(R[i]);\n } else {\n R[i] ^= _iv.getInt16Le();\n }\n }\n\n _output.putInt16Le(R[i]);\n }\n };\n\n /* Create cipher object */\n var cipher = null;\n cipher = {\n /**\n * Starts or restarts the encryption or decryption process, whichever\n * was previously configured.\n *\n * To use the cipher in CBC mode, iv may be given either as a string\n * of bytes, or as a byte buffer. For ECB mode, give null as iv.\n *\n * @param iv the initialization vector to use, null for ECB mode.\n * @param output the output the buffer to write to, null to create one.\n */\n start: function(iv, output) {\n if(iv) {\n /* CBC mode */\n if(typeof iv === 'string') {\n iv = forge.util.createBuffer(iv);\n }\n }\n\n _finish = false;\n _input = forge.util.createBuffer();\n _output = output || new forge.util.createBuffer();\n _iv = iv;\n\n cipher.output = _output;\n },\n\n /**\n * Updates the next block.\n *\n * @param input the buffer to read from.\n */\n update: function(input) {\n if(!_finish) {\n // not finishing, so fill the input buffer with more input\n _input.putBuffer(input);\n }\n\n while(_input.length() >= 8) {\n runPlan([\n [ 5, mixRound ],\n [ 1, mashRound ],\n [ 6, mixRound ],\n [ 1, mashRound ],\n [ 5, mixRound ]\n ]);\n }\n },\n\n /**\n * Finishes encrypting or decrypting.\n *\n * @param pad a padding function to use, null for PKCS#7 padding,\n * signature(blockSize, buffer, decrypt).\n *\n * @return true if successful, false on error.\n */\n finish: function(pad) {\n var rval = true;\n\n if(encrypt) {\n if(pad) {\n rval = pad(8, _input, !encrypt);\n } else {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (_input.length() === 8) ? 8 : (8 - _input.length());\n _input.fillWithByte(padding, padding);\n }\n }\n\n if(rval) {\n // do final update\n _finish = true;\n cipher.update();\n }\n\n if(!encrypt) {\n // check for error: input data not a multiple of block size\n rval = (_input.length() === 0);\n if(rval) {\n if(pad) {\n rval = pad(8, _output, !encrypt);\n } else {\n // ensure padding byte count is valid\n var len = _output.length();\n var count = _output.at(len - 1);\n\n if(count > len) {\n rval = false;\n } else {\n // trim off padding bytes\n _output.truncate(count);\n }\n }\n }\n }\n\n return rval;\n }\n };\n\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the\n * given symmetric key. The output will be stored in the 'output' member\n * of the returned cipher.\n *\n * The key and iv may be given as a string of bytes or a byte buffer.\n * The cipher is initialized to use 128 effective key bits.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n *\n * @return the cipher.\n */\nforge.rc2.startEncrypting = function(key, iv, output) {\n var cipher = forge.rc2.createEncryptionCipher(key, 128);\n cipher.start(iv, output);\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the\n * given symmetric key.\n *\n * The key may be given as a string of bytes or a byte buffer.\n *\n * To start encrypting call start() on the cipher with an iv and optional\n * output buffer.\n *\n * @param key the symmetric key to use.\n *\n * @return the cipher.\n */\nforge.rc2.createEncryptionCipher = function(key, bits) {\n return createCipher(key, bits, true);\n};\n\n/**\n * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the\n * given symmetric key. The output will be stored in the 'output' member\n * of the returned cipher.\n *\n * The key and iv may be given as a string of bytes or a byte buffer.\n * The cipher is initialized to use 128 effective key bits.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n *\n * @return the cipher.\n */\nforge.rc2.startDecrypting = function(key, iv, output) {\n var cipher = forge.rc2.createDecryptionCipher(key, 128);\n cipher.start(iv, output);\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the\n * given symmetric key.\n *\n * The key may be given as a string of bytes or a byte buffer.\n *\n * To start decrypting call start() on the cipher with an iv and optional\n * output buffer.\n *\n * @param key the symmetric key to use.\n *\n * @return the cipher.\n */\nforge.rc2.createDecryptionCipher = function(key, bits) {\n return createCipher(key, bits, false);\n};\n","// Copyright (c) 2005 Tom Wu\n// All Rights Reserved.\n// See \"LICENSE\" for details.\n\n// Basic JavaScript BN library - subset useful for RSA encryption.\n\n/*\nLicensing (LICENSE)\n-------------------\n\nThis software is covered under the following copyright:\n*/\n/*\n * Copyright (c) 2003-2005 Tom Wu\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS-IS\" AND WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY\n * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.\n *\n * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,\n * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER\n * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF\n * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT\n * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n * In addition, the following condition applies:\n *\n * All redistributions must retain an intact copy of this copyright notice\n * and disclaimer.\n */\n/*\nAddress all questions regarding this license to:\n\n Tom Wu\n tjw@cs.Stanford.EDU\n*/\nvar forge = require('./forge');\n\nmodule.exports = forge.jsbn = forge.jsbn || {};\n\n// Bits per digit\nvar dbits;\n\n// JavaScript engine analysis\nvar canary = 0xdeadbeefcafe;\nvar j_lm = ((canary&0xffffff)==0xefcafe);\n\n// (public) Constructor\nfunction BigInteger(a,b,c) {\n this.data = [];\n if(a != null)\n if(\"number\" == typeof a) this.fromNumber(a,b,c);\n else if(b == null && \"string\" != typeof a) this.fromString(a,256);\n else this.fromString(a,b);\n}\nforge.jsbn.BigInteger = BigInteger;\n\n// return new, unset BigInteger\nfunction nbi() { return new BigInteger(null); }\n\n// am: Compute w_j += (x*this_i), propagate carries,\n// c is initial carry, returns final carry.\n// c < 3*dvalue, x < 2*dvalue, this_i < dvalue\n// We need to select the fastest one that works in this environment.\n\n// am1: use a single mult and divide to get the high bits,\n// max digit bits should be 26 because\n// max internal value = 2*dvalue^2-2*dvalue (< 2^53)\nfunction am1(i,x,w,j,c,n) {\n while(--n >= 0) {\n var v = x*this.data[i++]+w.data[j]+c;\n c = Math.floor(v/0x4000000);\n w.data[j++] = v&0x3ffffff;\n }\n return c;\n}\n// am2 avoids a big mult-and-extract completely.\n// Max digit bits should be <= 30 because we do bitwise ops\n// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)\nfunction am2(i,x,w,j,c,n) {\n var xl = x&0x7fff, xh = x>>15;\n while(--n >= 0) {\n var l = this.data[i]&0x7fff;\n var h = this.data[i++]>>15;\n var m = xh*l+h*xl;\n l = xl*l+((m&0x7fff)<<15)+w.data[j]+(c&0x3fffffff);\n c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);\n w.data[j++] = l&0x3fffffff;\n }\n return c;\n}\n// Alternately, set max digit bits to 28 since some\n// browsers slow down when dealing with 32-bit numbers.\nfunction am3(i,x,w,j,c,n) {\n var xl = x&0x3fff, xh = x>>14;\n while(--n >= 0) {\n var l = this.data[i]&0x3fff;\n var h = this.data[i++]>>14;\n var m = xh*l+h*xl;\n l = xl*l+((m&0x3fff)<<14)+w.data[j]+c;\n c = (l>>28)+(m>>14)+xh*h;\n w.data[j++] = l&0xfffffff;\n }\n return c;\n}\n\n// node.js (no browser)\nif(typeof(navigator) === 'undefined')\n{\n BigInteger.prototype.am = am3;\n dbits = 28;\n} else if(j_lm && (navigator.appName == \"Microsoft Internet Explorer\")) {\n BigInteger.prototype.am = am2;\n dbits = 30;\n} else if(j_lm && (navigator.appName != \"Netscape\")) {\n BigInteger.prototype.am = am1;\n dbits = 26;\n} else { // Mozilla/Netscape seems to prefer am3\n BigInteger.prototype.am = am3;\n dbits = 28;\n}\n\nBigInteger.prototype.DB = dbits;\nBigInteger.prototype.DM = ((1<<dbits)-1);\nBigInteger.prototype.DV = (1<<dbits);\n\nvar BI_FP = 52;\nBigInteger.prototype.FV = Math.pow(2,BI_FP);\nBigInteger.prototype.F1 = BI_FP-dbits;\nBigInteger.prototype.F2 = 2*dbits-BI_FP;\n\n// Digit conversions\nvar BI_RM = \"0123456789abcdefghijklmnopqrstuvwxyz\";\nvar BI_RC = new Array();\nvar rr,vv;\nrr = \"0\".charCodeAt(0);\nfor(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;\nrr = \"a\".charCodeAt(0);\nfor(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;\nrr = \"A\".charCodeAt(0);\nfor(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;\n\nfunction int2char(n) { return BI_RM.charAt(n); }\nfunction intAt(s,i) {\n var c = BI_RC[s.charCodeAt(i)];\n return (c==null)?-1:c;\n}\n\n// (protected) copy this to r\nfunction bnpCopyTo(r) {\n for(var i = this.t-1; i >= 0; --i) r.data[i] = this.data[i];\n r.t = this.t;\n r.s = this.s;\n}\n\n// (protected) set from integer value x, -DV <= x < DV\nfunction bnpFromInt(x) {\n this.t = 1;\n this.s = (x<0)?-1:0;\n if(x > 0) this.data[0] = x;\n else if(x < -1) this.data[0] = x+this.DV;\n else this.t = 0;\n}\n\n// return bigint initialized to value\nfunction nbv(i) { var r = nbi(); r.fromInt(i); return r; }\n\n// (protected) set from string and radix\nfunction bnpFromString(s,b) {\n var k;\n if(b == 16) k = 4;\n else if(b == 8) k = 3;\n else if(b == 256) k = 8; // byte array\n else if(b == 2) k = 1;\n else if(b == 32) k = 5;\n else if(b == 4) k = 2;\n else { this.fromRadix(s,b); return; }\n this.t = 0;\n this.s = 0;\n var i = s.length, mi = false, sh = 0;\n while(--i >= 0) {\n var x = (k==8)?s[i]&0xff:intAt(s,i);\n if(x < 0) {\n if(s.charAt(i) == \"-\") mi = true;\n continue;\n }\n mi = false;\n if(sh == 0)\n this.data[this.t++] = x;\n else if(sh+k > this.DB) {\n this.data[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh;\n this.data[this.t++] = (x>>(this.DB-sh));\n } else\n this.data[this.t-1] |= x<<sh;\n sh += k;\n if(sh >= this.DB) sh -= this.DB;\n }\n if(k == 8 && (s[0]&0x80) != 0) {\n this.s = -1;\n if(sh > 0) this.data[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh;\n }\n this.clamp();\n if(mi) BigInteger.ZERO.subTo(this,this);\n}\n\n// (protected) clamp off excess high words\nfunction bnpClamp() {\n var c = this.s&this.DM;\n while(this.t > 0 && this.data[this.t-1] == c) --this.t;\n}\n\n// (public) return string representation in given radix\nfunction bnToString(b) {\n if(this.s < 0) return \"-\"+this.negate().toString(b);\n var k;\n if(b == 16) k = 4;\n else if(b == 8) k = 3;\n else if(b == 2) k = 1;\n else if(b == 32) k = 5;\n else if(b == 4) k = 2;\n else return this.toRadix(b);\n var km = (1<<k)-1, d, m = false, r = \"\", i = this.t;\n var p = this.DB-(i*this.DB)%k;\n if(i-- > 0) {\n if(p < this.DB && (d = this.data[i]>>p) > 0) { m = true; r = int2char(d); }\n while(i >= 0) {\n if(p < k) {\n d = (this.data[i]&((1<<p)-1))<<(k-p);\n d |= this.data[--i]>>(p+=this.DB-k);\n } else {\n d = (this.data[i]>>(p-=k))&km;\n if(p <= 0) { p += this.DB; --i; }\n }\n if(d > 0) m = true;\n if(m) r += int2char(d);\n }\n }\n return m?r:\"0\";\n}\n\n// (public) -this\nfunction bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }\n\n// (public) |this|\nfunction bnAbs() { return (this.s<0)?this.negate():this; }\n\n// (public) return + if this > a, - if this < a, 0 if equal\nfunction bnCompareTo(a) {\n var r = this.s-a.s;\n if(r != 0) return r;\n var i = this.t;\n r = i-a.t;\n if(r != 0) return (this.s<0)?-r:r;\n while(--i >= 0) if((r=this.data[i]-a.data[i]) != 0) return r;\n return 0;\n}\n\n// returns bit length of the integer x\nfunction nbits(x) {\n var r = 1, t;\n if((t=x>>>16) != 0) { x = t; r += 16; }\n if((t=x>>8) != 0) { x = t; r += 8; }\n if((t=x>>4) != 0) { x = t; r += 4; }\n if((t=x>>2) != 0) { x = t; r += 2; }\n if((t=x>>1) != 0) { x = t; r += 1; }\n return r;\n}\n\n// (public) return the number of bits in \"this\"\nfunction bnBitLength() {\n if(this.t <= 0) return 0;\n return this.DB*(this.t-1)+nbits(this.data[this.t-1]^(this.s&this.DM));\n}\n\n// (protected) r = this << n*DB\nfunction bnpDLShiftTo(n,r) {\n var i;\n for(i = this.t-1; i >= 0; --i) r.data[i+n] = this.data[i];\n for(i = n-1; i >= 0; --i) r.data[i] = 0;\n r.t = this.t+n;\n r.s = this.s;\n}\n\n// (protected) r = this >> n*DB\nfunction bnpDRShiftTo(n,r) {\n for(var i = n; i < this.t; ++i) r.data[i-n] = this.data[i];\n r.t = Math.max(this.t-n,0);\n r.s = this.s;\n}\n\n// (protected) r = this << n\nfunction bnpLShiftTo(n,r) {\n var bs = n%this.DB;\n var cbs = this.DB-bs;\n var bm = (1<<cbs)-1;\n var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i;\n for(i = this.t-1; i >= 0; --i) {\n r.data[i+ds+1] = (this.data[i]>>cbs)|c;\n c = (this.data[i]&bm)<<bs;\n }\n for(i = ds-1; i >= 0; --i) r.data[i] = 0;\n r.data[ds] = c;\n r.t = this.t+ds+1;\n r.s = this.s;\n r.clamp();\n}\n\n// (protected) r = this >> n\nfunction bnpRShiftTo(n,r) {\n r.s = this.s;\n var ds = Math.floor(n/this.DB);\n if(ds >= this.t) { r.t = 0; return; }\n var bs = n%this.DB;\n var cbs = this.DB-bs;\n var bm = (1<<bs)-1;\n r.data[0] = this.data[ds]>>bs;\n for(var i = ds+1; i < this.t; ++i) {\n r.data[i-ds-1] |= (this.data[i]&bm)<<cbs;\n r.data[i-ds] = this.data[i]>>bs;\n }\n if(bs > 0) r.data[this.t-ds-1] |= (this.s&bm)<<cbs;\n r.t = this.t-ds;\n r.clamp();\n}\n\n// (protected) r = this - a\nfunction bnpSubTo(a,r) {\n var i = 0, c = 0, m = Math.min(a.t,this.t);\n while(i < m) {\n c += this.data[i]-a.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n if(a.t < this.t) {\n c -= a.s;\n while(i < this.t) {\n c += this.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += this.s;\n } else {\n c += this.s;\n while(i < a.t) {\n c -= a.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c -= a.s;\n }\n r.s = (c<0)?-1:0;\n if(c < -1) r.data[i++] = this.DV+c;\n else if(c > 0) r.data[i++] = c;\n r.t = i;\n r.clamp();\n}\n\n// (protected) r = this * a, r != this,a (HAC 14.12)\n// \"this\" should be the larger one if appropriate.\nfunction bnpMultiplyTo(a,r) {\n var x = this.abs(), y = a.abs();\n var i = x.t;\n r.t = i+y.t;\n while(--i >= 0) r.data[i] = 0;\n for(i = 0; i < y.t; ++i) r.data[i+x.t] = x.am(0,y.data[i],r,i,0,x.t);\n r.s = 0;\n r.clamp();\n if(this.s != a.s) BigInteger.ZERO.subTo(r,r);\n}\n\n// (protected) r = this^2, r != this (HAC 14.16)\nfunction bnpSquareTo(r) {\n var x = this.abs();\n var i = r.t = 2*x.t;\n while(--i >= 0) r.data[i] = 0;\n for(i = 0; i < x.t-1; ++i) {\n var c = x.am(i,x.data[i],r,2*i,0,1);\n if((r.data[i+x.t]+=x.am(i+1,2*x.data[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {\n r.data[i+x.t] -= x.DV;\n r.data[i+x.t+1] = 1;\n }\n }\n if(r.t > 0) r.data[r.t-1] += x.am(i,x.data[i],r,2*i,0,1);\n r.s = 0;\n r.clamp();\n}\n\n// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)\n// r != q, this != m. q or r may be null.\nfunction bnpDivRemTo(m,q,r) {\n var pm = m.abs();\n if(pm.t <= 0) return;\n var pt = this.abs();\n if(pt.t < pm.t) {\n if(q != null) q.fromInt(0);\n if(r != null) this.copyTo(r);\n return;\n }\n if(r == null) r = nbi();\n var y = nbi(), ts = this.s, ms = m.s;\n var nsh = this.DB-nbits(pm.data[pm.t-1]);\t// normalize modulus\n if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); }\n var ys = y.t;\n var y0 = y.data[ys-1];\n if(y0 == 0) return;\n var yt = y0*(1<<this.F1)+((ys>1)?y.data[ys-2]>>this.F2:0);\n var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2;\n var i = r.t, j = i-ys, t = (q==null)?nbi():q;\n y.dlShiftTo(j,t);\n if(r.compareTo(t) >= 0) {\n r.data[r.t++] = 1;\n r.subTo(t,r);\n }\n BigInteger.ONE.dlShiftTo(ys,t);\n t.subTo(y,y);\t// \"negative\" y so we can replace sub with am later\n while(y.t < ys) y.data[y.t++] = 0;\n while(--j >= 0) {\n // Estimate quotient digit\n var qd = (r.data[--i]==y0)?this.DM:Math.floor(r.data[i]*d1+(r.data[i-1]+e)*d2);\n if((r.data[i]+=y.am(0,qd,r,j,0,ys)) < qd) {\t// Try it out\n y.dlShiftTo(j,t);\n r.subTo(t,r);\n while(r.data[i] < --qd) r.subTo(t,r);\n }\n }\n if(q != null) {\n r.drShiftTo(ys,q);\n if(ts != ms) BigInteger.ZERO.subTo(q,q);\n }\n r.t = ys;\n r.clamp();\n if(nsh > 0) r.rShiftTo(nsh,r);\t// Denormalize remainder\n if(ts < 0) BigInteger.ZERO.subTo(r,r);\n}\n\n// (public) this mod a\nfunction bnMod(a) {\n var r = nbi();\n this.abs().divRemTo(a,null,r);\n if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);\n return r;\n}\n\n// Modular reduction using \"classic\" algorithm\nfunction Classic(m) { this.m = m; }\nfunction cConvert(x) {\n if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);\n else return x;\n}\nfunction cRevert(x) { return x; }\nfunction cReduce(x) { x.divRemTo(this.m,null,x); }\nfunction cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\nfunction cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\nClassic.prototype.convert = cConvert;\nClassic.prototype.revert = cRevert;\nClassic.prototype.reduce = cReduce;\nClassic.prototype.mulTo = cMulTo;\nClassic.prototype.sqrTo = cSqrTo;\n\n// (protected) return \"-1/this % 2^DB\"; useful for Mont. reduction\n// justification:\n// xy == 1 (mod m)\n// xy = 1+km\n// xy(2-xy) = (1+km)(1-km)\n// x[y(2-xy)] = 1-k^2m^2\n// x[y(2-xy)] == 1 (mod m^2)\n// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2\n// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.\n// JS multiply \"overflows\" differently from C/C++, so care is needed here.\nfunction bnpInvDigit() {\n if(this.t < 1) return 0;\n var x = this.data[0];\n if((x&1) == 0) return 0;\n var y = x&3;\t\t// y == 1/x mod 2^2\n y = (y*(2-(x&0xf)*y))&0xf;\t// y == 1/x mod 2^4\n y = (y*(2-(x&0xff)*y))&0xff;\t// y == 1/x mod 2^8\n y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff;\t// y == 1/x mod 2^16\n // last step - calculate inverse mod DV directly;\n // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints\n y = (y*(2-x*y%this.DV))%this.DV;\t\t// y == 1/x mod 2^dbits\n // we really want the negative inverse, and -DV < y < DV\n return (y>0)?this.DV-y:-y;\n}\n\n// Montgomery reduction\nfunction Montgomery(m) {\n this.m = m;\n this.mp = m.invDigit();\n this.mpl = this.mp&0x7fff;\n this.mph = this.mp>>15;\n this.um = (1<<(m.DB-15))-1;\n this.mt2 = 2*m.t;\n}\n\n// xR mod m\nfunction montConvert(x) {\n var r = nbi();\n x.abs().dlShiftTo(this.m.t,r);\n r.divRemTo(this.m,null,r);\n if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);\n return r;\n}\n\n// x/R mod m\nfunction montRevert(x) {\n var r = nbi();\n x.copyTo(r);\n this.reduce(r);\n return r;\n}\n\n// x = x/R mod m (HAC 14.32)\nfunction montReduce(x) {\n while(x.t <= this.mt2)\t// pad x so am has enough room later\n x.data[x.t++] = 0;\n for(var i = 0; i < this.m.t; ++i) {\n // faster way of calculating u0 = x.data[i]*mp mod DV\n var j = x.data[i]&0x7fff;\n var u0 = (j*this.mpl+(((j*this.mph+(x.data[i]>>15)*this.mpl)&this.um)<<15))&x.DM;\n // use am to combine the multiply-shift-add into one call\n j = i+this.m.t;\n x.data[j] += this.m.am(0,u0,x,i,0,this.m.t);\n // propagate carry\n while(x.data[j] >= x.DV) { x.data[j] -= x.DV; x.data[++j]++; }\n }\n x.clamp();\n x.drShiftTo(this.m.t,x);\n if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);\n}\n\n// r = \"x^2/R mod m\"; x != r\nfunction montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\n// r = \"xy/R mod m\"; x,y != r\nfunction montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\n\nMontgomery.prototype.convert = montConvert;\nMontgomery.prototype.revert = montRevert;\nMontgomery.prototype.reduce = montReduce;\nMontgomery.prototype.mulTo = montMulTo;\nMontgomery.prototype.sqrTo = montSqrTo;\n\n// (protected) true iff this is even\nfunction bnpIsEven() { return ((this.t>0)?(this.data[0]&1):this.s) == 0; }\n\n// (protected) this^e, e < 2^32, doing sqr and mul with \"r\" (HAC 14.79)\nfunction bnpExp(e,z) {\n if(e > 0xffffffff || e < 1) return BigInteger.ONE;\n var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;\n g.copyTo(r);\n while(--i >= 0) {\n z.sqrTo(r,r2);\n if((e&(1<<i)) > 0) z.mulTo(r2,g,r);\n else { var t = r; r = r2; r2 = t; }\n }\n return z.revert(r);\n}\n\n// (public) this^e % m, 0 <= e < 2^32\nfunction bnModPowInt(e,m) {\n var z;\n if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);\n return this.exp(e,z);\n}\n\n// protected\nBigInteger.prototype.copyTo = bnpCopyTo;\nBigInteger.prototype.fromInt = bnpFromInt;\nBigInteger.prototype.fromString = bnpFromString;\nBigInteger.prototype.clamp = bnpClamp;\nBigInteger.prototype.dlShiftTo = bnpDLShiftTo;\nBigInteger.prototype.drShiftTo = bnpDRShiftTo;\nBigInteger.prototype.lShiftTo = bnpLShiftTo;\nBigInteger.prototype.rShiftTo = bnpRShiftTo;\nBigInteger.prototype.subTo = bnpSubTo;\nBigInteger.prototype.multiplyTo = bnpMultiplyTo;\nBigInteger.prototype.squareTo = bnpSquareTo;\nBigInteger.prototype.divRemTo = bnpDivRemTo;\nBigInteger.prototype.invDigit = bnpInvDigit;\nBigInteger.prototype.isEven = bnpIsEven;\nBigInteger.prototype.exp = bnpExp;\n\n// public\nBigInteger.prototype.toString = bnToString;\nBigInteger.prototype.negate = bnNegate;\nBigInteger.prototype.abs = bnAbs;\nBigInteger.prototype.compareTo = bnCompareTo;\nBigInteger.prototype.bitLength = bnBitLength;\nBigInteger.prototype.mod = bnMod;\nBigInteger.prototype.modPowInt = bnModPowInt;\n\n// \"constants\"\nBigInteger.ZERO = nbv(0);\nBigInteger.ONE = nbv(1);\n\n// jsbn2 lib\n\n//Copyright (c) 2005-2009 Tom Wu\n//All Rights Reserved.\n//See \"LICENSE\" for details (See jsbn.js for LICENSE).\n\n//Extended JavaScript BN functions, required for RSA private ops.\n\n//Version 1.1: new BigInteger(\"0\", 10) returns \"proper\" zero\n\n//(public)\nfunction bnClone() { var r = nbi(); this.copyTo(r); return r; }\n\n//(public) return value as integer\nfunction bnIntValue() {\nif(this.s < 0) {\n if(this.t == 1) return this.data[0]-this.DV;\n else if(this.t == 0) return -1;\n} else if(this.t == 1) return this.data[0];\nelse if(this.t == 0) return 0;\n// assumes 16 < DB < 32\nreturn ((this.data[1]&((1<<(32-this.DB))-1))<<this.DB)|this.data[0];\n}\n\n//(public) return value as byte\nfunction bnByteValue() { return (this.t==0)?this.s:(this.data[0]<<24)>>24; }\n\n//(public) return value as short (assumes DB>=16)\nfunction bnShortValue() { return (this.t==0)?this.s:(this.data[0]<<16)>>16; }\n\n//(protected) return x s.t. r^x < DV\nfunction bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); }\n\n//(public) 0 if this == 0, 1 if this > 0\nfunction bnSigNum() {\nif(this.s < 0) return -1;\nelse if(this.t <= 0 || (this.t == 1 && this.data[0] <= 0)) return 0;\nelse return 1;\n}\n\n//(protected) convert to radix string\nfunction bnpToRadix(b) {\nif(b == null) b = 10;\nif(this.signum() == 0 || b < 2 || b > 36) return \"0\";\nvar cs = this.chunkSize(b);\nvar a = Math.pow(b,cs);\nvar d = nbv(a), y = nbi(), z = nbi(), r = \"\";\nthis.divRemTo(d,y,z);\nwhile(y.signum() > 0) {\n r = (a+z.intValue()).toString(b).substr(1) + r;\n y.divRemTo(d,y,z);\n}\nreturn z.intValue().toString(b) + r;\n}\n\n//(protected) convert from radix string\nfunction bnpFromRadix(s,b) {\nthis.fromInt(0);\nif(b == null) b = 10;\nvar cs = this.chunkSize(b);\nvar d = Math.pow(b,cs), mi = false, j = 0, w = 0;\nfor(var i = 0; i < s.length; ++i) {\n var x = intAt(s,i);\n if(x < 0) {\n if(s.charAt(i) == \"-\" && this.signum() == 0) mi = true;\n continue;\n }\n w = b*w+x;\n if(++j >= cs) {\n this.dMultiply(d);\n this.dAddOffset(w,0);\n j = 0;\n w = 0;\n }\n}\nif(j > 0) {\n this.dMultiply(Math.pow(b,j));\n this.dAddOffset(w,0);\n}\nif(mi) BigInteger.ZERO.subTo(this,this);\n}\n\n//(protected) alternate constructor\nfunction bnpFromNumber(a,b,c) {\nif(\"number\" == typeof b) {\n // new BigInteger(int,int,RNG)\n if(a < 2) this.fromInt(1);\n else {\n this.fromNumber(a,c);\n if(!this.testBit(a-1)) // force MSB set\n this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);\n if(this.isEven()) this.dAddOffset(1,0); // force odd\n while(!this.isProbablePrime(b)) {\n this.dAddOffset(2,0);\n if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this);\n }\n }\n} else {\n // new BigInteger(int,RNG)\n var x = new Array(), t = a&7;\n x.length = (a>>3)+1;\n b.nextBytes(x);\n if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0;\n this.fromString(x,256);\n}\n}\n\n//(public) convert to bigendian byte array\nfunction bnToByteArray() {\nvar i = this.t, r = new Array();\nr[0] = this.s;\nvar p = this.DB-(i*this.DB)%8, d, k = 0;\nif(i-- > 0) {\n if(p < this.DB && (d = this.data[i]>>p) != (this.s&this.DM)>>p)\n r[k++] = d|(this.s<<(this.DB-p));\n while(i >= 0) {\n if(p < 8) {\n d = (this.data[i]&((1<<p)-1))<<(8-p);\n d |= this.data[--i]>>(p+=this.DB-8);\n } else {\n d = (this.data[i]>>(p-=8))&0xff;\n if(p <= 0) { p += this.DB; --i; }\n }\n if((d&0x80) != 0) d |= -256;\n if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;\n if(k > 0 || d != this.s) r[k++] = d;\n }\n}\nreturn r;\n}\n\nfunction bnEquals(a) { return(this.compareTo(a)==0); }\nfunction bnMin(a) { return(this.compareTo(a)<0)?this:a; }\nfunction bnMax(a) { return(this.compareTo(a)>0)?this:a; }\n\n//(protected) r = this op a (bitwise)\nfunction bnpBitwiseTo(a,op,r) {\nvar i, f, m = Math.min(a.t,this.t);\nfor(i = 0; i < m; ++i) r.data[i] = op(this.data[i],a.data[i]);\nif(a.t < this.t) {\n f = a.s&this.DM;\n for(i = m; i < this.t; ++i) r.data[i] = op(this.data[i],f);\n r.t = this.t;\n} else {\n f = this.s&this.DM;\n for(i = m; i < a.t; ++i) r.data[i] = op(f,a.data[i]);\n r.t = a.t;\n}\nr.s = op(this.s,a.s);\nr.clamp();\n}\n\n//(public) this & a\nfunction op_and(x,y) { return x&y; }\nfunction bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }\n\n//(public) this | a\nfunction op_or(x,y) { return x|y; }\nfunction bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }\n\n//(public) this ^ a\nfunction op_xor(x,y) { return x^y; }\nfunction bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }\n\n//(public) this & ~a\nfunction op_andnot(x,y) { return x&~y; }\nfunction bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }\n\n//(public) ~this\nfunction bnNot() {\nvar r = nbi();\nfor(var i = 0; i < this.t; ++i) r.data[i] = this.DM&~this.data[i];\nr.t = this.t;\nr.s = ~this.s;\nreturn r;\n}\n\n//(public) this << n\nfunction bnShiftLeft(n) {\nvar r = nbi();\nif(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);\nreturn r;\n}\n\n//(public) this >> n\nfunction bnShiftRight(n) {\nvar r = nbi();\nif(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);\nreturn r;\n}\n\n//return index of lowest 1-bit in x, x < 2^31\nfunction lbit(x) {\nif(x == 0) return -1;\nvar r = 0;\nif((x&0xffff) == 0) { x >>= 16; r += 16; }\nif((x&0xff) == 0) { x >>= 8; r += 8; }\nif((x&0xf) == 0) { x >>= 4; r += 4; }\nif((x&3) == 0) { x >>= 2; r += 2; }\nif((x&1) == 0) ++r;\nreturn r;\n}\n\n//(public) returns index of lowest 1-bit (or -1 if none)\nfunction bnGetLowestSetBit() {\nfor(var i = 0; i < this.t; ++i)\n if(this.data[i] != 0) return i*this.DB+lbit(this.data[i]);\nif(this.s < 0) return this.t*this.DB;\nreturn -1;\n}\n\n//return number of 1 bits in x\nfunction cbit(x) {\nvar r = 0;\nwhile(x != 0) { x &= x-1; ++r; }\nreturn r;\n}\n\n//(public) return number of set bits\nfunction bnBitCount() {\nvar r = 0, x = this.s&this.DM;\nfor(var i = 0; i < this.t; ++i) r += cbit(this.data[i]^x);\nreturn r;\n}\n\n//(public) true iff nth bit is set\nfunction bnTestBit(n) {\nvar j = Math.floor(n/this.DB);\nif(j >= this.t) return(this.s!=0);\nreturn((this.data[j]&(1<<(n%this.DB)))!=0);\n}\n\n//(protected) this op (1<<n)\nfunction bnpChangeBit(n,op) {\nvar r = BigInteger.ONE.shiftLeft(n);\nthis.bitwiseTo(r,op,r);\nreturn r;\n}\n\n//(public) this | (1<<n)\nfunction bnSetBit(n) { return this.changeBit(n,op_or); }\n\n//(public) this & ~(1<<n)\nfunction bnClearBit(n) { return this.changeBit(n,op_andnot); }\n\n//(public) this ^ (1<<n)\nfunction bnFlipBit(n) { return this.changeBit(n,op_xor); }\n\n//(protected) r = this + a\nfunction bnpAddTo(a,r) {\nvar i = 0, c = 0, m = Math.min(a.t,this.t);\nwhile(i < m) {\n c += this.data[i]+a.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n}\nif(a.t < this.t) {\n c += a.s;\n while(i < this.t) {\n c += this.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += this.s;\n} else {\n c += this.s;\n while(i < a.t) {\n c += a.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += a.s;\n}\nr.s = (c<0)?-1:0;\nif(c > 0) r.data[i++] = c;\nelse if(c < -1) r.data[i++] = this.DV+c;\nr.t = i;\nr.clamp();\n}\n\n//(public) this + a\nfunction bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }\n\n//(public) this - a\nfunction bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }\n\n//(public) this * a\nfunction bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }\n\n//(public) this / a\nfunction bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }\n\n//(public) this % a\nfunction bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }\n\n//(public) [this/a,this%a]\nfunction bnDivideAndRemainder(a) {\nvar q = nbi(), r = nbi();\nthis.divRemTo(a,q,r);\nreturn new Array(q,r);\n}\n\n//(protected) this *= n, this >= 0, 1 < n < DV\nfunction bnpDMultiply(n) {\nthis.data[this.t] = this.am(0,n-1,this,0,0,this.t);\n++this.t;\nthis.clamp();\n}\n\n//(protected) this += n << w words, this >= 0\nfunction bnpDAddOffset(n,w) {\nif(n == 0) return;\nwhile(this.t <= w) this.data[this.t++] = 0;\nthis.data[w] += n;\nwhile(this.data[w] >= this.DV) {\n this.data[w] -= this.DV;\n if(++w >= this.t) this.data[this.t++] = 0;\n ++this.data[w];\n}\n}\n\n//A \"null\" reducer\nfunction NullExp() {}\nfunction nNop(x) { return x; }\nfunction nMulTo(x,y,r) { x.multiplyTo(y,r); }\nfunction nSqrTo(x,r) { x.squareTo(r); }\n\nNullExp.prototype.convert = nNop;\nNullExp.prototype.revert = nNop;\nNullExp.prototype.mulTo = nMulTo;\nNullExp.prototype.sqrTo = nSqrTo;\n\n//(public) this^e\nfunction bnPow(e) { return this.exp(e,new NullExp()); }\n\n//(protected) r = lower n words of \"this * a\", a.t <= n\n//\"this\" should be the larger one if appropriate.\nfunction bnpMultiplyLowerTo(a,n,r) {\nvar i = Math.min(this.t+a.t,n);\nr.s = 0; // assumes a,this >= 0\nr.t = i;\nwhile(i > 0) r.data[--i] = 0;\nvar j;\nfor(j = r.t-this.t; i < j; ++i) r.data[i+this.t] = this.am(0,a.data[i],r,i,0,this.t);\nfor(j = Math.min(a.t,n); i < j; ++i) this.am(0,a.data[i],r,i,0,n-i);\nr.clamp();\n}\n\n//(protected) r = \"this * a\" without lower n words, n > 0\n//\"this\" should be the larger one if appropriate.\nfunction bnpMultiplyUpperTo(a,n,r) {\n--n;\nvar i = r.t = this.t+a.t-n;\nr.s = 0; // assumes a,this >= 0\nwhile(--i >= 0) r.data[i] = 0;\nfor(i = Math.max(n-this.t,0); i < a.t; ++i)\n r.data[this.t+i-n] = this.am(n-i,a.data[i],r,0,0,this.t+i-n);\nr.clamp();\nr.drShiftTo(1,r);\n}\n\n//Barrett modular reduction\nfunction Barrett(m) {\n// setup Barrett\nthis.r2 = nbi();\nthis.q3 = nbi();\nBigInteger.ONE.dlShiftTo(2*m.t,this.r2);\nthis.mu = this.r2.divide(m);\nthis.m = m;\n}\n\nfunction barrettConvert(x) {\nif(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);\nelse if(x.compareTo(this.m) < 0) return x;\nelse { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }\n}\n\nfunction barrettRevert(x) { return x; }\n\n//x = x mod m (HAC 14.42)\nfunction barrettReduce(x) {\nx.drShiftTo(this.m.t-1,this.r2);\nif(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }\nthis.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);\nthis.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);\nwhile(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);\nx.subTo(this.r2,x);\nwhile(x.compareTo(this.m) >= 0) x.subTo(this.m,x);\n}\n\n//r = x^2 mod m; x != r\nfunction barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\n//r = x*y mod m; x,y != r\nfunction barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\n\nBarrett.prototype.convert = barrettConvert;\nBarrett.prototype.revert = barrettRevert;\nBarrett.prototype.reduce = barrettReduce;\nBarrett.prototype.mulTo = barrettMulTo;\nBarrett.prototype.sqrTo = barrettSqrTo;\n\n//(public) this^e % m (HAC 14.85)\nfunction bnModPow(e,m) {\nvar i = e.bitLength(), k, r = nbv(1), z;\nif(i <= 0) return r;\nelse if(i < 18) k = 1;\nelse if(i < 48) k = 3;\nelse if(i < 144) k = 4;\nelse if(i < 768) k = 5;\nelse k = 6;\nif(i < 8)\n z = new Classic(m);\nelse if(m.isEven())\n z = new Barrett(m);\nelse\n z = new Montgomery(m);\n\n// precomputation\nvar g = new Array(), n = 3, k1 = k-1, km = (1<<k)-1;\ng[1] = z.convert(this);\nif(k > 1) {\n var g2 = nbi();\n z.sqrTo(g[1],g2);\n while(n <= km) {\n g[n] = nbi();\n z.mulTo(g2,g[n-2],g[n]);\n n += 2;\n }\n}\n\nvar j = e.t-1, w, is1 = true, r2 = nbi(), t;\ni = nbits(e.data[j])-1;\nwhile(j >= 0) {\n if(i >= k1) w = (e.data[j]>>(i-k1))&km;\n else {\n w = (e.data[j]&((1<<(i+1))-1))<<(k1-i);\n if(j > 0) w |= e.data[j-1]>>(this.DB+i-k1);\n }\n\n n = k;\n while((w&1) == 0) { w >>= 1; --n; }\n if((i -= n) < 0) { i += this.DB; --j; }\n if(is1) { // ret == 1, don't bother squaring or multiplying it\n g[w].copyTo(r);\n is1 = false;\n } else {\n while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }\n if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }\n z.mulTo(r2,g[w],r);\n }\n\n while(j >= 0 && (e.data[j]&(1<<i)) == 0) {\n z.sqrTo(r,r2); t = r; r = r2; r2 = t;\n if(--i < 0) { i = this.DB-1; --j; }\n }\n}\nreturn z.revert(r);\n}\n\n//(public) gcd(this,a) (HAC 14.54)\nfunction bnGCD(a) {\nvar x = (this.s<0)?this.negate():this.clone();\nvar y = (a.s<0)?a.negate():a.clone();\nif(x.compareTo(y) < 0) { var t = x; x = y; y = t; }\nvar i = x.getLowestSetBit(), g = y.getLowestSetBit();\nif(g < 0) return x;\nif(i < g) g = i;\nif(g > 0) {\n x.rShiftTo(g,x);\n y.rShiftTo(g,y);\n}\nwhile(x.signum() > 0) {\n if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);\n if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);\n if(x.compareTo(y) >= 0) {\n x.subTo(y,x);\n x.rShiftTo(1,x);\n } else {\n y.subTo(x,y);\n y.rShiftTo(1,y);\n }\n}\nif(g > 0) y.lShiftTo(g,y);\nreturn y;\n}\n\n//(protected) this % n, n < 2^26\nfunction bnpModInt(n) {\nif(n <= 0) return 0;\nvar d = this.DV%n, r = (this.s<0)?n-1:0;\nif(this.t > 0)\n if(d == 0) r = this.data[0]%n;\n else for(var i = this.t-1; i >= 0; --i) r = (d*r+this.data[i])%n;\nreturn r;\n}\n\n//(public) 1/this % m (HAC 14.61)\nfunction bnModInverse(m) {\nvar ac = m.isEven();\nif((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;\nvar u = m.clone(), v = this.clone();\nvar a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);\nwhile(u.signum() != 0) {\n while(u.isEven()) {\n u.rShiftTo(1,u);\n if(ac) {\n if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }\n a.rShiftTo(1,a);\n } else if(!b.isEven()) b.subTo(m,b);\n b.rShiftTo(1,b);\n }\n while(v.isEven()) {\n v.rShiftTo(1,v);\n if(ac) {\n if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }\n c.rShiftTo(1,c);\n } else if(!d.isEven()) d.subTo(m,d);\n d.rShiftTo(1,d);\n }\n if(u.compareTo(v) >= 0) {\n u.subTo(v,u);\n if(ac) a.subTo(c,a);\n b.subTo(d,b);\n } else {\n v.subTo(u,v);\n if(ac) c.subTo(a,c);\n d.subTo(b,d);\n }\n}\nif(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;\nif(d.compareTo(m) >= 0) return d.subtract(m);\nif(d.signum() < 0) d.addTo(m,d); else return d;\nif(d.signum() < 0) return d.add(m); else return d;\n}\n\nvar lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509];\nvar lplim = (1<<26)/lowprimes[lowprimes.length-1];\n\n//(public) test primality with certainty >= 1-.5^t\nfunction bnIsProbablePrime(t) {\nvar i, x = this.abs();\nif(x.t == 1 && x.data[0] <= lowprimes[lowprimes.length-1]) {\n for(i = 0; i < lowprimes.length; ++i)\n if(x.data[0] == lowprimes[i]) return true;\n return false;\n}\nif(x.isEven()) return false;\ni = 1;\nwhile(i < lowprimes.length) {\n var m = lowprimes[i], j = i+1;\n while(j < lowprimes.length && m < lplim) m *= lowprimes[j++];\n m = x.modInt(m);\n while(i < j) if(m%lowprimes[i++] == 0) return false;\n}\nreturn x.millerRabin(t);\n}\n\n//(protected) true if probably prime (HAC 4.24, Miller-Rabin)\nfunction bnpMillerRabin(t) {\nvar n1 = this.subtract(BigInteger.ONE);\nvar k = n1.getLowestSetBit();\nif(k <= 0) return false;\nvar r = n1.shiftRight(k);\nvar prng = bnGetPrng();\nvar a;\nfor(var i = 0; i < t; ++i) {\n // select witness 'a' at random from between 1 and n1\n do {\n a = new BigInteger(this.bitLength(), prng);\n }\n while(a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0);\n var y = a.modPow(r,this);\n if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {\n var j = 1;\n while(j++ < k && y.compareTo(n1) != 0) {\n y = y.modPowInt(2,this);\n if(y.compareTo(BigInteger.ONE) == 0) return false;\n }\n if(y.compareTo(n1) != 0) return false;\n }\n}\nreturn true;\n}\n\n// get pseudo random number generator\nfunction bnGetPrng() {\n // create prng with api that matches BigInteger secure random\n return {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n for(var i = 0; i < x.length; ++i) {\n x[i] = Math.floor(Math.random() * 0x0100);\n }\n }\n };\n}\n\n//protected\nBigInteger.prototype.chunkSize = bnpChunkSize;\nBigInteger.prototype.toRadix = bnpToRadix;\nBigInteger.prototype.fromRadix = bnpFromRadix;\nBigInteger.prototype.fromNumber = bnpFromNumber;\nBigInteger.prototype.bitwiseTo = bnpBitwiseTo;\nBigInteger.prototype.changeBit = bnpChangeBit;\nBigInteger.prototype.addTo = bnpAddTo;\nBigInteger.prototype.dMultiply = bnpDMultiply;\nBigInteger.prototype.dAddOffset = bnpDAddOffset;\nBigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;\nBigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;\nBigInteger.prototype.modInt = bnpModInt;\nBigInteger.prototype.millerRabin = bnpMillerRabin;\n\n//public\nBigInteger.prototype.clone = bnClone;\nBigInteger.prototype.intValue = bnIntValue;\nBigInteger.prototype.byteValue = bnByteValue;\nBigInteger.prototype.shortValue = bnShortValue;\nBigInteger.prototype.signum = bnSigNum;\nBigInteger.prototype.toByteArray = bnToByteArray;\nBigInteger.prototype.equals = bnEquals;\nBigInteger.prototype.min = bnMin;\nBigInteger.prototype.max = bnMax;\nBigInteger.prototype.and = bnAnd;\nBigInteger.prototype.or = bnOr;\nBigInteger.prototype.xor = bnXor;\nBigInteger.prototype.andNot = bnAndNot;\nBigInteger.prototype.not = bnNot;\nBigInteger.prototype.shiftLeft = bnShiftLeft;\nBigInteger.prototype.shiftRight = bnShiftRight;\nBigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;\nBigInteger.prototype.bitCount = bnBitCount;\nBigInteger.prototype.testBit = bnTestBit;\nBigInteger.prototype.setBit = bnSetBit;\nBigInteger.prototype.clearBit = bnClearBit;\nBigInteger.prototype.flipBit = bnFlipBit;\nBigInteger.prototype.add = bnAdd;\nBigInteger.prototype.subtract = bnSubtract;\nBigInteger.prototype.multiply = bnMultiply;\nBigInteger.prototype.divide = bnDivide;\nBigInteger.prototype.remainder = bnRemainder;\nBigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;\nBigInteger.prototype.modPow = bnModPow;\nBigInteger.prototype.modInverse = bnModInverse;\nBigInteger.prototype.pow = bnPow;\nBigInteger.prototype.gcd = bnGCD;\nBigInteger.prototype.isProbablePrime = bnIsProbablePrime;\n\n//BigInteger interfaces not implemented in jsbn:\n\n//BigInteger(int signum, byte[] magnitude)\n//double doubleValue()\n//float floatValue()\n//int hashCode()\n//long longValue()\n//static BigInteger valueOf(long val)\n","/**\n * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha1 = module.exports = forge.sha1 = forge.sha1 || {};\nforge.md.sha1 = forge.md.algorithms.sha1 = sha1;\n\n/**\n * Creates a SHA-1 message digest object.\n *\n * @return a message digest object.\n */\nsha1.create = function() {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n // SHA-1 state contains five 32-bit integers\n var _state = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for word storage\n var _w = new Array(80);\n\n // message digest object\n var md = {\n algorithm: 'sha1',\n blockLength: 64,\n digestLength: 20,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 8\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength64 for backwards-compatibility)\n md.fullMessageLength = md.messageLength64 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _state = {\n h0: 0x67452301,\n h1: 0xEFCDAB89,\n h2: 0x98BADCFE,\n h3: 0x10325476,\n h4: 0xC3D2E1F0\n };\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_state, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-1 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 448 mod 512. In other words,\n the data to be digested must be a multiple of 512 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 8 bytes (64\n bits), that means that the last segment of the data must have 56 bytes\n (448 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 448 mod 512 because\n 512 - 128 = 448.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 448 mod 512, then 512 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var s2 = {\n h0: _state.h0,\n h1: _state.h1,\n h2: _state.h2,\n h3: _state.h3,\n h4: _state.h4\n };\n _update(s2, _w, finalBlock);\n var rval = forge.util.createBuffer();\n rval.putInt32(s2.h0);\n rval.putInt32(s2.h1);\n rval.putInt32(s2.h2);\n rval.putInt32(s2.h3);\n rval.putInt32(s2.h4);\n return rval;\n };\n\n return md;\n};\n\n// sha-1 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 64);\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-1 state with the given byte buffer.\n *\n * @param s the SHA-1 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (64 byte) chunks\n var t, a, b, c, d, e, f, i;\n var len = bytes.length();\n while(len >= 64) {\n // the w array will be populated with sixteen 32-bit big-endian words\n // and then extended into 80 32-bit words according to SHA-1 algorithm\n // and for 32-79 using Max Locktyukhin's optimization\n\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n e = s.h4;\n\n // round 1\n for(i = 0; i < 16; ++i) {\n t = bytes.getInt32();\n w[i] = t;\n f = d ^ (b & (c ^ d));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n for(; i < 20; ++i) {\n t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);\n t = (t << 1) | (t >>> 31);\n w[i] = t;\n f = d ^ (b & (c ^ d));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 2\n for(; i < 32; ++i) {\n t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);\n t = (t << 1) | (t >>> 31);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n for(; i < 40; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 3\n for(; i < 60; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = (b & c) | (d & (b ^ c));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 4\n for(; i < 80; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n s.h4 = (s.h4 + e) | 0;\n\n len -= 64;\n }\n}\n","/**\n * Partial implementation of PKCS#1 v2.2: RSA-OEAP\n *\n * Modified but based on the following MIT and BSD licensed code:\n *\n * https://github.com/kjur/jsjws/blob/master/rsa.js:\n *\n * The 'jsjws'(JSON Web Signature JavaScript Library) License\n *\n * Copyright (c) 2012 Kenji Urushima\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * http://webrsa.cvs.sourceforge.net/viewvc/webrsa/Client/RSAES-OAEP.js?content-type=text%2Fplain:\n *\n * RSAES-OAEP.js\n * $Id: RSAES-OAEP.js,v 1.1.1.1 2003/03/19 15:37:20 ellispritchard Exp $\n * JavaScript Implementation of PKCS #1 v2.1 RSA CRYPTOGRAPHY STANDARD (RSA Laboratories, June 14, 2002)\n * Copyright (C) Ellis Pritchard, Guardian Unlimited 2003.\n * Contact: ellis@nukinetics.com\n * Distributed under the BSD License.\n *\n * Official documentation: http://www.rsa.com/rsalabs/node.asp?id=2125\n *\n * @author Evan Jones (http://evanjones.ca/)\n * @author Dave Longley\n *\n * Copyright (c) 2013-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./random');\nrequire('./sha1');\n\n// shortcut for PKCS#1 API\nvar pkcs1 = module.exports = forge.pkcs1 = forge.pkcs1 || {};\n\n/**\n * Encode the given RSAES-OAEP message (M) using key, with optional label (L)\n * and seed.\n *\n * This method does not perform RSA encryption, it only encodes the message\n * using RSAES-OAEP.\n *\n * @param key the RSA key to use.\n * @param message the message to encode.\n * @param options the options to use:\n * label an optional label to use.\n * seed the seed to use.\n * md the message digest object to use, undefined for SHA-1.\n * mgf1 optional mgf1 parameters:\n * md the message digest object to use for MGF1.\n *\n * @return the encoded message bytes.\n */\npkcs1.encode_rsa_oaep = function(key, message, options) {\n // parse arguments\n var label;\n var seed;\n var md;\n var mgf1Md;\n // legacy args (label, seed, md)\n if(typeof options === 'string') {\n label = options;\n seed = arguments[3] || undefined;\n md = arguments[4] || undefined;\n } else if(options) {\n label = options.label || undefined;\n seed = options.seed || undefined;\n md = options.md || undefined;\n if(options.mgf1 && options.mgf1.md) {\n mgf1Md = options.mgf1.md;\n }\n }\n\n // default OAEP to SHA-1 message digest\n if(!md) {\n md = forge.md.sha1.create();\n } else {\n md.start();\n }\n\n // default MGF-1 to same as OAEP\n if(!mgf1Md) {\n mgf1Md = md;\n }\n\n // compute length in bytes and check output\n var keyLength = Math.ceil(key.n.bitLength() / 8);\n var maxLength = keyLength - 2 * md.digestLength - 2;\n if(message.length > maxLength) {\n var error = new Error('RSAES-OAEP input message length is too long.');\n error.length = message.length;\n error.maxLength = maxLength;\n throw error;\n }\n\n if(!label) {\n label = '';\n }\n md.update(label, 'raw');\n var lHash = md.digest();\n\n var PS = '';\n var PS_length = maxLength - message.length;\n for(var i = 0; i < PS_length; i++) {\n PS += '\\x00';\n }\n\n var DB = lHash.getBytes() + PS + '\\x01' + message;\n\n if(!seed) {\n seed = forge.random.getBytes(md.digestLength);\n } else if(seed.length !== md.digestLength) {\n var error = new Error('Invalid RSAES-OAEP seed. The seed length must ' +\n 'match the digest length.');\n error.seedLength = seed.length;\n error.digestLength = md.digestLength;\n throw error;\n }\n\n var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);\n var maskedDB = forge.util.xorBytes(DB, dbMask, DB.length);\n\n var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);\n var maskedSeed = forge.util.xorBytes(seed, seedMask, seed.length);\n\n // return encoded message\n return '\\x00' + maskedSeed + maskedDB;\n};\n\n/**\n * Decode the given RSAES-OAEP encoded message (EM) using key, with optional\n * label (L).\n *\n * This method does not perform RSA decryption, it only decodes the message\n * using RSAES-OAEP.\n *\n * @param key the RSA key to use.\n * @param em the encoded message to decode.\n * @param options the options to use:\n * label an optional label to use.\n * md the message digest object to use for OAEP, undefined for SHA-1.\n * mgf1 optional mgf1 parameters:\n * md the message digest object to use for MGF1.\n *\n * @return the decoded message bytes.\n */\npkcs1.decode_rsa_oaep = function(key, em, options) {\n // parse args\n var label;\n var md;\n var mgf1Md;\n // legacy args\n if(typeof options === 'string') {\n label = options;\n md = arguments[3] || undefined;\n } else if(options) {\n label = options.label || undefined;\n md = options.md || undefined;\n if(options.mgf1 && options.mgf1.md) {\n mgf1Md = options.mgf1.md;\n }\n }\n\n // compute length in bytes\n var keyLength = Math.ceil(key.n.bitLength() / 8);\n\n if(em.length !== keyLength) {\n var error = new Error('RSAES-OAEP encoded message length is invalid.');\n error.length = em.length;\n error.expectedLength = keyLength;\n throw error;\n }\n\n // default OAEP to SHA-1 message digest\n if(md === undefined) {\n md = forge.md.sha1.create();\n } else {\n md.start();\n }\n\n // default MGF-1 to same as OAEP\n if(!mgf1Md) {\n mgf1Md = md;\n }\n\n if(keyLength < 2 * md.digestLength + 2) {\n throw new Error('RSAES-OAEP key is too short for the hash function.');\n }\n\n if(!label) {\n label = '';\n }\n md.update(label, 'raw');\n var lHash = md.digest().getBytes();\n\n // split the message into its parts\n var y = em.charAt(0);\n var maskedSeed = em.substring(1, md.digestLength + 1);\n var maskedDB = em.substring(1 + md.digestLength);\n\n var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);\n var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length);\n\n var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);\n var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length);\n\n var lHashPrime = db.substring(0, md.digestLength);\n\n // constant time check that all values match what is expected\n var error = (y !== '\\x00');\n\n // constant time check lHash vs lHashPrime\n for(var i = 0; i < md.digestLength; ++i) {\n error |= (lHash.charAt(i) !== lHashPrime.charAt(i));\n }\n\n // \"constant time\" find the 0x1 byte separating the padding (zeros) from the\n // message\n // TODO: It must be possible to do this in a better/smarter way?\n var in_ps = 1;\n var index = md.digestLength;\n for(var j = md.digestLength; j < db.length; j++) {\n var code = db.charCodeAt(j);\n\n var is_0 = (code & 0x1) ^ 0x1;\n\n // non-zero if not 0 or 1 in the ps section\n var error_mask = in_ps ? 0xfffe : 0x0000;\n error |= (code & error_mask);\n\n // latch in_ps to zero after we find 0x1\n in_ps = in_ps & is_0;\n index += in_ps;\n }\n\n if(error || db.charCodeAt(index) !== 0x1) {\n throw new Error('Invalid RSAES-OAEP padding.');\n }\n\n return db.substring(index + 1);\n};\n\nfunction rsa_mgf1(seed, maskLength, hash) {\n // default to SHA-1 message digest\n if(!hash) {\n hash = forge.md.sha1.create();\n }\n var t = '';\n var count = Math.ceil(maskLength / hash.digestLength);\n for(var i = 0; i < count; ++i) {\n var c = String.fromCharCode(\n (i >> 24) & 0xFF, (i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF);\n hash.start();\n hash.update(seed + c);\n t += hash.digest().getBytes();\n }\n return t.substring(0, maskLength);\n}\n","/**\n * Prime number generation API.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./jsbn');\nrequire('./random');\n\n(function() {\n\n// forge.prime already defined\nif(forge.prime) {\n module.exports = forge.prime;\n return;\n}\n\n/* PRIME API */\nvar prime = module.exports = forge.prime = forge.prime || {};\n\nvar BigInteger = forge.jsbn.BigInteger;\n\n// primes are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29\nvar GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];\nvar THIRTY = new BigInteger(null);\nTHIRTY.fromInt(30);\nvar op_or = function(x, y) {return x|y;};\n\n/**\n * Generates a random probable prime with the given number of bits.\n *\n * Alternative algorithms can be specified by name as a string or as an\n * object with custom options like so:\n *\n * {\n * name: 'PRIMEINC',\n * options: {\n * maxBlockTime: <the maximum amount of time to block the main\n * thread before allowing I/O other JS to run>,\n * millerRabinTests: <the number of miller-rabin tests to run>,\n * workerScript: <the worker script URL>,\n * workers: <the number of web workers (if supported) to use,\n * -1 to use estimated cores minus one>.\n * workLoad: the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * }\n * }\n *\n * @param bits the number of bits for the prime number.\n * @param options the options to use.\n * [algorithm] the algorithm to use (default: 'PRIMEINC').\n * [prng] a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\".\n *\n * @return callback(err, num) called once the operation completes.\n */\nprime.generateProbablePrime = function(bits, options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n // default to PRIMEINC algorithm\n var algorithm = options.algorithm || 'PRIMEINC';\n if(typeof algorithm === 'string') {\n algorithm = {name: algorithm};\n }\n algorithm.options = algorithm.options || {};\n\n // create prng with api that matches BigInteger secure random\n var prng = options.prng || forge.random;\n var rng = {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n var b = prng.getBytesSync(x.length);\n for(var i = 0; i < x.length; ++i) {\n x[i] = b.charCodeAt(i);\n }\n }\n };\n\n if(algorithm.name === 'PRIMEINC') {\n return primeincFindPrime(bits, rng, algorithm.options, callback);\n }\n\n throw new Error('Invalid prime generation algorithm: ' + algorithm.name);\n};\n\nfunction primeincFindPrime(bits, rng, options, callback) {\n if('workers' in options) {\n return primeincFindPrimeWithWorkers(bits, rng, options, callback);\n }\n return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);\n}\n\nfunction primeincFindPrimeWithoutWorkers(bits, rng, options, callback) {\n // initialize random number\n var num = generateRandom(bits, rng);\n\n /* Note: All primes are of the form 30k+i for i < 30 and gcd(30, i)=1. The\n number we are given is always aligned at 30k + 1. Each time the number is\n determined not to be prime we add to get to the next 'i', eg: if the number\n was at 30k + 1 we add 6. */\n var deltaIdx = 0;\n\n // get required number of MR tests\n var mrTests = getMillerRabinTests(num.bitLength());\n if('millerRabinTests' in options) {\n mrTests = options.millerRabinTests;\n }\n\n // find prime nearest to 'num' for maxBlockTime ms\n // 10 ms gives 5ms of leeway for other calculations before dropping\n // below 60fps (1000/60 == 16.67), but in reality, the number will\n // likely be higher due to an 'atomic' big int modPow\n var maxBlockTime = 10;\n if('maxBlockTime' in options) {\n maxBlockTime = options.maxBlockTime;\n }\n\n _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);\n}\n\nfunction _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) {\n var start = +new Date();\n do {\n // overflow, regenerate random number\n if(num.bitLength() > bits) {\n num = generateRandom(bits, rng);\n }\n // do primality test\n if(num.isProbablePrime(mrTests)) {\n return callback(null, num);\n }\n // get next potential prime\n num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);\n } while(maxBlockTime < 0 || (+new Date() - start < maxBlockTime));\n\n // keep trying later\n forge.util.setImmediate(function() {\n _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);\n });\n}\n\n// NOTE: This algorithm is indeterminate in nature because workers\n// run in parallel looking at different segments of numbers. Even if this\n// algorithm is run twice with the same input from a predictable RNG, it\n// may produce different outputs.\nfunction primeincFindPrimeWithWorkers(bits, rng, options, callback) {\n // web workers unavailable\n if(typeof Worker === 'undefined') {\n return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);\n }\n\n // initialize random number\n var num = generateRandom(bits, rng);\n\n // use web workers to generate keys\n var numWorkers = options.workers;\n var workLoad = options.workLoad || 100;\n var range = workLoad * 30 / 8;\n var workerScript = options.workerScript || 'forge/prime.worker.js';\n if(numWorkers === -1) {\n return forge.util.estimateCores(function(err, cores) {\n if(err) {\n // default to 2\n cores = 2;\n }\n numWorkers = cores - 1;\n generate();\n });\n }\n generate();\n\n function generate() {\n // require at least 1 worker\n numWorkers = Math.max(1, numWorkers);\n\n // TODO: consider optimizing by starting workers outside getPrime() ...\n // note that in order to clean up they will have to be made internally\n // asynchronous which may actually be slower\n\n // start workers immediately\n var workers = [];\n for(var i = 0; i < numWorkers; ++i) {\n // FIXME: fix path or use blob URLs\n workers[i] = new Worker(workerScript);\n }\n var running = numWorkers;\n\n // listen for requests from workers and assign ranges to find prime\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].addEventListener('message', workerMessage);\n }\n\n /* Note: The distribution of random numbers is unknown. Therefore, each\n web worker is continuously allocated a range of numbers to check for a\n random number until one is found.\n\n Every 30 numbers will be checked just 8 times, because prime numbers\n have the form:\n\n 30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this)\n\n Therefore, if we want a web worker to run N checks before asking for\n a new range of numbers, each range must contain N*30/8 numbers.\n\n For 100 checks (workLoad), this is a range of 375. */\n\n var found = false;\n function workerMessage(e) {\n // ignore message, prime already found\n if(found) {\n return;\n }\n\n --running;\n var data = e.data;\n if(data.found) {\n // terminate all workers\n for(var i = 0; i < workers.length; ++i) {\n workers[i].terminate();\n }\n found = true;\n return callback(null, new BigInteger(data.prime, 16));\n }\n\n // overflow, regenerate random number\n if(num.bitLength() > bits) {\n num = generateRandom(bits, rng);\n }\n\n // assign new range to check\n var hex = num.toString(16);\n\n // start prime search\n e.target.postMessage({\n hex: hex,\n workLoad: workLoad\n });\n\n num.dAddOffset(range, 0);\n }\n }\n}\n\n/**\n * Generates a random number using the given number of bits and RNG.\n *\n * @param bits the number of bits for the number.\n * @param rng the random number generator to use.\n *\n * @return the random number.\n */\nfunction generateRandom(bits, rng) {\n var num = new BigInteger(bits, rng);\n // force MSB set\n var bits1 = bits - 1;\n if(!num.testBit(bits1)) {\n num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num);\n }\n // align number on 30k+1 boundary\n num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0);\n return num;\n}\n\n/**\n * Returns the required number of Miller-Rabin tests to generate a\n * prime with an error probability of (1/2)^80.\n *\n * See Handbook of Applied Cryptography Chapter 4, Table 4.4.\n *\n * @param bits the bit size.\n *\n * @return the required number of iterations.\n */\nfunction getMillerRabinTests(bits) {\n if(bits <= 100) return 27;\n if(bits <= 150) return 18;\n if(bits <= 200) return 15;\n if(bits <= 250) return 12;\n if(bits <= 300) return 9;\n if(bits <= 350) return 8;\n if(bits <= 400) return 7;\n if(bits <= 500) return 6;\n if(bits <= 600) return 5;\n if(bits <= 800) return 4;\n if(bits <= 1250) return 3;\n return 2;\n}\n\n})();\n","/**\n * Javascript implementation of basic RSA algorithms.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n *\n * The only algorithm currently supported for PKI is RSA.\n *\n * An RSA key is often stored in ASN.1 DER format. The SubjectPublicKeyInfo\n * ASN.1 structure is composed of an algorithm of type AlgorithmIdentifier\n * and a subjectPublicKey of type bit string.\n *\n * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters\n * for the algorithm, if any. In the case of RSA, there aren't any.\n *\n * SubjectPublicKeyInfo ::= SEQUENCE {\n * algorithm AlgorithmIdentifier,\n * subjectPublicKey BIT STRING\n * }\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * For an RSA public key, the subjectPublicKey is:\n *\n * RSAPublicKey ::= SEQUENCE {\n * modulus INTEGER, -- n\n * publicExponent INTEGER -- e\n * }\n *\n * PrivateKeyInfo ::= SEQUENCE {\n * version Version,\n * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,\n * privateKey PrivateKey,\n * attributes [0] IMPLICIT Attributes OPTIONAL\n * }\n *\n * Version ::= INTEGER\n * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier\n * PrivateKey ::= OCTET STRING\n * Attributes ::= SET OF Attribute\n *\n * An RSA private key as the following structure:\n *\n * RSAPrivateKey ::= SEQUENCE {\n * version Version,\n * modulus INTEGER, -- n\n * publicExponent INTEGER, -- e\n * privateExponent INTEGER, -- d\n * prime1 INTEGER, -- p\n * prime2 INTEGER, -- q\n * exponent1 INTEGER, -- d mod (p-1)\n * exponent2 INTEGER, -- d mod (q-1)\n * coefficient INTEGER -- (inverse of q) mod p\n * }\n *\n * Version ::= INTEGER\n *\n * The OID for the RSA key algorithm is: 1.2.840.113549.1.1.1\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./jsbn');\nrequire('./oids');\nrequire('./pkcs1');\nrequire('./prime');\nrequire('./random');\nrequire('./util');\n\nif(typeof BigInteger === 'undefined') {\n var BigInteger = forge.jsbn.BigInteger;\n}\n\nvar _crypto = forge.util.isNodejs ? require('crypto') : null;\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n// shortcut for util API\nvar util = forge.util;\n\n/*\n * RSA encryption and decryption, see RFC 2313.\n */\nforge.pki = forge.pki || {};\nmodule.exports = forge.pki.rsa = forge.rsa = forge.rsa || {};\nvar pki = forge.pki;\n\n// for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29\nvar GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];\n\n// validator for a PrivateKeyInfo structure\nvar privateKeyValidator = {\n // PrivateKeyInfo\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // Version (INTEGER)\n name: 'PrivateKeyInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyVersion'\n }, {\n // privateKeyAlgorithm\n name: 'PrivateKeyInfo.privateKeyAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'privateKeyOid'\n }]\n }, {\n // PrivateKey\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'privateKey'\n }]\n};\n\n// validator for an RSA private key\nvar rsaPrivateKeyValidator = {\n // RSAPrivateKey\n name: 'RSAPrivateKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // Version (INTEGER)\n name: 'RSAPrivateKey.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyVersion'\n }, {\n // modulus (n)\n name: 'RSAPrivateKey.modulus',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyModulus'\n }, {\n // publicExponent (e)\n name: 'RSAPrivateKey.publicExponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPublicExponent'\n }, {\n // privateExponent (d)\n name: 'RSAPrivateKey.privateExponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrivateExponent'\n }, {\n // prime1 (p)\n name: 'RSAPrivateKey.prime1',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrime1'\n }, {\n // prime2 (q)\n name: 'RSAPrivateKey.prime2',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrime2'\n }, {\n // exponent1 (d mod (p-1))\n name: 'RSAPrivateKey.exponent1',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyExponent1'\n }, {\n // exponent2 (d mod (q-1))\n name: 'RSAPrivateKey.exponent2',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyExponent2'\n }, {\n // coefficient ((inverse of q) mod p)\n name: 'RSAPrivateKey.coefficient',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyCoefficient'\n }]\n};\n\n// validator for an RSA public key\nvar rsaPublicKeyValidator = {\n // RSAPublicKey\n name: 'RSAPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // modulus (n)\n name: 'RSAPublicKey.modulus',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'publicKeyModulus'\n }, {\n // publicExponent (e)\n name: 'RSAPublicKey.exponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'publicKeyExponent'\n }]\n};\n\n// validator for an SubjectPublicKeyInfo structure\n// Note: Currently only works with an RSA public key\nvar publicKeyValidator = forge.pki.rsa.publicKeyValidator = {\n name: 'SubjectPublicKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'subjectPublicKeyInfo',\n value: [{\n name: 'SubjectPublicKeyInfo.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'publicKeyOid'\n }]\n }, {\n // subjectPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n value: [{\n // RSAPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n captureAsn1: 'rsaPublicKey'\n }]\n }]\n};\n\n// validator for a DigestInfo structure\nvar digestInfoValidator = {\n name: 'DigestInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'DigestInfo.DigestAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'DigestInfo.DigestAlgorithm.algorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'algorithmIdentifier'\n }, {\n // NULL paramters\n name: 'DigestInfo.DigestAlgorithm.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.NULL,\n // captured only to check existence for md2 and md5\n capture: 'parameters',\n optional: true,\n constructed: false\n }]\n }, {\n // digest\n name: 'DigestInfo.digest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'digest'\n }]\n};\n\n/**\n * Wrap digest in DigestInfo object.\n *\n * This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447.\n *\n * DigestInfo ::= SEQUENCE {\n * digestAlgorithm DigestAlgorithmIdentifier,\n * digest Digest\n * }\n *\n * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n * Digest ::= OCTET STRING\n *\n * @param md the message digest object with the hash to sign.\n *\n * @return the encoded message (ready for RSA encrytion)\n */\nvar emsaPkcs1v15encode = function(md) {\n // get the oid for the algorithm\n var oid;\n if(md.algorithm in pki.oids) {\n oid = pki.oids[md.algorithm];\n } else {\n var error = new Error('Unknown message digest algorithm.');\n error.algorithm = md.algorithm;\n throw error;\n }\n var oidBytes = asn1.oidToDer(oid).getBytes();\n\n // create the digest info\n var digestInfo = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var digestAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n digestAlgorithm.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes));\n digestAlgorithm.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ''));\n var digest = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING,\n false, md.digest().getBytes());\n digestInfo.value.push(digestAlgorithm);\n digestInfo.value.push(digest);\n\n // encode digest info\n return asn1.toDer(digestInfo).getBytes();\n};\n\n/**\n * Performs x^c mod n (RSA encryption or decryption operation).\n *\n * @param x the number to raise and mod.\n * @param key the key to use.\n * @param pub true if the key is public, false if private.\n *\n * @return the result of x^c mod n.\n */\nvar _modPow = function(x, key, pub) {\n if(pub) {\n return x.modPow(key.e, key.n);\n }\n\n if(!key.p || !key.q) {\n // allow calculation without CRT params (slow)\n return x.modPow(key.d, key.n);\n }\n\n // pre-compute dP, dQ, and qInv if necessary\n if(!key.dP) {\n key.dP = key.d.mod(key.p.subtract(BigInteger.ONE));\n }\n if(!key.dQ) {\n key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE));\n }\n if(!key.qInv) {\n key.qInv = key.q.modInverse(key.p);\n }\n\n /* Chinese remainder theorem (CRT) states:\n\n Suppose n1, n2, ..., nk are positive integers which are pairwise\n coprime (n1 and n2 have no common factors other than 1). For any\n integers x1, x2, ..., xk there exists an integer x solving the\n system of simultaneous congruences (where ~= means modularly\n congruent so a ~= b mod n means a mod n = b mod n):\n\n x ~= x1 mod n1\n x ~= x2 mod n2\n ...\n x ~= xk mod nk\n\n This system of congruences has a single simultaneous solution x\n between 0 and n - 1. Furthermore, each xk solution and x itself\n is congruent modulo the product n = n1*n2*...*nk.\n So x1 mod n = x2 mod n = xk mod n = x mod n.\n\n The single simultaneous solution x can be solved with the following\n equation:\n\n x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni.\n\n Where x is less than n, xi = x mod ni.\n\n For RSA we are only concerned with k = 2. The modulus n = pq, where\n p and q are coprime. The RSA decryption algorithm is:\n\n y = x^d mod n\n\n Given the above:\n\n x1 = x^d mod p\n r1 = n/p = q\n s1 = q^-1 mod p\n x2 = x^d mod q\n r2 = n/q = p\n s2 = p^-1 mod q\n\n So y = (x1r1s1 + x2r2s2) mod n\n = ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n\n\n According to Fermat's Little Theorem, if the modulus P is prime,\n for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P.\n Since A is not divisible by P it follows that if:\n N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore:\n\n A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort\n to calculate). In order to calculate x^d mod p more quickly the\n exponent d mod (p - 1) is stored in the RSA private key (the same\n is done for x^d mod q). These values are referred to as dP and dQ\n respectively. Therefore we now have:\n\n y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n\n\n Since we'll be reducing x^dP by modulo p (same for q) we can also\n reduce x by p (and q respectively) before hand. Therefore, let\n\n xp = ((x mod p)^dP mod p), and\n xq = ((x mod q)^dQ mod q), yielding:\n\n y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n\n\n This can be further reduced to a simple algorithm that only\n requires 1 inverse (the q inverse is used) to be used and stored.\n The algorithm is called Garner's algorithm. If qInv is the\n inverse of q, we simply calculate:\n\n y = (qInv*(xp - xq) mod p) * q + xq\n\n However, there are two further complications. First, we need to\n ensure that xp > xq to prevent signed BigIntegers from being used\n so we add p until this is true (since we will be mod'ing with\n p anyway). Then, there is a known timing attack on algorithms\n using the CRT. To mitigate this risk, \"cryptographic blinding\"\n should be used. This requires simply generating a random number r\n between 0 and n-1 and its inverse and multiplying x by r^e before\n calculating y and then multiplying y by r^-1 afterwards. Note that\n r must be coprime with n (gcd(r, n) === 1) in order to have an\n inverse.\n */\n\n // cryptographic blinding\n var r;\n do {\n r = new BigInteger(\n forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)),\n 16);\n } while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE));\n x = x.multiply(r.modPow(key.e, key.n)).mod(key.n);\n\n // calculate xp and xq\n var xp = x.mod(key.p).modPow(key.dP, key.p);\n var xq = x.mod(key.q).modPow(key.dQ, key.q);\n\n // xp must be larger than xq to avoid signed bit usage\n while(xp.compareTo(xq) < 0) {\n xp = xp.add(key.p);\n }\n\n // do last step\n var y = xp.subtract(xq)\n .multiply(key.qInv).mod(key.p)\n .multiply(key.q).add(xq);\n\n // remove effect of random for cryptographic blinding\n y = y.multiply(r.modInverse(key.n)).mod(key.n);\n\n return y;\n};\n\n/**\n * NOTE: THIS METHOD IS DEPRECATED, use 'sign' on a private key object or\n * 'encrypt' on a public key object instead.\n *\n * Performs RSA encryption.\n *\n * The parameter bt controls whether to put padding bytes before the\n * message passed in. Set bt to either true or false to disable padding\n * completely (in order to handle e.g. EMSA-PSS encoding seperately before),\n * signaling whether the encryption operation is a public key operation\n * (i.e. encrypting data) or not, i.e. private key operation (data signing).\n *\n * For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x01\n * (for signing) or 0x02 (for encryption). The key operation mode (private\n * or public) is derived from this flag in that case).\n *\n * @param m the message to encrypt as a byte string.\n * @param key the RSA key to use.\n * @param bt for PKCS#1 v1.5 padding, the block type to use\n * (0x01 for private key, 0x02 for public),\n * to disable padding: true = public key, false = private key.\n *\n * @return the encrypted bytes as a string.\n */\npki.rsa.encrypt = function(m, key, bt) {\n var pub = bt;\n var eb;\n\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n if(bt !== false && bt !== true) {\n // legacy, default to PKCS#1 v1.5 padding\n pub = (bt === 0x02);\n eb = _encodePkcs1_v1_5(m, key, bt);\n } else {\n eb = forge.util.createBuffer();\n eb.putBytes(m);\n }\n\n // load encryption block as big integer 'x'\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var x = new BigInteger(eb.toHex(), 16);\n\n // do RSA encryption\n var y = _modPow(x, key, pub);\n\n // convert y into the encrypted data byte string, if y is shorter in\n // bytes than k, then prepend zero bytes to fill up ed\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var yhex = y.toString(16);\n var ed = forge.util.createBuffer();\n var zeros = k - Math.ceil(yhex.length / 2);\n while(zeros > 0) {\n ed.putByte(0x00);\n --zeros;\n }\n ed.putBytes(forge.util.hexToBytes(yhex));\n return ed.getBytes();\n};\n\n/**\n * NOTE: THIS METHOD IS DEPRECATED, use 'decrypt' on a private key object or\n * 'verify' on a public key object instead.\n *\n * Performs RSA decryption.\n *\n * The parameter ml controls whether to apply PKCS#1 v1.5 padding\n * or not. Set ml = false to disable padding removal completely\n * (in order to handle e.g. EMSA-PSS later on) and simply pass back\n * the RSA encryption block.\n *\n * @param ed the encrypted data to decrypt in as a byte string.\n * @param key the RSA key to use.\n * @param pub true for a public key operation, false for private.\n * @param ml the message length, if known, false to disable padding.\n *\n * @return the decrypted message as a byte string.\n */\npki.rsa.decrypt = function(ed, key, pub, ml) {\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n // error if the length of the encrypted data ED is not k\n if(ed.length !== k) {\n var error = new Error('Encrypted message length is invalid.');\n error.length = ed.length;\n error.expected = k;\n throw error;\n }\n\n // convert encrypted data into a big integer\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16);\n\n // y must be less than the modulus or it wasn't the result of\n // a previous mod operation (encryption) using that modulus\n if(y.compareTo(key.n) >= 0) {\n throw new Error('Encrypted message is invalid.');\n }\n\n // do RSA decryption\n var x = _modPow(y, key, pub);\n\n // create the encryption block, if x is shorter in bytes than k, then\n // prepend zero bytes to fill up eb\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var xhex = x.toString(16);\n var eb = forge.util.createBuffer();\n var zeros = k - Math.ceil(xhex.length / 2);\n while(zeros > 0) {\n eb.putByte(0x00);\n --zeros;\n }\n eb.putBytes(forge.util.hexToBytes(xhex));\n\n if(ml !== false) {\n // legacy, default to PKCS#1 v1.5 padding\n return _decodePkcs1_v1_5(eb.getBytes(), key, pub);\n }\n\n // return message\n return eb.getBytes();\n};\n\n/**\n * Creates an RSA key-pair generation state object. It is used to allow\n * key-generation to be performed in steps. It also allows for a UI to\n * display progress updates.\n *\n * @param bits the size for the private key in bits, defaults to 2048.\n * @param e the public exponent to use, defaults to 65537 (0x10001).\n * @param [options] the options to use.\n * prng a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\".\n * algorithm the algorithm to use (default: 'PRIMEINC').\n *\n * @return the state object to use to generate the key-pair.\n */\npki.rsa.createKeyPairGenerationState = function(bits, e, options) {\n // TODO: migrate step-based prime generation code to forge.prime\n\n // set default bits\n if(typeof(bits) === 'string') {\n bits = parseInt(bits, 10);\n }\n bits = bits || 2048;\n\n // create prng with api that matches BigInteger secure random\n options = options || {};\n var prng = options.prng || forge.random;\n var rng = {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n var b = prng.getBytesSync(x.length);\n for(var i = 0; i < x.length; ++i) {\n x[i] = b.charCodeAt(i);\n }\n }\n };\n\n var algorithm = options.algorithm || 'PRIMEINC';\n\n // create PRIMEINC algorithm state\n var rval;\n if(algorithm === 'PRIMEINC') {\n rval = {\n algorithm: algorithm,\n state: 0,\n bits: bits,\n rng: rng,\n eInt: e || 65537,\n e: new BigInteger(null),\n p: null,\n q: null,\n qBits: bits >> 1,\n pBits: bits - (bits >> 1),\n pqState: 0,\n num: null,\n keys: null\n };\n rval.e.fromInt(rval.eInt);\n } else {\n throw new Error('Invalid key generation algorithm: ' + algorithm);\n }\n\n return rval;\n};\n\n/**\n * Attempts to runs the key-generation algorithm for at most n seconds\n * (approximately) using the given state. When key-generation has completed,\n * the keys will be stored in state.keys.\n *\n * To use this function to update a UI while generating a key or to prevent\n * causing browser lockups/warnings, set \"n\" to a value other than 0. A\n * simple pattern for generating a key and showing a progress indicator is:\n *\n * var state = pki.rsa.createKeyPairGenerationState(2048);\n * var step = function() {\n * // step key-generation, run algorithm for 100 ms, repeat\n * if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) {\n * setTimeout(step, 1);\n * } else {\n * // key-generation complete\n * // TODO: turn off progress indicator here\n * // TODO: use the generated key-pair in \"state.keys\"\n * }\n * };\n * // TODO: turn on progress indicator here\n * setTimeout(step, 0);\n *\n * @param state the state to use.\n * @param n the maximum number of milliseconds to run the algorithm for, 0\n * to run the algorithm to completion.\n *\n * @return true if the key-generation completed, false if not.\n */\npki.rsa.stepKeyPairGenerationState = function(state, n) {\n // set default algorithm if not set\n if(!('algorithm' in state)) {\n state.algorithm = 'PRIMEINC';\n }\n\n // TODO: migrate step-based prime generation code to forge.prime\n // TODO: abstract as PRIMEINC algorithm\n\n // do key generation (based on Tom Wu's rsa.js, see jsbn.js license)\n // with some minor optimizations and designed to run in steps\n\n // local state vars\n var THIRTY = new BigInteger(null);\n THIRTY.fromInt(30);\n var deltaIdx = 0;\n var op_or = function(x, y) {return x | y;};\n\n // keep stepping until time limit is reached or done\n var t1 = +new Date();\n var t2;\n var total = 0;\n while(state.keys === null && (n <= 0 || total < n)) {\n // generate p or q\n if(state.state === 0) {\n /* Note: All primes are of the form:\n\n 30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i\n\n When we generate a random number, we always align it at 30k + 1. Each\n time the number is determined not to be prime we add to get to the\n next 'i', eg: if the number was at 30k + 1 we add 6. */\n var bits = (state.p === null) ? state.pBits : state.qBits;\n var bits1 = bits - 1;\n\n // get a random number\n if(state.pqState === 0) {\n state.num = new BigInteger(bits, state.rng);\n // force MSB set\n if(!state.num.testBit(bits1)) {\n state.num.bitwiseTo(\n BigInteger.ONE.shiftLeft(bits1), op_or, state.num);\n }\n // align number on 30k+1 boundary\n state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0);\n deltaIdx = 0;\n\n ++state.pqState;\n } else if(state.pqState === 1) {\n // try to make the number a prime\n if(state.num.bitLength() > bits) {\n // overflow, try again\n state.pqState = 0;\n // do primality test\n } else if(state.num.isProbablePrime(\n _getMillerRabinTests(state.num.bitLength()))) {\n ++state.pqState;\n } else {\n // get next potential prime\n state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);\n }\n } else if(state.pqState === 2) {\n // ensure number is coprime with e\n state.pqState =\n (state.num.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) === 0) ? 3 : 0;\n } else if(state.pqState === 3) {\n // store p or q\n state.pqState = 0;\n if(state.p === null) {\n state.p = state.num;\n } else {\n state.q = state.num;\n }\n\n // advance state if both p and q are ready\n if(state.p !== null && state.q !== null) {\n ++state.state;\n }\n state.num = null;\n }\n } else if(state.state === 1) {\n // ensure p is larger than q (swap them if not)\n if(state.p.compareTo(state.q) < 0) {\n state.num = state.p;\n state.p = state.q;\n state.q = state.num;\n }\n ++state.state;\n } else if(state.state === 2) {\n // compute phi: (p - 1)(q - 1) (Euler's totient function)\n state.p1 = state.p.subtract(BigInteger.ONE);\n state.q1 = state.q.subtract(BigInteger.ONE);\n state.phi = state.p1.multiply(state.q1);\n ++state.state;\n } else if(state.state === 3) {\n // ensure e and phi are coprime\n if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) {\n // phi and e are coprime, advance\n ++state.state;\n } else {\n // phi and e aren't coprime, so generate a new p and q\n state.p = null;\n state.q = null;\n state.state = 0;\n }\n } else if(state.state === 4) {\n // create n, ensure n is has the right number of bits\n state.n = state.p.multiply(state.q);\n\n // ensure n is right number of bits\n if(state.n.bitLength() === state.bits) {\n // success, advance\n ++state.state;\n } else {\n // failed, get new q\n state.q = null;\n state.state = 0;\n }\n } else if(state.state === 5) {\n // set keys\n var d = state.e.modInverse(state.phi);\n state.keys = {\n privateKey: pki.rsa.setPrivateKey(\n state.n, state.e, d, state.p, state.q,\n d.mod(state.p1), d.mod(state.q1),\n state.q.modInverse(state.p)),\n publicKey: pki.rsa.setPublicKey(state.n, state.e)\n };\n }\n\n // update timing\n t2 = +new Date();\n total += t2 - t1;\n t1 = t2;\n }\n\n return state.keys !== null;\n};\n\n/**\n * Generates an RSA public-private key pair in a single call.\n *\n * To generate a key-pair in steps (to allow for progress updates and to\n * prevent blocking or warnings in slow browsers) then use the key-pair\n * generation state functions.\n *\n * To generate a key-pair asynchronously (either through web-workers, if\n * available, or by breaking up the work on the main thread), pass a\n * callback function.\n *\n * @param [bits] the size for the private key in bits, defaults to 2048.\n * @param [e] the public exponent to use, defaults to 65537.\n * @param [options] options for key-pair generation, if given then 'bits'\n * and 'e' must *not* be given:\n * bits the size for the private key in bits, (default: 2048).\n * e the public exponent to use, (default: 65537 (0x10001)).\n * workerScript the worker script URL.\n * workers the number of web workers (if supported) to use,\n * (default: 2).\n * workLoad the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * prng a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\". Disables use of native APIs.\n * algorithm the algorithm to use (default: 'PRIMEINC').\n * @param [callback(err, keypair)] called once the operation completes.\n *\n * @return an object with privateKey and publicKey properties.\n */\npki.rsa.generateKeyPair = function(bits, e, options, callback) {\n // (bits), (options), (callback)\n if(arguments.length === 1) {\n if(typeof bits === 'object') {\n options = bits;\n bits = undefined;\n } else if(typeof bits === 'function') {\n callback = bits;\n bits = undefined;\n }\n } else if(arguments.length === 2) {\n // (bits, e), (bits, options), (bits, callback), (options, callback)\n if(typeof bits === 'number') {\n if(typeof e === 'function') {\n callback = e;\n e = undefined;\n } else if(typeof e !== 'number') {\n options = e;\n e = undefined;\n }\n } else {\n options = bits;\n callback = e;\n bits = undefined;\n e = undefined;\n }\n } else if(arguments.length === 3) {\n // (bits, e, options), (bits, e, callback), (bits, options, callback)\n if(typeof e === 'number') {\n if(typeof options === 'function') {\n callback = options;\n options = undefined;\n }\n } else {\n callback = options;\n options = e;\n e = undefined;\n }\n }\n options = options || {};\n if(bits === undefined) {\n bits = options.bits || 2048;\n }\n if(e === undefined) {\n e = options.e || 0x10001;\n }\n\n // use native code if permitted, available, and parameters are acceptable\n if(!forge.options.usePureJavaScript && !options.prng &&\n bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) {\n if(callback) {\n // try native async\n if(_detectNodeCrypto('generateKeyPair')) {\n return _crypto.generateKeyPair('rsa', {\n modulusLength: bits,\n publicExponent: e,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem'\n }\n }, function(err, pub, priv) {\n if(err) {\n return callback(err);\n }\n callback(null, {\n privateKey: pki.privateKeyFromPem(priv),\n publicKey: pki.publicKeyFromPem(pub)\n });\n });\n }\n if(_detectSubtleCrypto('generateKey') &&\n _detectSubtleCrypto('exportKey')) {\n // use standard native generateKey\n return util.globalScope.crypto.subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: _intToUint8Array(e),\n hash: {name: 'SHA-256'}\n }, true /* key can be exported*/, ['sign', 'verify'])\n .then(function(pair) {\n return util.globalScope.crypto.subtle.exportKey(\n 'pkcs8', pair.privateKey);\n // avoiding catch(function(err) {...}) to support IE <= 8\n }).then(undefined, function(err) {\n callback(err);\n }).then(function(pkcs8) {\n if(pkcs8) {\n var privateKey = pki.privateKeyFromAsn1(\n asn1.fromDer(forge.util.createBuffer(pkcs8)));\n callback(null, {\n privateKey: privateKey,\n publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)\n });\n }\n });\n }\n if(_detectSubtleMsCrypto('generateKey') &&\n _detectSubtleMsCrypto('exportKey')) {\n var genOp = util.globalScope.msCrypto.subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: _intToUint8Array(e),\n hash: {name: 'SHA-256'}\n }, true /* key can be exported*/, ['sign', 'verify']);\n genOp.oncomplete = function(e) {\n var pair = e.target.result;\n var exportOp = util.globalScope.msCrypto.subtle.exportKey(\n 'pkcs8', pair.privateKey);\n exportOp.oncomplete = function(e) {\n var pkcs8 = e.target.result;\n var privateKey = pki.privateKeyFromAsn1(\n asn1.fromDer(forge.util.createBuffer(pkcs8)));\n callback(null, {\n privateKey: privateKey,\n publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)\n });\n };\n exportOp.onerror = function(err) {\n callback(err);\n };\n };\n genOp.onerror = function(err) {\n callback(err);\n };\n return;\n }\n } else {\n // try native sync\n if(_detectNodeCrypto('generateKeyPairSync')) {\n var keypair = _crypto.generateKeyPairSync('rsa', {\n modulusLength: bits,\n publicExponent: e,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem'\n }\n });\n return {\n privateKey: pki.privateKeyFromPem(keypair.privateKey),\n publicKey: pki.publicKeyFromPem(keypair.publicKey)\n };\n }\n }\n }\n\n // use JavaScript implementation\n var state = pki.rsa.createKeyPairGenerationState(bits, e, options);\n if(!callback) {\n pki.rsa.stepKeyPairGenerationState(state, 0);\n return state.keys;\n }\n _generateKeyPair(state, options, callback);\n};\n\n/**\n * Sets an RSA public key from BigIntegers modulus and exponent.\n *\n * @param n the modulus.\n * @param e the exponent.\n *\n * @return the public key.\n */\npki.setRsaPublicKey = pki.rsa.setPublicKey = function(n, e) {\n var key = {\n n: n,\n e: e\n };\n\n /**\n * Encrypts the given data with this public key. Newer applications\n * should use the 'RSA-OAEP' decryption scheme, 'RSAES-PKCS1-V1_5' is for\n * legacy applications.\n *\n * @param data the byte string to encrypt.\n * @param scheme the encryption scheme to use:\n * 'RSAES-PKCS1-V1_5' (default),\n * 'RSA-OAEP',\n * 'RAW', 'NONE', or null to perform raw RSA encryption,\n * an object with an 'encode' property set to a function\n * with the signature 'function(data, key)' that returns\n * a binary-encoded string representing the encoded data.\n * @param schemeOptions any scheme-specific options.\n *\n * @return the encrypted byte string.\n */\n key.encrypt = function(data, scheme, schemeOptions) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSAES-PKCS1-V1_5';\n }\n\n if(scheme === 'RSAES-PKCS1-V1_5') {\n scheme = {\n encode: function(m, key, pub) {\n return _encodePkcs1_v1_5(m, key, 0x02).getBytes();\n }\n };\n } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {\n scheme = {\n encode: function(m, key) {\n return forge.pkcs1.encode_rsa_oaep(key, m, schemeOptions);\n }\n };\n } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {\n scheme = {encode: function(e) {return e;}};\n } else if(typeof scheme === 'string') {\n throw new Error('Unsupported encryption scheme: \"' + scheme + '\".');\n }\n\n // do scheme-based encoding then rsa encryption\n var e = scheme.encode(data, key, true);\n return pki.rsa.encrypt(e, key, true);\n };\n\n /**\n * Verifies the given signature against the given digest.\n *\n * PKCS#1 supports multiple (currently two) signature schemes:\n * RSASSA-PKCS1-V1_5 and RSASSA-PSS.\n *\n * By default this implementation uses the \"old scheme\", i.e.\n * RSASSA-PKCS1-V1_5, in which case once RSA-decrypted, the\n * signature is an OCTET STRING that holds a DigestInfo.\n *\n * DigestInfo ::= SEQUENCE {\n * digestAlgorithm DigestAlgorithmIdentifier,\n * digest Digest\n * }\n * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n * Digest ::= OCTET STRING\n *\n * To perform PSS signature verification, provide an instance\n * of Forge PSS object as the scheme parameter.\n *\n * @param digest the message digest hash to compare against the signature,\n * as a binary-encoded string.\n * @param signature the signature to verify, as a binary-encoded string.\n * @param scheme signature verification scheme to use:\n * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,\n * a Forge PSS object for RSASSA-PSS,\n * 'NONE' or null for none, DigestInfo will not be expected, but\n * PKCS#1 v1.5 padding will still be used.\n * @param options optional verify options\n * _parseAllDigestBytes testing flag to control parsing of all\n * digest bytes. Unsupported and not for general usage.\n * (default: true)\n *\n * @return true if the signature was verified, false if not.\n */\n key.verify = function(digest, signature, scheme, options) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSASSA-PKCS1-V1_5';\n }\n if(options === undefined) {\n options = {\n _parseAllDigestBytes: true\n };\n }\n if(!('_parseAllDigestBytes' in options)) {\n options._parseAllDigestBytes = true;\n }\n\n if(scheme === 'RSASSA-PKCS1-V1_5') {\n scheme = {\n verify: function(digest, d) {\n // remove padding\n d = _decodePkcs1_v1_5(d, key, true);\n // d is ASN.1 BER-encoded DigestInfo\n var obj = asn1.fromDer(d, {\n parseAllBytes: options._parseAllDigestBytes\n });\n\n // validate DigestInfo\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, digestInfoValidator, capture, errors)) {\n var error = new Error(\n 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' +\n 'DigestInfo value.');\n error.errors = errors;\n throw error;\n }\n // check hash algorithm identifier\n // see PKCS1-v1-5DigestAlgorithms in RFC 8017\n // FIXME: add support to vaidator for strict value choices\n var oid = asn1.derToOid(capture.algorithmIdentifier);\n if(!(oid === forge.oids.md2 ||\n oid === forge.oids.md5 ||\n oid === forge.oids.sha1 ||\n oid === forge.oids.sha224 ||\n oid === forge.oids.sha256 ||\n oid === forge.oids.sha384 ||\n oid === forge.oids.sha512 ||\n oid === forge.oids['sha512-224'] ||\n oid === forge.oids['sha512-256'])) {\n var error = new Error(\n 'Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.');\n error.oid = oid;\n throw error;\n }\n\n // special check for md2 and md5 that NULL parameters exist\n if(oid === forge.oids.md2 || oid === forge.oids.md5) {\n if(!('parameters' in capture)) {\n throw new Error(\n 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' +\n 'DigestInfo value. ' +\n 'Missing algorithm identifer NULL parameters.');\n }\n }\n\n // compare the given digest to the decrypted one\n return digest === capture.digest;\n }\n };\n } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {\n scheme = {\n verify: function(digest, d) {\n // remove padding\n d = _decodePkcs1_v1_5(d, key, true);\n return digest === d;\n }\n };\n }\n\n // do rsa decryption w/o any decoding, then verify -- which does decoding\n var d = pki.rsa.decrypt(signature, key, true, false);\n return scheme.verify(digest, d, key.n.bitLength());\n };\n\n return key;\n};\n\n/**\n * Sets an RSA private key from BigIntegers modulus, exponent, primes,\n * prime exponents, and modular multiplicative inverse.\n *\n * @param n the modulus.\n * @param e the public exponent.\n * @param d the private exponent ((inverse of e) mod n).\n * @param p the first prime.\n * @param q the second prime.\n * @param dP exponent1 (d mod (p-1)).\n * @param dQ exponent2 (d mod (q-1)).\n * @param qInv ((inverse of q) mod p)\n *\n * @return the private key.\n */\npki.setRsaPrivateKey = pki.rsa.setPrivateKey = function(\n n, e, d, p, q, dP, dQ, qInv) {\n var key = {\n n: n,\n e: e,\n d: d,\n p: p,\n q: q,\n dP: dP,\n dQ: dQ,\n qInv: qInv\n };\n\n /**\n * Decrypts the given data with this private key. The decryption scheme\n * must match the one used to encrypt the data.\n *\n * @param data the byte string to decrypt.\n * @param scheme the decryption scheme to use:\n * 'RSAES-PKCS1-V1_5' (default),\n * 'RSA-OAEP',\n * 'RAW', 'NONE', or null to perform raw RSA decryption.\n * @param schemeOptions any scheme-specific options.\n *\n * @return the decrypted byte string.\n */\n key.decrypt = function(data, scheme, schemeOptions) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSAES-PKCS1-V1_5';\n }\n\n // do rsa decryption w/o any decoding\n var d = pki.rsa.decrypt(data, key, false, false);\n\n if(scheme === 'RSAES-PKCS1-V1_5') {\n scheme = {decode: _decodePkcs1_v1_5};\n } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {\n scheme = {\n decode: function(d, key) {\n return forge.pkcs1.decode_rsa_oaep(key, d, schemeOptions);\n }\n };\n } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {\n scheme = {decode: function(d) {return d;}};\n } else {\n throw new Error('Unsupported encryption scheme: \"' + scheme + '\".');\n }\n\n // decode according to scheme\n return scheme.decode(d, key, false);\n };\n\n /**\n * Signs the given digest, producing a signature.\n *\n * PKCS#1 supports multiple (currently two) signature schemes:\n * RSASSA-PKCS1-V1_5 and RSASSA-PSS.\n *\n * By default this implementation uses the \"old scheme\", i.e.\n * RSASSA-PKCS1-V1_5. In order to generate a PSS signature, provide\n * an instance of Forge PSS object as the scheme parameter.\n *\n * @param md the message digest object with the hash to sign.\n * @param scheme the signature scheme to use:\n * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,\n * a Forge PSS object for RSASSA-PSS,\n * 'NONE' or null for none, DigestInfo will not be used but\n * PKCS#1 v1.5 padding will still be used.\n *\n * @return the signature as a byte string.\n */\n key.sign = function(md, scheme) {\n /* Note: The internal implementation of RSA operations is being\n transitioned away from a PKCS#1 v1.5 hard-coded scheme. Some legacy\n code like the use of an encoding block identifier 'bt' will eventually\n be removed. */\n\n // private key operation\n var bt = false;\n\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n }\n\n if(scheme === undefined || scheme === 'RSASSA-PKCS1-V1_5') {\n scheme = {encode: emsaPkcs1v15encode};\n bt = 0x01;\n } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {\n scheme = {encode: function() {return md;}};\n bt = 0x01;\n }\n\n // encode and then encrypt\n var d = scheme.encode(md, key.n.bitLength());\n return pki.rsa.encrypt(d, key, bt);\n };\n\n return key;\n};\n\n/**\n * Wraps an RSAPrivateKey ASN.1 object in an ASN.1 PrivateKeyInfo object.\n *\n * @param rsaKey the ASN.1 RSAPrivateKey.\n *\n * @return the ASN.1 PrivateKeyInfo.\n */\npki.wrapRsaPrivateKey = function(rsaKey) {\n // PrivateKeyInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version (0)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(0).getBytes()),\n // privateKeyAlgorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // PrivateKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(rsaKey).getBytes())\n ]);\n};\n\n/**\n * Converts a private key from an ASN.1 object.\n *\n * @param obj the ASN.1 representation of a PrivateKeyInfo containing an\n * RSAPrivateKey or an RSAPrivateKey.\n *\n * @return the private key.\n */\npki.privateKeyFromAsn1 = function(obj) {\n // get PrivateKeyInfo\n var capture = {};\n var errors = [];\n if(asn1.validate(obj, privateKeyValidator, capture, errors)) {\n obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey));\n }\n\n // get RSAPrivateKey\n capture = {};\n errors = [];\n if(!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) {\n var error = new Error('Cannot read private key. ' +\n 'ASN.1 object does not contain an RSAPrivateKey.');\n error.errors = errors;\n throw error;\n }\n\n // Note: Version is currently ignored.\n // capture.privateKeyVersion\n // FIXME: inefficient, get a BigInteger that uses byte strings\n var n, e, d, p, q, dP, dQ, qInv;\n n = forge.util.createBuffer(capture.privateKeyModulus).toHex();\n e = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex();\n d = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex();\n p = forge.util.createBuffer(capture.privateKeyPrime1).toHex();\n q = forge.util.createBuffer(capture.privateKeyPrime2).toHex();\n dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex();\n dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex();\n qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex();\n\n // set private key\n return pki.setRsaPrivateKey(\n new BigInteger(n, 16),\n new BigInteger(e, 16),\n new BigInteger(d, 16),\n new BigInteger(p, 16),\n new BigInteger(q, 16),\n new BigInteger(dP, 16),\n new BigInteger(dQ, 16),\n new BigInteger(qInv, 16));\n};\n\n/**\n * Converts a private key to an ASN.1 RSAPrivateKey.\n *\n * @param key the private key.\n *\n * @return the ASN.1 representation of an RSAPrivateKey.\n */\npki.privateKeyToAsn1 = pki.privateKeyToRSAPrivateKey = function(key) {\n // RSAPrivateKey\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version (0 = only 2 primes, 1 multiple primes)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(0).getBytes()),\n // modulus (n)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.n)),\n // publicExponent (e)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.e)),\n // privateExponent (d)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.d)),\n // privateKeyPrime1 (p)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.p)),\n // privateKeyPrime2 (q)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.q)),\n // privateKeyExponent1 (dP)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.dP)),\n // privateKeyExponent2 (dQ)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.dQ)),\n // coefficient (qInv)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.qInv))\n ]);\n};\n\n/**\n * Converts a public key from an ASN.1 SubjectPublicKeyInfo or RSAPublicKey.\n *\n * @param obj the asn1 representation of a SubjectPublicKeyInfo or RSAPublicKey.\n *\n * @return the public key.\n */\npki.publicKeyFromAsn1 = function(obj) {\n // get SubjectPublicKeyInfo\n var capture = {};\n var errors = [];\n if(asn1.validate(obj, publicKeyValidator, capture, errors)) {\n // get oid\n var oid = asn1.derToOid(capture.publicKeyOid);\n if(oid !== pki.oids.rsaEncryption) {\n var error = new Error('Cannot read public key. Unknown OID.');\n error.oid = oid;\n throw error;\n }\n obj = capture.rsaPublicKey;\n }\n\n // get RSA params\n errors = [];\n if(!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) {\n var error = new Error('Cannot read public key. ' +\n 'ASN.1 object does not contain an RSAPublicKey.');\n error.errors = errors;\n throw error;\n }\n\n // FIXME: inefficient, get a BigInteger that uses byte strings\n var n = forge.util.createBuffer(capture.publicKeyModulus).toHex();\n var e = forge.util.createBuffer(capture.publicKeyExponent).toHex();\n\n // set public key\n return pki.setRsaPublicKey(\n new BigInteger(n, 16),\n new BigInteger(e, 16));\n};\n\n/**\n * Converts a public key to an ASN.1 SubjectPublicKeyInfo.\n *\n * @param key the public key.\n *\n * @return the asn1 representation of a SubjectPublicKeyInfo.\n */\npki.publicKeyToAsn1 = pki.publicKeyToSubjectPublicKeyInfo = function(key) {\n // SubjectPublicKeyInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // subjectPublicKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [\n pki.publicKeyToRSAPublicKey(key)\n ])\n ]);\n};\n\n/**\n * Converts a public key to an ASN.1 RSAPublicKey.\n *\n * @param key the public key.\n *\n * @return the asn1 representation of a RSAPublicKey.\n */\npki.publicKeyToRSAPublicKey = function(key) {\n // RSAPublicKey\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // modulus (n)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.n)),\n // publicExponent (e)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.e))\n ]);\n};\n\n/**\n * Encodes a message using PKCS#1 v1.5 padding.\n *\n * @param m the message to encode.\n * @param key the RSA key to use.\n * @param bt the block type to use, i.e. either 0x01 (for signing) or 0x02\n * (for encryption).\n *\n * @return the padded byte buffer.\n */\nfunction _encodePkcs1_v1_5(m, key, bt) {\n var eb = forge.util.createBuffer();\n\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n /* use PKCS#1 v1.5 padding */\n if(m.length > (k - 11)) {\n var error = new Error('Message is too long for PKCS#1 v1.5 padding.');\n error.length = m.length;\n error.max = k - 11;\n throw error;\n }\n\n /* A block type BT, a padding string PS, and the data D shall be\n formatted into an octet string EB, the encryption block:\n\n EB = 00 || BT || PS || 00 || D\n\n The block type BT shall be a single octet indicating the structure of\n the encryption block. For this version of the document it shall have\n value 00, 01, or 02. For a private-key operation, the block type\n shall be 00 or 01. For a public-key operation, it shall be 02.\n\n The padding string PS shall consist of k-3-||D|| octets. For block\n type 00, the octets shall have value 00; for block type 01, they\n shall have value FF; and for block type 02, they shall be\n pseudorandomly generated and nonzero. This makes the length of the\n encryption block EB equal to k. */\n\n // build the encryption block\n eb.putByte(0x00);\n eb.putByte(bt);\n\n // create the padding\n var padNum = k - 3 - m.length;\n var padByte;\n // private key op\n if(bt === 0x00 || bt === 0x01) {\n padByte = (bt === 0x00) ? 0x00 : 0xFF;\n for(var i = 0; i < padNum; ++i) {\n eb.putByte(padByte);\n }\n } else {\n // public key op\n // pad with random non-zero values\n while(padNum > 0) {\n var numZeros = 0;\n var padBytes = forge.random.getBytes(padNum);\n for(var i = 0; i < padNum; ++i) {\n padByte = padBytes.charCodeAt(i);\n if(padByte === 0) {\n ++numZeros;\n } else {\n eb.putByte(padByte);\n }\n }\n padNum = numZeros;\n }\n }\n\n // zero followed by message\n eb.putByte(0x00);\n eb.putBytes(m);\n\n return eb;\n}\n\n/**\n * Decodes a message using PKCS#1 v1.5 padding.\n *\n * @param em the message to decode.\n * @param key the RSA key to use.\n * @param pub true if the key is a public key, false if it is private.\n * @param ml the message length, if specified.\n *\n * @return the decoded bytes.\n */\nfunction _decodePkcs1_v1_5(em, key, pub, ml) {\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n /* It is an error if any of the following conditions occurs:\n\n 1. The encryption block EB cannot be parsed unambiguously.\n 2. The padding string PS consists of fewer than eight octets\n or is inconsisent with the block type BT.\n 3. The decryption process is a public-key operation and the block\n type BT is not 00 or 01, or the decryption process is a\n private-key operation and the block type is not 02.\n */\n\n // parse the encryption block\n var eb = forge.util.createBuffer(em);\n var first = eb.getByte();\n var bt = eb.getByte();\n if(first !== 0x00 ||\n (pub && bt !== 0x00 && bt !== 0x01) ||\n (!pub && bt != 0x02) ||\n (pub && bt === 0x00 && typeof(ml) === 'undefined')) {\n throw new Error('Encryption block is invalid.');\n }\n\n var padNum = 0;\n if(bt === 0x00) {\n // check all padding bytes for 0x00\n padNum = k - 3 - ml;\n for(var i = 0; i < padNum; ++i) {\n if(eb.getByte() !== 0x00) {\n throw new Error('Encryption block is invalid.');\n }\n }\n } else if(bt === 0x01) {\n // find the first byte that isn't 0xFF, should be after all padding\n padNum = 0;\n while(eb.length() > 1) {\n if(eb.getByte() !== 0xFF) {\n --eb.read;\n break;\n }\n ++padNum;\n }\n } else if(bt === 0x02) {\n // look for 0x00 byte\n padNum = 0;\n while(eb.length() > 1) {\n if(eb.getByte() === 0x00) {\n --eb.read;\n break;\n }\n ++padNum;\n }\n }\n\n // zero must be 0x00 and padNum must be (k - 3 - message length)\n var zero = eb.getByte();\n if(zero !== 0x00 || padNum !== (k - 3 - eb.length())) {\n throw new Error('Encryption block is invalid.');\n }\n\n return eb.getBytes();\n}\n\n/**\n * Runs the key-generation algorithm asynchronously, either in the background\n * via Web Workers, or using the main thread and setImmediate.\n *\n * @param state the key-pair generation state.\n * @param [options] options for key-pair generation:\n * workerScript the worker script URL.\n * workers the number of web workers (if supported) to use,\n * (default: 2, -1 to use estimated cores minus one).\n * workLoad the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * @param callback(err, keypair) called once the operation completes.\n */\nfunction _generateKeyPair(state, options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n var opts = {\n algorithm: {\n name: options.algorithm || 'PRIMEINC',\n options: {\n workers: options.workers || 2,\n workLoad: options.workLoad || 100,\n workerScript: options.workerScript\n }\n }\n };\n if('prng' in options) {\n opts.prng = options.prng;\n }\n\n generate();\n\n function generate() {\n // find p and then q (done in series to simplify)\n getPrime(state.pBits, function(err, num) {\n if(err) {\n return callback(err);\n }\n state.p = num;\n if(state.q !== null) {\n return finish(err, state.q);\n }\n getPrime(state.qBits, finish);\n });\n }\n\n function getPrime(bits, callback) {\n forge.prime.generateProbablePrime(bits, opts, callback);\n }\n\n function finish(err, num) {\n if(err) {\n return callback(err);\n }\n\n // set q\n state.q = num;\n\n // ensure p is larger than q (swap them if not)\n if(state.p.compareTo(state.q) < 0) {\n var tmp = state.p;\n state.p = state.q;\n state.q = tmp;\n }\n\n // ensure p is coprime with e\n if(state.p.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) !== 0) {\n state.p = null;\n generate();\n return;\n }\n\n // ensure q is coprime with e\n if(state.q.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) !== 0) {\n state.q = null;\n getPrime(state.qBits, finish);\n return;\n }\n\n // compute phi: (p - 1)(q - 1) (Euler's totient function)\n state.p1 = state.p.subtract(BigInteger.ONE);\n state.q1 = state.q.subtract(BigInteger.ONE);\n state.phi = state.p1.multiply(state.q1);\n\n // ensure e and phi are coprime\n if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) {\n // phi and e aren't coprime, so generate a new p and q\n state.p = state.q = null;\n generate();\n return;\n }\n\n // create n, ensure n is has the right number of bits\n state.n = state.p.multiply(state.q);\n if(state.n.bitLength() !== state.bits) {\n // failed, get new q\n state.q = null;\n getPrime(state.qBits, finish);\n return;\n }\n\n // set keys\n var d = state.e.modInverse(state.phi);\n state.keys = {\n privateKey: pki.rsa.setPrivateKey(\n state.n, state.e, d, state.p, state.q,\n d.mod(state.p1), d.mod(state.q1),\n state.q.modInverse(state.p)),\n publicKey: pki.rsa.setPublicKey(state.n, state.e)\n };\n\n callback(null, state.keys);\n }\n}\n\n/**\n * Converts a positive BigInteger into 2's-complement big-endian bytes.\n *\n * @param b the big integer to convert.\n *\n * @return the bytes.\n */\nfunction _bnToBytes(b) {\n // prepend 0x00 if first byte >= 0x80\n var hex = b.toString(16);\n if(hex[0] >= '8') {\n hex = '00' + hex;\n }\n var bytes = forge.util.hexToBytes(hex);\n\n // ensure integer is minimally-encoded\n if(bytes.length > 1 &&\n // leading 0x00 for positive integer\n ((bytes.charCodeAt(0) === 0 &&\n (bytes.charCodeAt(1) & 0x80) === 0) ||\n // leading 0xFF for negative integer\n (bytes.charCodeAt(0) === 0xFF &&\n (bytes.charCodeAt(1) & 0x80) === 0x80))) {\n return bytes.substr(1);\n }\n return bytes;\n}\n\n/**\n * Returns the required number of Miller-Rabin tests to generate a\n * prime with an error probability of (1/2)^80.\n *\n * See Handbook of Applied Cryptography Chapter 4, Table 4.4.\n *\n * @param bits the bit size.\n *\n * @return the required number of iterations.\n */\nfunction _getMillerRabinTests(bits) {\n if(bits <= 100) return 27;\n if(bits <= 150) return 18;\n if(bits <= 200) return 15;\n if(bits <= 250) return 12;\n if(bits <= 300) return 9;\n if(bits <= 350) return 8;\n if(bits <= 400) return 7;\n if(bits <= 500) return 6;\n if(bits <= 600) return 5;\n if(bits <= 800) return 4;\n if(bits <= 1250) return 3;\n return 2;\n}\n\n/**\n * Performs feature detection on the Node crypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectNodeCrypto(fn) {\n return forge.util.isNodejs && typeof _crypto[fn] === 'function';\n}\n\n/**\n * Performs feature detection on the SubtleCrypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectSubtleCrypto(fn) {\n return (typeof util.globalScope !== 'undefined' &&\n typeof util.globalScope.crypto === 'object' &&\n typeof util.globalScope.crypto.subtle === 'object' &&\n typeof util.globalScope.crypto.subtle[fn] === 'function');\n}\n\n/**\n * Performs feature detection on the deprecated Microsoft Internet Explorer\n * outdated SubtleCrypto interface. This function should only be used after\n * checking for the modern, standard SubtleCrypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectSubtleMsCrypto(fn) {\n return (typeof util.globalScope !== 'undefined' &&\n typeof util.globalScope.msCrypto === 'object' &&\n typeof util.globalScope.msCrypto.subtle === 'object' &&\n typeof util.globalScope.msCrypto.subtle[fn] === 'function');\n}\n\nfunction _intToUint8Array(x) {\n var bytes = forge.util.hexToBytes(x.toString(16));\n var buffer = new Uint8Array(bytes.length);\n for(var i = 0; i < bytes.length; ++i) {\n buffer[i] = bytes.charCodeAt(i);\n }\n return buffer;\n}\n\nfunction _privateKeyFromJwk(jwk) {\n if(jwk.kty !== 'RSA') {\n throw new Error(\n 'Unsupported key algorithm \"' + jwk.kty + '\"; algorithm must be \"RSA\".');\n }\n return pki.setRsaPrivateKey(\n _base64ToBigInt(jwk.n),\n _base64ToBigInt(jwk.e),\n _base64ToBigInt(jwk.d),\n _base64ToBigInt(jwk.p),\n _base64ToBigInt(jwk.q),\n _base64ToBigInt(jwk.dp),\n _base64ToBigInt(jwk.dq),\n _base64ToBigInt(jwk.qi));\n}\n\nfunction _publicKeyFromJwk(jwk) {\n if(jwk.kty !== 'RSA') {\n throw new Error('Key algorithm must be \"RSA\".');\n }\n return pki.setRsaPublicKey(\n _base64ToBigInt(jwk.n),\n _base64ToBigInt(jwk.e));\n}\n\nfunction _base64ToBigInt(b64) {\n return new BigInteger(forge.util.bytesToHex(forge.util.decode64(b64)), 16);\n}\n","/**\n * Password-based encryption functions.\n *\n * @author Dave Longley\n * @author Stefan Siegl <stesie@brokenpipe.de>\n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>\n *\n * An EncryptedPrivateKeyInfo:\n *\n * EncryptedPrivateKeyInfo ::= SEQUENCE {\n * encryptionAlgorithm EncryptionAlgorithmIdentifier,\n * encryptedData EncryptedData }\n *\n * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * EncryptedData ::= OCTET STRING\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./asn1');\nrequire('./des');\nrequire('./md');\nrequire('./oids');\nrequire('./pbkdf2');\nrequire('./pem');\nrequire('./random');\nrequire('./rc2');\nrequire('./rsa');\nrequire('./util');\n\nif(typeof BigInteger === 'undefined') {\n var BigInteger = forge.jsbn.BigInteger;\n}\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n/* Password-based encryption implementation. */\nvar pki = forge.pki = forge.pki || {};\nmodule.exports = pki.pbe = forge.pbe = forge.pbe || {};\nvar oids = pki.oids;\n\n// validator for an EncryptedPrivateKeyInfo structure\n// Note: Currently only works w/algorithm params\nvar encryptedPrivateKeyValidator = {\n name: 'EncryptedPrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedPrivateKeyInfo.encryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encryptionOid'\n }, {\n name: 'AlgorithmIdentifier.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'encryptionParams'\n }]\n }, {\n // encryptedData\n name: 'EncryptedPrivateKeyInfo.encryptedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encryptedData'\n }]\n};\n\n// validator for a PBES2Algorithms structure\n// Note: Currently only works w/PBKDF2 + AES encryption schemes\nvar PBES2AlgorithmsValidator = {\n name: 'PBES2Algorithms',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.keyDerivationFunc',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.keyDerivationFunc.oid',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'kdfOid'\n }, {\n name: 'PBES2Algorithms.params',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.params.salt',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'kdfSalt'\n }, {\n name: 'PBES2Algorithms.params.iterationCount',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'kdfIterationCount'\n }, {\n name: 'PBES2Algorithms.params.keyLength',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n optional: true,\n capture: 'keyLength'\n }, {\n // prf\n name: 'PBES2Algorithms.params.prf',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n value: [{\n name: 'PBES2Algorithms.params.prf.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'prfOid'\n }]\n }]\n }]\n }, {\n name: 'PBES2Algorithms.encryptionScheme',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.encryptionScheme.oid',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encOid'\n }, {\n name: 'PBES2Algorithms.encryptionScheme.iv',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encIv'\n }]\n }]\n};\n\nvar pkcs12PbeParamsValidator = {\n name: 'pkcs-12PbeParams',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'pkcs-12PbeParams.salt',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'salt'\n }, {\n name: 'pkcs-12PbeParams.iterations',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'iterations'\n }]\n};\n\n/**\n * Encrypts a ASN.1 PrivateKeyInfo object, producing an EncryptedPrivateKeyInfo.\n *\n * PBES2Algorithms ALGORITHM-IDENTIFIER ::=\n * { {PBES2-params IDENTIFIED BY id-PBES2}, ...}\n *\n * id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13}\n *\n * PBES2-params ::= SEQUENCE {\n * keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},\n * encryptionScheme AlgorithmIdentifier {{PBES2-Encs}}\n * }\n *\n * PBES2-KDFs ALGORITHM-IDENTIFIER ::=\n * { {PBKDF2-params IDENTIFIED BY id-PBKDF2}, ... }\n *\n * PBES2-Encs ALGORITHM-IDENTIFIER ::= { ... }\n *\n * PBKDF2-params ::= SEQUENCE {\n * salt CHOICE {\n * specified OCTET STRING,\n * otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}}\n * },\n * iterationCount INTEGER (1..MAX),\n * keyLength INTEGER (1..MAX) OPTIONAL,\n * prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1\n * }\n *\n * @param obj the ASN.1 PrivateKeyInfo object.\n * @param password the password to encrypt with.\n * @param options:\n * algorithm the encryption algorithm to use\n * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'.\n * count the iteration count to use.\n * saltSize the salt size to use.\n * prfAlgorithm the PRF message digest algorithm to use\n * ('sha1', 'sha224', 'sha256', 'sha384', 'sha512')\n *\n * @return the ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptPrivateKeyInfo = function(obj, password, options) {\n // set default options\n options = options || {};\n options.saltSize = options.saltSize || 8;\n options.count = options.count || 2048;\n options.algorithm = options.algorithm || 'aes128';\n options.prfAlgorithm = options.prfAlgorithm || 'sha1';\n\n // generate PBE params\n var salt = forge.random.getBytesSync(options.saltSize);\n var count = options.count;\n var countBytes = asn1.integerToDer(count);\n var dkLen;\n var encryptionAlgorithm;\n var encryptedData;\n if(options.algorithm.indexOf('aes') === 0 || options.algorithm === 'des') {\n // do PBES2\n var ivLen, encOid, cipherFn;\n switch(options.algorithm) {\n case 'aes128':\n dkLen = 16;\n ivLen = 16;\n encOid = oids['aes128-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes192':\n dkLen = 24;\n ivLen = 16;\n encOid = oids['aes192-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes256':\n dkLen = 32;\n ivLen = 16;\n encOid = oids['aes256-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'des':\n dkLen = 8;\n ivLen = 8;\n encOid = oids['desCBC'];\n cipherFn = forge.des.createEncryptionCipher;\n break;\n default:\n var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // get PRF message digest\n var prfAlgorithm = 'hmacWith' + options.prfAlgorithm.toUpperCase();\n var md = prfAlgorithmToMessageDigest(prfAlgorithm);\n\n // encrypt private key using pbe SHA-1 and AES/DES\n var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md);\n var iv = forge.random.getBytesSync(ivLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(obj));\n cipher.finish();\n encryptedData = cipher.output.getBytes();\n\n // get PBKDF2-params\n var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm);\n\n encryptionAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pkcs5PBES2']).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // keyDerivationFunc\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pkcs5PBKDF2']).getBytes()),\n // PBKDF2-params\n params\n ]),\n // encryptionScheme\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(encOid).getBytes()),\n // iv\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, iv)\n ])\n ])\n ]);\n } else if(options.algorithm === '3des') {\n // Do PKCS12 PBE\n dkLen = 24;\n\n var saltBytes = new forge.util.ByteBuffer(salt);\n var dk = pki.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen);\n var iv = pki.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen);\n var cipher = forge.des.createEncryptionCipher(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(obj));\n cipher.finish();\n encryptedData = cipher.output.getBytes();\n\n encryptionAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pbeWithSHAAnd3-KeyTripleDES-CBC']).getBytes()),\n // pkcs-12PbeParams\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // salt\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),\n // iteration count\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n countBytes.getBytes())\n ])\n ]);\n } else {\n var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // EncryptedPrivateKeyInfo\n var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // encryptionAlgorithm\n encryptionAlgorithm,\n // encryptedData\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, encryptedData)\n ]);\n return rval;\n};\n\n/**\n * Decrypts a ASN.1 PrivateKeyInfo object.\n *\n * @param obj the ASN.1 EncryptedPrivateKeyInfo object.\n * @param password the password to decrypt with.\n *\n * @return the ASN.1 PrivateKeyInfo on success, null on failure.\n */\npki.decryptPrivateKeyInfo = function(obj, password) {\n var rval = null;\n\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n // get cipher\n var oid = asn1.derToOid(capture.encryptionOid);\n var cipher = pki.pbe.getCipher(oid, capture.encryptionParams, password);\n\n // get encrypted data\n var encrypted = forge.util.createBuffer(capture.encryptedData);\n\n cipher.update(encrypted);\n if(cipher.finish()) {\n rval = asn1.fromDer(cipher.output);\n }\n\n return rval;\n};\n\n/**\n * Converts a EncryptedPrivateKeyInfo to PEM format.\n *\n * @param epki the EncryptedPrivateKeyInfo.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted encrypted private key.\n */\npki.encryptedPrivateKeyToPem = function(epki, maxline) {\n // convert to DER, then PEM-encode\n var msg = {\n type: 'ENCRYPTED PRIVATE KEY',\n body: asn1.toDer(epki).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format. Decryption\n * is not performed.\n *\n * @param pem the EncryptedPrivateKeyInfo in PEM-format.\n *\n * @return the ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptedPrivateKeyFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'ENCRYPTED PRIVATE KEY') {\n var error = new Error('Could not convert encrypted private key from PEM; ' +\n 'PEM header type is \"ENCRYPTED PRIVATE KEY\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert encrypted private key from PEM; ' +\n 'PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n return asn1.fromDer(msg.body);\n};\n\n/**\n * Encrypts an RSA private key. By default, the key will be wrapped in\n * a PrivateKeyInfo and encrypted to produce a PKCS#8 EncryptedPrivateKeyInfo.\n * This is the standard, preferred way to encrypt a private key.\n *\n * To produce a non-standard PEM-encrypted private key that uses encapsulated\n * headers to indicate the encryption algorithm (old-style non-PKCS#8 OpenSSL\n * private key encryption), set the 'legacy' option to true. Note: Using this\n * option will cause the iteration count to be forced to 1.\n *\n * Note: The 'des' algorithm is supported, but it is not considered to be\n * secure because it only uses a single 56-bit key. If possible, it is highly\n * recommended that a different algorithm be used.\n *\n * @param rsaKey the RSA key to encrypt.\n * @param password the password to use.\n * @param options:\n * algorithm: the encryption algorithm to use\n * ('aes128', 'aes192', 'aes256', '3des', 'des').\n * count: the iteration count to use.\n * saltSize: the salt size to use.\n * legacy: output an old non-PKCS#8 PEM-encrypted+encapsulated\n * headers (DEK-Info) private key.\n *\n * @return the PEM-encoded ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptRsaPrivateKey = function(rsaKey, password, options) {\n // standard PKCS#8\n options = options || {};\n if(!options.legacy) {\n // encrypt PrivateKeyInfo\n var rval = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey));\n rval = pki.encryptPrivateKeyInfo(rval, password, options);\n return pki.encryptedPrivateKeyToPem(rval);\n }\n\n // legacy non-PKCS#8\n var algorithm;\n var iv;\n var dkLen;\n var cipherFn;\n switch(options.algorithm) {\n case 'aes128':\n algorithm = 'AES-128-CBC';\n dkLen = 16;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes192':\n algorithm = 'AES-192-CBC';\n dkLen = 24;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes256':\n algorithm = 'AES-256-CBC';\n dkLen = 32;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case '3des':\n algorithm = 'DES-EDE3-CBC';\n dkLen = 24;\n iv = forge.random.getBytesSync(8);\n cipherFn = forge.des.createEncryptionCipher;\n break;\n case 'des':\n algorithm = 'DES-CBC';\n dkLen = 8;\n iv = forge.random.getBytesSync(8);\n cipherFn = forge.des.createEncryptionCipher;\n break;\n default:\n var error = new Error('Could not encrypt RSA private key; unsupported ' +\n 'encryption algorithm \"' + options.algorithm + '\".');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // encrypt private key using OpenSSL legacy key derivation\n var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(pki.privateKeyToAsn1(rsaKey)));\n cipher.finish();\n\n var msg = {\n type: 'RSA PRIVATE KEY',\n procType: {\n version: '4',\n type: 'ENCRYPTED'\n },\n dekInfo: {\n algorithm: algorithm,\n parameters: forge.util.bytesToHex(iv).toUpperCase()\n },\n body: cipher.output.getBytes()\n };\n return forge.pem.encode(msg);\n};\n\n/**\n * Decrypts an RSA private key.\n *\n * @param pem the PEM-formatted EncryptedPrivateKeyInfo to decrypt.\n * @param password the password to use.\n *\n * @return the RSA key on success, null on failure.\n */\npki.decryptRsaPrivateKey = function(pem, password) {\n var rval = null;\n\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'ENCRYPTED PRIVATE KEY' &&\n msg.type !== 'PRIVATE KEY' &&\n msg.type !== 'RSA PRIVATE KEY') {\n var error = new Error('Could not convert private key from PEM; PEM header type ' +\n 'is not \"ENCRYPTED PRIVATE KEY\", \"PRIVATE KEY\", or \"RSA PRIVATE KEY\".');\n error.headerType = error;\n throw error;\n }\n\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n var dkLen;\n var cipherFn;\n switch(msg.dekInfo.algorithm) {\n case 'DES-CBC':\n dkLen = 8;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'DES-EDE3-CBC':\n dkLen = 24;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'AES-128-CBC':\n dkLen = 16;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'AES-192-CBC':\n dkLen = 24;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'AES-256-CBC':\n dkLen = 32;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'RC2-40-CBC':\n dkLen = 5;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 40);\n };\n break;\n case 'RC2-64-CBC':\n dkLen = 8;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 64);\n };\n break;\n case 'RC2-128-CBC':\n dkLen = 16;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 128);\n };\n break;\n default:\n var error = new Error('Could not decrypt private key; unsupported ' +\n 'encryption algorithm \"' + msg.dekInfo.algorithm + '\".');\n error.algorithm = msg.dekInfo.algorithm;\n throw error;\n }\n\n // use OpenSSL legacy key derivation\n var iv = forge.util.hexToBytes(msg.dekInfo.parameters);\n var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(forge.util.createBuffer(msg.body));\n if(cipher.finish()) {\n rval = cipher.output.getBytes();\n } else {\n return rval;\n }\n } else {\n rval = msg.body;\n }\n\n if(msg.type === 'ENCRYPTED PRIVATE KEY') {\n rval = pki.decryptPrivateKeyInfo(asn1.fromDer(rval), password);\n } else {\n // decryption already performed above\n rval = asn1.fromDer(rval);\n }\n\n if(rval !== null) {\n rval = pki.privateKeyFromAsn1(rval);\n }\n\n return rval;\n};\n\n/**\n * Derives a PKCS#12 key.\n *\n * @param password the password to derive the key material from, null or\n * undefined for none.\n * @param salt the salt, as a ByteBuffer, to use.\n * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC).\n * @param iter the iteration count.\n * @param n the number of bytes to derive from the password.\n * @param md the message digest to use, defaults to SHA-1.\n *\n * @return a ByteBuffer with the bytes derived from the password.\n */\npki.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) {\n var j, l;\n\n if(typeof md === 'undefined' || md === null) {\n if(!('sha1' in forge.md)) {\n throw new Error('\"sha1\" hash algorithm unavailable.');\n }\n md = forge.md.sha1.create();\n }\n\n var u = md.digestLength;\n var v = md.blockLength;\n var result = new forge.util.ByteBuffer();\n\n /* Convert password to Unicode byte buffer + trailing 0-byte. */\n var passBuf = new forge.util.ByteBuffer();\n if(password !== null && password !== undefined) {\n for(l = 0; l < password.length; l++) {\n passBuf.putInt16(password.charCodeAt(l));\n }\n passBuf.putInt16(0);\n }\n\n /* Length of salt and password in BYTES. */\n var p = passBuf.length();\n var s = salt.length();\n\n /* 1. Construct a string, D (the \"diversifier\"), by concatenating\n v copies of ID. */\n var D = new forge.util.ByteBuffer();\n D.fillWithByte(id, v);\n\n /* 2. Concatenate copies of the salt together to create a string S of length\n v * ceil(s / v) bytes (the final copy of the salt may be trunacted\n to create S).\n Note that if the salt is the empty string, then so is S. */\n var Slen = v * Math.ceil(s / v);\n var S = new forge.util.ByteBuffer();\n for(l = 0; l < Slen; l++) {\n S.putByte(salt.at(l % s));\n }\n\n /* 3. Concatenate copies of the password together to create a string P of\n length v * ceil(p / v) bytes (the final copy of the password may be\n truncated to create P).\n Note that if the password is the empty string, then so is P. */\n var Plen = v * Math.ceil(p / v);\n var P = new forge.util.ByteBuffer();\n for(l = 0; l < Plen; l++) {\n P.putByte(passBuf.at(l % p));\n }\n\n /* 4. Set I=S||P to be the concatenation of S and P. */\n var I = S;\n I.putBuffer(P);\n\n /* 5. Set c=ceil(n / u). */\n var c = Math.ceil(n / u);\n\n /* 6. For i=1, 2, ..., c, do the following: */\n for(var i = 1; i <= c; i++) {\n /* a) Set Ai=H^r(D||I). (l.e. the rth hash of D||I, H(H(H(...H(D||I)))) */\n var buf = new forge.util.ByteBuffer();\n buf.putBytes(D.bytes());\n buf.putBytes(I.bytes());\n for(var round = 0; round < iter; round++) {\n md.start();\n md.update(buf.getBytes());\n buf = md.digest();\n }\n\n /* b) Concatenate copies of Ai to create a string B of length v bytes (the\n final copy of Ai may be truncated to create B). */\n var B = new forge.util.ByteBuffer();\n for(l = 0; l < v; l++) {\n B.putByte(buf.at(l % u));\n }\n\n /* c) Treating I as a concatenation I0, I1, ..., Ik-1 of v-byte blocks,\n where k=ceil(s / v) + ceil(p / v), modify I by setting\n Ij=(Ij+B+1) mod 2v for each j. */\n var k = Math.ceil(s / v) + Math.ceil(p / v);\n var Inew = new forge.util.ByteBuffer();\n for(j = 0; j < k; j++) {\n var chunk = new forge.util.ByteBuffer(I.getBytes(v));\n var x = 0x1ff;\n for(l = B.length() - 1; l >= 0; l--) {\n x = x >> 8;\n x += B.at(l) + chunk.at(l);\n chunk.setAt(l, x & 0xff);\n }\n Inew.putBuffer(chunk);\n }\n I = Inew;\n\n /* Add Ai to A. */\n result.putBuffer(buf);\n }\n\n result.truncate(result.length() - n);\n return result;\n};\n\n/**\n * Get new Forge cipher object instance.\n *\n * @param oid the OID (in string notation).\n * @param params the ASN.1 params object.\n * @param password the password to decrypt with.\n *\n * @return new cipher object instance.\n */\npki.pbe.getCipher = function(oid, params, password) {\n switch(oid) {\n case pki.oids['pkcs5PBES2']:\n return pki.pbe.getCipherForPBES2(oid, params, password);\n\n case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:\n case pki.oids['pbewithSHAAnd40BitRC2-CBC']:\n return pki.pbe.getCipherForPKCS12PBE(oid, params, password);\n\n default:\n var error = new Error('Cannot read encrypted PBE data block. Unsupported OID.');\n error.oid = oid;\n error.supportedOids = [\n 'pkcs5PBES2',\n 'pbeWithSHAAnd3-KeyTripleDES-CBC',\n 'pbewithSHAAnd40BitRC2-CBC'\n ];\n throw error;\n }\n};\n\n/**\n * Get new Forge cipher object instance according to PBES2 params block.\n *\n * The returned cipher instance is already started using the IV\n * from PBES2 parameter block.\n *\n * @param oid the PKCS#5 PBKDF2 OID (in string notation).\n * @param params the ASN.1 PBES2-params object.\n * @param password the password to decrypt with.\n *\n * @return new cipher object instance.\n */\npki.pbe.getCipherForPBES2 = function(oid, params, password) {\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) {\n var error = new Error('Cannot read password-based-encryption algorithm ' +\n 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n // check oids\n oid = asn1.derToOid(capture.kdfOid);\n if(oid !== pki.oids['pkcs5PBKDF2']) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'Unsupported key derivation function OID.');\n error.oid = oid;\n error.supportedOids = ['pkcs5PBKDF2'];\n throw error;\n }\n oid = asn1.derToOid(capture.encOid);\n if(oid !== pki.oids['aes128-CBC'] &&\n oid !== pki.oids['aes192-CBC'] &&\n oid !== pki.oids['aes256-CBC'] &&\n oid !== pki.oids['des-EDE3-CBC'] &&\n oid !== pki.oids['desCBC']) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'Unsupported encryption scheme OID.');\n error.oid = oid;\n error.supportedOids = [\n 'aes128-CBC', 'aes192-CBC', 'aes256-CBC', 'des-EDE3-CBC', 'desCBC'];\n throw error;\n }\n\n // set PBE params\n var salt = capture.kdfSalt;\n var count = forge.util.createBuffer(capture.kdfIterationCount);\n count = count.getInt(count.length() << 3);\n var dkLen;\n var cipherFn;\n switch(pki.oids[oid]) {\n case 'aes128-CBC':\n dkLen = 16;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'aes192-CBC':\n dkLen = 24;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'aes256-CBC':\n dkLen = 32;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'des-EDE3-CBC':\n dkLen = 24;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'desCBC':\n dkLen = 8;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n }\n\n // get PRF message digest\n var md = prfOidToMessageDigest(capture.prfOid);\n\n // decrypt private key using pbe with chosen PRF and AES/DES\n var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md);\n var iv = capture.encIv;\n var cipher = cipherFn(dk);\n cipher.start(iv);\n\n return cipher;\n};\n\n/**\n * Get new Forge cipher object instance for PKCS#12 PBE.\n *\n * The returned cipher instance is already started using the key & IV\n * derived from the provided password and PKCS#12 PBE salt.\n *\n * @param oid The PKCS#12 PBE OID (in string notation).\n * @param params The ASN.1 PKCS#12 PBE-params object.\n * @param password The password to decrypt with.\n *\n * @return the new cipher object instance.\n */\npki.pbe.getCipherForPKCS12PBE = function(oid, params, password) {\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) {\n var error = new Error('Cannot read password-based-encryption algorithm ' +\n 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n var salt = forge.util.createBuffer(capture.salt);\n var count = forge.util.createBuffer(capture.iterations);\n count = count.getInt(count.length() << 3);\n\n var dkLen, dIvLen, cipherFn;\n switch(oid) {\n case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:\n dkLen = 24;\n dIvLen = 8;\n cipherFn = forge.des.startDecrypting;\n break;\n\n case pki.oids['pbewithSHAAnd40BitRC2-CBC']:\n dkLen = 5;\n dIvLen = 8;\n cipherFn = function(key, iv) {\n var cipher = forge.rc2.createDecryptionCipher(key, 40);\n cipher.start(iv, null);\n return cipher;\n };\n break;\n\n default:\n var error = new Error('Cannot read PKCS #12 PBE data block. Unsupported OID.');\n error.oid = oid;\n throw error;\n }\n\n // get PRF message digest\n var md = prfOidToMessageDigest(capture.prfOid);\n var key = pki.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md);\n md.start();\n var iv = pki.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md);\n\n return cipherFn(key, iv);\n};\n\n/**\n * OpenSSL's legacy key derivation function.\n *\n * See: http://www.openssl.org/docs/crypto/EVP_BytesToKey.html\n *\n * @param password the password to derive the key from.\n * @param salt the salt to use, null for none.\n * @param dkLen the number of bytes needed for the derived key.\n * @param [options] the options to use:\n * [md] an optional message digest object to use.\n */\npki.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) {\n if(typeof md === 'undefined' || md === null) {\n if(!('md5' in forge.md)) {\n throw new Error('\"md5\" hash algorithm unavailable.');\n }\n md = forge.md.md5.create();\n }\n if(salt === null) {\n salt = '';\n }\n var digests = [hash(md, password + salt)];\n for(var length = 16, i = 1; length < dkLen; ++i, length += 16) {\n digests.push(hash(md, digests[i - 1] + password + salt));\n }\n return digests.join('').substr(0, dkLen);\n};\n\nfunction hash(md, bytes) {\n return md.start().update(bytes).digest().getBytes();\n}\n\nfunction prfOidToMessageDigest(prfOid) {\n // get PRF algorithm, default to SHA-1\n var prfAlgorithm;\n if(!prfOid) {\n prfAlgorithm = 'hmacWithSHA1';\n } else {\n prfAlgorithm = pki.oids[asn1.derToOid(prfOid)];\n if(!prfAlgorithm) {\n var error = new Error('Unsupported PRF OID.');\n error.oid = prfOid;\n error.supported = [\n 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',\n 'hmacWithSHA512'];\n throw error;\n }\n }\n return prfAlgorithmToMessageDigest(prfAlgorithm);\n}\n\nfunction prfAlgorithmToMessageDigest(prfAlgorithm) {\n var factory = forge.md;\n switch(prfAlgorithm) {\n case 'hmacWithSHA224':\n factory = forge.md.sha512;\n case 'hmacWithSHA1':\n case 'hmacWithSHA256':\n case 'hmacWithSHA384':\n case 'hmacWithSHA512':\n prfAlgorithm = prfAlgorithm.substr(8).toLowerCase();\n break;\n default:\n var error = new Error('Unsupported PRF algorithm.');\n error.algorithm = prfAlgorithm;\n error.supported = [\n 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',\n 'hmacWithSHA512'];\n throw error;\n }\n if(!factory || !(prfAlgorithm in factory)) {\n throw new Error('Unknown hash algorithm: ' + prfAlgorithm);\n }\n return factory[prfAlgorithm].create();\n}\n\nfunction createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) {\n var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // salt\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),\n // iteration count\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n countBytes.getBytes())\n ]);\n // when PRF algorithm is not SHA-1 default, add key length and PRF algorithm\n if(prfAlgorithm !== 'hmacWithSHA1') {\n params.value.push(\n // key length\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(dkLen.toString(16))),\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]));\n }\n return params;\n}\n","/**\n * Javascript implementation of ASN.1 validators for PKCS#7 v1.5.\n *\n * @author Dave Longley\n * @author Stefan Siegl\n *\n * Copyright (c) 2012-2015 Digital Bazaar, Inc.\n * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>\n *\n * The ASN.1 representation of PKCS#7 is as follows\n * (see RFC #2315 for details, http://www.ietf.org/rfc/rfc2315.txt):\n *\n * A PKCS#7 message consists of a ContentInfo on root level, which may\n * contain any number of further ContentInfo nested into it.\n *\n * ContentInfo ::= SEQUENCE {\n * contentType ContentType,\n * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL\n * }\n *\n * ContentType ::= OBJECT IDENTIFIER\n *\n * EnvelopedData ::= SEQUENCE {\n * version Version,\n * recipientInfos RecipientInfos,\n * encryptedContentInfo EncryptedContentInfo\n * }\n *\n * EncryptedData ::= SEQUENCE {\n * version Version,\n * encryptedContentInfo EncryptedContentInfo\n * }\n *\n * id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)\n * us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 }\n *\n * SignedData ::= SEQUENCE {\n * version INTEGER,\n * digestAlgorithms DigestAlgorithmIdentifiers,\n * contentInfo ContentInfo,\n * certificates [0] IMPLICIT Certificates OPTIONAL,\n * crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,\n * signerInfos SignerInfos\n * }\n *\n * SignerInfos ::= SET OF SignerInfo\n *\n * SignerInfo ::= SEQUENCE {\n * version Version,\n * issuerAndSerialNumber IssuerAndSerialNumber,\n * digestAlgorithm DigestAlgorithmIdentifier,\n * authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL,\n * digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,\n * encryptedDigest EncryptedDigest,\n * unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL\n * }\n *\n * EncryptedDigest ::= OCTET STRING\n *\n * Attributes ::= SET OF Attribute\n *\n * Attribute ::= SEQUENCE {\n * attrType OBJECT IDENTIFIER,\n * attrValues SET OF AttributeValue\n * }\n *\n * AttributeValue ::= ANY\n *\n * Version ::= INTEGER\n *\n * RecipientInfos ::= SET OF RecipientInfo\n *\n * EncryptedContentInfo ::= SEQUENCE {\n * contentType ContentType,\n * contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,\n * encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL\n * }\n *\n * ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters\n * for the algorithm, if any. In the case of AES and DES3, there is only one,\n * the IV.\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * EncryptedContent ::= OCTET STRING\n *\n * RecipientInfo ::= SEQUENCE {\n * version Version,\n * issuerAndSerialNumber IssuerAndSerialNumber,\n * keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,\n * encryptedKey EncryptedKey\n * }\n *\n * IssuerAndSerialNumber ::= SEQUENCE {\n * issuer Name,\n * serialNumber CertificateSerialNumber\n * }\n *\n * CertificateSerialNumber ::= INTEGER\n *\n * KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * EncryptedKey ::= OCTET STRING\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./util');\n\n// shortcut for ASN.1 API\nvar asn1 = forge.asn1;\n\n// shortcut for PKCS#7 API\nvar p7v = module.exports = forge.pkcs7asn1 = forge.pkcs7asn1 || {};\nforge.pkcs7 = forge.pkcs7 || {};\nforge.pkcs7.asn1 = p7v;\n\nvar contentInfoValidator = {\n name: 'ContentInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'ContentInfo.ContentType',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'contentType'\n }, {\n name: 'ContentInfo.content',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n captureAsn1: 'content'\n }]\n};\np7v.contentInfoValidator = contentInfoValidator;\n\nvar encryptedContentInfoValidator = {\n name: 'EncryptedContentInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedContentInfo.contentType',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'contentType'\n }, {\n name: 'EncryptedContentInfo.contentEncryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedContentInfo.contentEncryptionAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encAlgorithm'\n }, {\n name: 'EncryptedContentInfo.contentEncryptionAlgorithm.parameter',\n tagClass: asn1.Class.UNIVERSAL,\n captureAsn1: 'encParameter'\n }]\n }, {\n name: 'EncryptedContentInfo.encryptedContent',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n /* The PKCS#7 structure output by OpenSSL somewhat differs from what\n * other implementations do generate.\n *\n * OpenSSL generates a structure like this:\n * SEQUENCE {\n * ...\n * [0]\n * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38\n * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45\n * ...\n * }\n *\n * Whereas other implementations (and this PKCS#7 module) generate:\n * SEQUENCE {\n * ...\n * [0] {\n * OCTET STRING\n * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38\n * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45\n * ...\n * }\n * }\n *\n * In order to support both, we just capture the context specific\n * field here. The OCTET STRING bit is removed below.\n */\n capture: 'encryptedContent',\n captureAsn1: 'encryptedContentAsn1'\n }]\n};\n\np7v.envelopedDataValidator = {\n name: 'EnvelopedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EnvelopedData.Version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }, {\n name: 'EnvelopedData.RecipientInfos',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n captureAsn1: 'recipientInfos'\n }].concat(encryptedContentInfoValidator)\n};\n\np7v.encryptedDataValidator = {\n name: 'EncryptedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedData.Version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }].concat(encryptedContentInfoValidator)\n};\n\nvar signerValidator = {\n name: 'SignerInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignerInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false\n }, {\n name: 'SignerInfo.issuerAndSerialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignerInfo.issuerAndSerialNumber.issuer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'issuer'\n }, {\n name: 'SignerInfo.issuerAndSerialNumber.serialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'serial'\n }]\n }, {\n name: 'SignerInfo.digestAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignerInfo.digestAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'digestAlgorithm'\n }, {\n name: 'SignerInfo.digestAlgorithm.parameter',\n tagClass: asn1.Class.UNIVERSAL,\n constructed: false,\n captureAsn1: 'digestParameter',\n optional: true\n }]\n }, {\n name: 'SignerInfo.authenticatedAttributes',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n capture: 'authenticatedAttributes'\n }, {\n name: 'SignerInfo.digestEncryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n capture: 'signatureAlgorithm'\n }, {\n name: 'SignerInfo.encryptedDigest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'signature'\n }, {\n name: 'SignerInfo.unauthenticatedAttributes',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n constructed: true,\n optional: true,\n capture: 'unauthenticatedAttributes'\n }]\n};\n\np7v.signedDataValidator = {\n name: 'SignedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignedData.Version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }, {\n name: 'SignedData.DigestAlgorithms',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n captureAsn1: 'digestAlgorithms'\n },\n contentInfoValidator,\n {\n name: 'SignedData.Certificates',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n optional: true,\n captureAsn1: 'certificates'\n }, {\n name: 'SignedData.CertificateRevocationLists',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n optional: true,\n captureAsn1: 'crls'\n }, {\n name: 'SignedData.SignerInfos',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n capture: 'signerInfos',\n optional: true,\n value: [signerValidator]\n }]\n};\n\np7v.recipientInfoValidator = {\n name: 'RecipientInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'RecipientInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }, {\n name: 'RecipientInfo.issuerAndSerial',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'RecipientInfo.issuerAndSerial.issuer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'issuer'\n }, {\n name: 'RecipientInfo.issuerAndSerial.serialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'serial'\n }]\n }, {\n name: 'RecipientInfo.keyEncryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'RecipientInfo.keyEncryptionAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encAlgorithm'\n }, {\n name: 'RecipientInfo.keyEncryptionAlgorithm.parameter',\n tagClass: asn1.Class.UNIVERSAL,\n constructed: false,\n captureAsn1: 'encParameter',\n optional: true\n }]\n }, {\n name: 'RecipientInfo.encryptedKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encKey'\n }]\n};\n","/**\n * Javascript implementation of mask generation function MGF1.\n *\n * @author Stefan Siegl\n * @author Dave Longley\n *\n * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>\n * Copyright (c) 2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nforge.mgf = forge.mgf || {};\nvar mgf1 = module.exports = forge.mgf.mgf1 = forge.mgf1 = forge.mgf1 || {};\n\n/**\n * Creates a MGF1 mask generation function object.\n *\n * @param md the message digest API to use (eg: forge.md.sha1.create()).\n *\n * @return a mask generation function object.\n */\nmgf1.create = function(md) {\n var mgf = {\n /**\n * Generate mask of specified length.\n *\n * @param {String} seed The seed for mask generation.\n * @param maskLen Number of bytes to generate.\n * @return {String} The generated mask.\n */\n generate: function(seed, maskLen) {\n /* 2. Let T be the empty octet string. */\n var t = new forge.util.ByteBuffer();\n\n /* 3. For counter from 0 to ceil(maskLen / hLen), do the following: */\n var len = Math.ceil(maskLen / md.digestLength);\n for(var i = 0; i < len; i++) {\n /* a. Convert counter to an octet string C of length 4 octets */\n var c = new forge.util.ByteBuffer();\n c.putInt32(i);\n\n /* b. Concatenate the hash of the seed mgfSeed and C to the octet\n * string T: */\n md.start();\n md.update(seed + c.getBytes());\n t.putBuffer(md.digest());\n }\n\n /* Output the leading maskLen octets of T as the octet string mask. */\n t.truncate(t.length() - maskLen);\n return t.getBytes();\n }\n };\n\n return mgf;\n};\n","/**\n * Node.js module for Forge mask generation functions.\n *\n * @author Stefan Siegl\n *\n * Copyright 2012 Stefan Siegl <stesie@brokenpipe.de>\n */\nvar forge = require('./forge');\nrequire('./mgf1');\n\nmodule.exports = forge.mgf = forge.mgf || {};\nforge.mgf.mgf1 = forge.mgf1;\n","/**\n * Javascript implementation of PKCS#1 PSS signature padding.\n *\n * @author Stefan Siegl\n *\n * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>\n */\nvar forge = require('./forge');\nrequire('./random');\nrequire('./util');\n\n// shortcut for PSS API\nvar pss = module.exports = forge.pss = forge.pss || {};\n\n/**\n * Creates a PSS signature scheme object.\n *\n * There are several ways to provide a salt for encoding:\n *\n * 1. Specify the saltLength only and the built-in PRNG will generate it.\n * 2. Specify the saltLength and a custom PRNG with 'getBytesSync' defined that\n * will be used.\n * 3. Specify the salt itself as a forge.util.ByteBuffer.\n *\n * @param options the options to use:\n * md the message digest object to use, a forge md instance.\n * mgf the mask generation function to use, a forge mgf instance.\n * [saltLength] the length of the salt in octets.\n * [prng] the pseudo-random number generator to use to produce a salt.\n * [salt] the salt to use when encoding.\n *\n * @return a signature scheme object.\n */\npss.create = function(options) {\n // backwards compatibility w/legacy args: hash, mgf, sLen\n if(arguments.length === 3) {\n options = {\n md: arguments[0],\n mgf: arguments[1],\n saltLength: arguments[2]\n };\n }\n\n var hash = options.md;\n var mgf = options.mgf;\n var hLen = hash.digestLength;\n\n var salt_ = options.salt || null;\n if(typeof salt_ === 'string') {\n // assume binary-encoded string\n salt_ = forge.util.createBuffer(salt_);\n }\n\n var sLen;\n if('saltLength' in options) {\n sLen = options.saltLength;\n } else if(salt_ !== null) {\n sLen = salt_.length();\n } else {\n throw new Error('Salt length not specified or specific salt not given.');\n }\n\n if(salt_ !== null && salt_.length() !== sLen) {\n throw new Error('Given salt length does not match length of given salt.');\n }\n\n var prng = options.prng || forge.random;\n\n var pssobj = {};\n\n /**\n * Encodes a PSS signature.\n *\n * This function implements EMSA-PSS-ENCODE as per RFC 3447, section 9.1.1.\n *\n * @param md the message digest object with the hash to sign.\n * @param modsBits the length of the RSA modulus in bits.\n *\n * @return the encoded message as a binary-encoded string of length\n * ceil((modBits - 1) / 8).\n */\n pssobj.encode = function(md, modBits) {\n var i;\n var emBits = modBits - 1;\n var emLen = Math.ceil(emBits / 8);\n\n /* 2. Let mHash = Hash(M), an octet string of length hLen. */\n var mHash = md.digest().getBytes();\n\n /* 3. If emLen < hLen + sLen + 2, output \"encoding error\" and stop. */\n if(emLen < hLen + sLen + 2) {\n throw new Error('Message is too long to encrypt.');\n }\n\n /* 4. Generate a random octet string salt of length sLen; if sLen = 0,\n * then salt is the empty string. */\n var salt;\n if(salt_ === null) {\n salt = prng.getBytesSync(sLen);\n } else {\n salt = salt_.bytes();\n }\n\n /* 5. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt; */\n var m_ = new forge.util.ByteBuffer();\n m_.fillWithByte(0, 8);\n m_.putBytes(mHash);\n m_.putBytes(salt);\n\n /* 6. Let H = Hash(M'), an octet string of length hLen. */\n hash.start();\n hash.update(m_.getBytes());\n var h = hash.digest().getBytes();\n\n /* 7. Generate an octet string PS consisting of emLen - sLen - hLen - 2\n * zero octets. The length of PS may be 0. */\n var ps = new forge.util.ByteBuffer();\n ps.fillWithByte(0, emLen - sLen - hLen - 2);\n\n /* 8. Let DB = PS || 0x01 || salt; DB is an octet string of length\n * emLen - hLen - 1. */\n ps.putByte(0x01);\n ps.putBytes(salt);\n var db = ps.getBytes();\n\n /* 9. Let dbMask = MGF(H, emLen - hLen - 1). */\n var maskLen = emLen - hLen - 1;\n var dbMask = mgf.generate(h, maskLen);\n\n /* 10. Let maskedDB = DB \\xor dbMask. */\n var maskedDB = '';\n for(i = 0; i < maskLen; i++) {\n maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i));\n }\n\n /* 11. Set the leftmost 8emLen - emBits bits of the leftmost octet in\n * maskedDB to zero. */\n var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF;\n maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) +\n maskedDB.substr(1);\n\n /* 12. Let EM = maskedDB || H || 0xbc.\n * 13. Output EM. */\n return maskedDB + h + String.fromCharCode(0xbc);\n };\n\n /**\n * Verifies a PSS signature.\n *\n * This function implements EMSA-PSS-VERIFY as per RFC 3447, section 9.1.2.\n *\n * @param mHash the message digest hash, as a binary-encoded string, to\n * compare against the signature.\n * @param em the encoded message, as a binary-encoded string\n * (RSA decryption result).\n * @param modsBits the length of the RSA modulus in bits.\n *\n * @return true if the signature was verified, false if not.\n */\n pssobj.verify = function(mHash, em, modBits) {\n var i;\n var emBits = modBits - 1;\n var emLen = Math.ceil(emBits / 8);\n\n /* c. Convert the message representative m to an encoded message EM\n * of length emLen = ceil((modBits - 1) / 8) octets, where modBits\n * is the length in bits of the RSA modulus n */\n em = em.substr(-emLen);\n\n /* 3. If emLen < hLen + sLen + 2, output \"inconsistent\" and stop. */\n if(emLen < hLen + sLen + 2) {\n throw new Error('Inconsistent parameters to PSS signature verification.');\n }\n\n /* 4. If the rightmost octet of EM does not have hexadecimal value\n * 0xbc, output \"inconsistent\" and stop. */\n if(em.charCodeAt(emLen - 1) !== 0xbc) {\n throw new Error('Encoded message does not end in 0xBC.');\n }\n\n /* 5. Let maskedDB be the leftmost emLen - hLen - 1 octets of EM, and\n * let H be the next hLen octets. */\n var maskLen = emLen - hLen - 1;\n var maskedDB = em.substr(0, maskLen);\n var h = em.substr(maskLen, hLen);\n\n /* 6. If the leftmost 8emLen - emBits bits of the leftmost octet in\n * maskedDB are not all equal to zero, output \"inconsistent\" and stop. */\n var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF;\n if((maskedDB.charCodeAt(0) & mask) !== 0) {\n throw new Error('Bits beyond keysize not zero as expected.');\n }\n\n /* 7. Let dbMask = MGF(H, emLen - hLen - 1). */\n var dbMask = mgf.generate(h, maskLen);\n\n /* 8. Let DB = maskedDB \\xor dbMask. */\n var db = '';\n for(i = 0; i < maskLen; i++) {\n db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i));\n }\n\n /* 9. Set the leftmost 8emLen - emBits bits of the leftmost octet\n * in DB to zero. */\n db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1);\n\n /* 10. If the emLen - hLen - sLen - 2 leftmost octets of DB are not zero\n * or if the octet at position emLen - hLen - sLen - 1 (the leftmost\n * position is \"position 1\") does not have hexadecimal value 0x01,\n * output \"inconsistent\" and stop. */\n var checkLen = emLen - hLen - sLen - 2;\n for(i = 0; i < checkLen; i++) {\n if(db.charCodeAt(i) !== 0x00) {\n throw new Error('Leftmost octets not zero as expected');\n }\n }\n\n if(db.charCodeAt(checkLen) !== 0x01) {\n throw new Error('Inconsistent PSS signature, 0x01 marker not found');\n }\n\n /* 11. Let salt be the last sLen octets of DB. */\n var salt = db.substr(-sLen);\n\n /* 12. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt */\n var m_ = new forge.util.ByteBuffer();\n m_.fillWithByte(0, 8);\n m_.putBytes(mHash);\n m_.putBytes(salt);\n\n /* 13. Let H' = Hash(M'), an octet string of length hLen. */\n hash.start();\n hash.update(m_.getBytes());\n var h_ = hash.digest().getBytes();\n\n /* 14. If H = H', output \"consistent.\" Otherwise, output \"inconsistent.\" */\n return h === h_;\n };\n\n return pssobj;\n};\n","/**\n * Javascript implementation of X.509 and related components (such as\n * Certification Signing Requests) of a Public Key Infrastructure.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n *\n * The ASN.1 representation of an X.509v3 certificate is as follows\n * (see RFC 2459):\n *\n * Certificate ::= SEQUENCE {\n * tbsCertificate TBSCertificate,\n * signatureAlgorithm AlgorithmIdentifier,\n * signatureValue BIT STRING\n * }\n *\n * TBSCertificate ::= SEQUENCE {\n * version [0] EXPLICIT Version DEFAULT v1,\n * serialNumber CertificateSerialNumber,\n * signature AlgorithmIdentifier,\n * issuer Name,\n * validity Validity,\n * subject Name,\n * subjectPublicKeyInfo SubjectPublicKeyInfo,\n * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,\n * -- If present, version shall be v2 or v3\n * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,\n * -- If present, version shall be v2 or v3\n * extensions [3] EXPLICIT Extensions OPTIONAL\n * -- If present, version shall be v3\n * }\n *\n * Version ::= INTEGER { v1(0), v2(1), v3(2) }\n *\n * CertificateSerialNumber ::= INTEGER\n *\n * Name ::= CHOICE {\n * // only one possible choice for now\n * RDNSequence\n * }\n *\n * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName\n *\n * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue\n *\n * AttributeTypeAndValue ::= SEQUENCE {\n * type AttributeType,\n * value AttributeValue\n * }\n * AttributeType ::= OBJECT IDENTIFIER\n * AttributeValue ::= ANY DEFINED BY AttributeType\n *\n * Validity ::= SEQUENCE {\n * notBefore Time,\n * notAfter Time\n * }\n *\n * Time ::= CHOICE {\n * utcTime UTCTime,\n * generalTime GeneralizedTime\n * }\n *\n * UniqueIdentifier ::= BIT STRING\n *\n * SubjectPublicKeyInfo ::= SEQUENCE {\n * algorithm AlgorithmIdentifier,\n * subjectPublicKey BIT STRING\n * }\n *\n * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension\n *\n * Extension ::= SEQUENCE {\n * extnID OBJECT IDENTIFIER,\n * critical BOOLEAN DEFAULT FALSE,\n * extnValue OCTET STRING\n * }\n *\n * The only key algorithm currently supported for PKI is RSA.\n *\n * RSASSA-PSS signatures are described in RFC 3447 and RFC 4055.\n *\n * PKCS#10 v1.7 describes certificate signing requests:\n *\n * CertificationRequestInfo:\n *\n * CertificationRequestInfo ::= SEQUENCE {\n * version INTEGER { v1(0) } (v1,...),\n * subject Name,\n * subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},\n * attributes [0] Attributes{{ CRIAttributes }}\n * }\n *\n * Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}\n *\n * CRIAttributes ATTRIBUTE ::= {\n * ... -- add any locally defined attributes here -- }\n *\n * Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {\n * type ATTRIBUTE.&id({IOSet}),\n * values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type})\n * }\n *\n * CertificationRequest ::= SEQUENCE {\n * certificationRequestInfo CertificationRequestInfo,\n * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},\n * signature BIT STRING\n * }\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./asn1');\nrequire('./des');\nrequire('./md');\nrequire('./mgf');\nrequire('./oids');\nrequire('./pem');\nrequire('./pss');\nrequire('./rsa');\nrequire('./util');\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n/* Public Key Infrastructure (PKI) implementation. */\nvar pki = module.exports = forge.pki = forge.pki || {};\nvar oids = pki.oids;\n\n// short name OID mappings\nvar _shortNames = {};\n_shortNames['CN'] = oids['commonName'];\n_shortNames['commonName'] = 'CN';\n_shortNames['C'] = oids['countryName'];\n_shortNames['countryName'] = 'C';\n_shortNames['L'] = oids['localityName'];\n_shortNames['localityName'] = 'L';\n_shortNames['ST'] = oids['stateOrProvinceName'];\n_shortNames['stateOrProvinceName'] = 'ST';\n_shortNames['O'] = oids['organizationName'];\n_shortNames['organizationName'] = 'O';\n_shortNames['OU'] = oids['organizationalUnitName'];\n_shortNames['organizationalUnitName'] = 'OU';\n_shortNames['E'] = oids['emailAddress'];\n_shortNames['emailAddress'] = 'E';\n\n// validator for an SubjectPublicKeyInfo structure\n// Note: Currently only works with an RSA public key\nvar publicKeyValidator = forge.pki.rsa.publicKeyValidator;\n\n// validator for an X.509v3 certificate\nvar x509CertificateValidator = {\n name: 'Certificate',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'Certificate.TBSCertificate',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'tbsCertificate',\n value: [{\n name: 'Certificate.TBSCertificate.version',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n value: [{\n name: 'Certificate.TBSCertificate.version.integer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'certVersion'\n }]\n }, {\n name: 'Certificate.TBSCertificate.serialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'certSerialNumber'\n }, {\n name: 'Certificate.TBSCertificate.signature',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'Certificate.TBSCertificate.signature.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'certinfoSignatureOid'\n }, {\n name: 'Certificate.TBSCertificate.signature.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n optional: true,\n captureAsn1: 'certinfoSignatureParams'\n }]\n }, {\n name: 'Certificate.TBSCertificate.issuer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certIssuer'\n }, {\n name: 'Certificate.TBSCertificate.validity',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n // Note: UTC and generalized times may both appear so the capture\n // names are based on their detected order, the names used below\n // are only for the common case, which validity time really means\n // \"notBefore\" and which means \"notAfter\" will be determined by order\n value: [{\n // notBefore (Time) (UTC time case)\n name: 'Certificate.TBSCertificate.validity.notBefore (utc)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.UTCTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity1UTCTime'\n }, {\n // notBefore (Time) (generalized time case)\n name: 'Certificate.TBSCertificate.validity.notBefore (generalized)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.GENERALIZEDTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity2GeneralizedTime'\n }, {\n // notAfter (Time) (only UTC time is supported)\n name: 'Certificate.TBSCertificate.validity.notAfter (utc)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.UTCTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity3UTCTime'\n }, {\n // notAfter (Time) (only UTC time is supported)\n name: 'Certificate.TBSCertificate.validity.notAfter (generalized)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.GENERALIZEDTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity4GeneralizedTime'\n }]\n }, {\n // Name (subject) (RDNSequence)\n name: 'Certificate.TBSCertificate.subject',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certSubject'\n },\n // SubjectPublicKeyInfo\n publicKeyValidator,\n {\n // issuerUniqueID (optional)\n name: 'Certificate.TBSCertificate.issuerUniqueID',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n constructed: true,\n optional: true,\n value: [{\n name: 'Certificate.TBSCertificate.issuerUniqueID.id',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n // TODO: support arbitrary bit length ids\n captureBitStringValue: 'certIssuerUniqueId'\n }]\n }, {\n // subjectUniqueID (optional)\n name: 'Certificate.TBSCertificate.subjectUniqueID',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 2,\n constructed: true,\n optional: true,\n value: [{\n name: 'Certificate.TBSCertificate.subjectUniqueID.id',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n // TODO: support arbitrary bit length ids\n captureBitStringValue: 'certSubjectUniqueId'\n }]\n }, {\n // Extensions (optional)\n name: 'Certificate.TBSCertificate.extensions',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 3,\n constructed: true,\n captureAsn1: 'certExtensions',\n optional: true\n }]\n }, {\n // AlgorithmIdentifier (signature algorithm)\n name: 'Certificate.signatureAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // algorithm\n name: 'Certificate.signatureAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'certSignatureOid'\n }, {\n name: 'Certificate.TBSCertificate.signature.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n optional: true,\n captureAsn1: 'certSignatureParams'\n }]\n }, {\n // SignatureValue\n name: 'Certificate.signatureValue',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n captureBitStringValue: 'certSignature'\n }]\n};\n\nvar rsassaPssParameterValidator = {\n name: 'rsapss',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'rsapss.hashAlgorithm',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n value: [{\n name: 'rsapss.hashAlgorithm.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.SEQUENCE,\n constructed: true,\n optional: true,\n value: [{\n name: 'rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'hashOid'\n /* parameter block omitted, for SHA1 NULL anyhow. */\n }]\n }]\n }, {\n name: 'rsapss.maskGenAlgorithm',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n constructed: true,\n value: [{\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.SEQUENCE,\n constructed: true,\n optional: true,\n value: [{\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'maskGenOid'\n }, {\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'maskGenHashOid'\n /* parameter block omitted, for SHA1 NULL anyhow. */\n }]\n }]\n }]\n }, {\n name: 'rsapss.saltLength',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 2,\n optional: true,\n value: [{\n name: 'rsapss.saltLength.saltLength',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.INTEGER,\n constructed: false,\n capture: 'saltLength'\n }]\n }, {\n name: 'rsapss.trailerField',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 3,\n optional: true,\n value: [{\n name: 'rsapss.trailer.trailer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.INTEGER,\n constructed: false,\n capture: 'trailer'\n }]\n }]\n};\n\n// validator for a CertificationRequestInfo structure\nvar certificationRequestInfoValidator = {\n name: 'CertificationRequestInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certificationRequestInfo',\n value: [{\n name: 'CertificationRequestInfo.integer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'certificationRequestInfoVersion'\n }, {\n // Name (subject) (RDNSequence)\n name: 'CertificationRequestInfo.subject',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certificationRequestInfoSubject'\n },\n // SubjectPublicKeyInfo\n publicKeyValidator,\n {\n name: 'CertificationRequestInfo.attributes',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n capture: 'certificationRequestInfoAttributes',\n value: [{\n name: 'CertificationRequestInfo.attributes',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'CertificationRequestInfo.attributes.type',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false\n }, {\n name: 'CertificationRequestInfo.attributes.value',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true\n }]\n }]\n }]\n};\n\n// validator for a CertificationRequest structure\nvar certificationRequestValidator = {\n name: 'CertificationRequest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'csr',\n value: [\n certificationRequestInfoValidator, {\n // AlgorithmIdentifier (signature algorithm)\n name: 'CertificationRequest.signatureAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // algorithm\n name: 'CertificationRequest.signatureAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'csrSignatureOid'\n }, {\n name: 'CertificationRequest.signatureAlgorithm.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n optional: true,\n captureAsn1: 'csrSignatureParams'\n }]\n }, {\n // signature\n name: 'CertificationRequest.signature',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n captureBitStringValue: 'csrSignature'\n }\n ]\n};\n\n/**\n * Converts an RDNSequence of ASN.1 DER-encoded RelativeDistinguishedName\n * sets into an array with objects that have type and value properties.\n *\n * @param rdn the RDNSequence to convert.\n * @param md a message digest to append type and value to if provided.\n */\npki.RDNAttributesAsArray = function(rdn, md) {\n var rval = [];\n\n // each value in 'rdn' in is a SET of RelativeDistinguishedName\n var set, attr, obj;\n for(var si = 0; si < rdn.value.length; ++si) {\n // get the RelativeDistinguishedName set\n set = rdn.value[si];\n\n // each value in the SET is an AttributeTypeAndValue sequence\n // containing first a type (an OID) and second a value (defined by\n // the OID)\n for(var i = 0; i < set.value.length; ++i) {\n obj = {};\n attr = set.value[i];\n obj.type = asn1.derToOid(attr.value[0].value);\n obj.value = attr.value[1].value;\n obj.valueTagClass = attr.value[1].type;\n // if the OID is known, get its name and short name\n if(obj.type in oids) {\n obj.name = oids[obj.type];\n if(obj.name in _shortNames) {\n obj.shortName = _shortNames[obj.name];\n }\n }\n if(md) {\n md.update(obj.type);\n md.update(obj.value);\n }\n rval.push(obj);\n }\n }\n\n return rval;\n};\n\n/**\n * Converts ASN.1 CRIAttributes into an array with objects that have type and\n * value properties.\n *\n * @param attributes the CRIAttributes to convert.\n */\npki.CRIAttributesAsArray = function(attributes) {\n var rval = [];\n\n // each value in 'attributes' in is a SEQUENCE with an OID and a SET\n for(var si = 0; si < attributes.length; ++si) {\n // get the attribute sequence\n var seq = attributes[si];\n\n // each value in the SEQUENCE containing first a type (an OID) and\n // second a set of values (defined by the OID)\n var type = asn1.derToOid(seq.value[0].value);\n var values = seq.value[1].value;\n for(var vi = 0; vi < values.length; ++vi) {\n var obj = {};\n obj.type = type;\n obj.value = values[vi].value;\n obj.valueTagClass = values[vi].type;\n // if the OID is known, get its name and short name\n if(obj.type in oids) {\n obj.name = oids[obj.type];\n if(obj.name in _shortNames) {\n obj.shortName = _shortNames[obj.name];\n }\n }\n // parse extensions\n if(obj.type === oids.extensionRequest) {\n obj.extensions = [];\n for(var ei = 0; ei < obj.value.length; ++ei) {\n obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei]));\n }\n }\n rval.push(obj);\n }\n }\n\n return rval;\n};\n\n/**\n * Gets an issuer or subject attribute from its name, type, or short name.\n *\n * @param obj the issuer or subject object.\n * @param options a short name string or an object with:\n * shortName the short name for the attribute.\n * name the name for the attribute.\n * type the type for the attribute.\n *\n * @return the attribute.\n */\nfunction _getAttribute(obj, options) {\n if(typeof options === 'string') {\n options = {shortName: options};\n }\n\n var rval = null;\n var attr;\n for(var i = 0; rval === null && i < obj.attributes.length; ++i) {\n attr = obj.attributes[i];\n if(options.type && options.type === attr.type) {\n rval = attr;\n } else if(options.name && options.name === attr.name) {\n rval = attr;\n } else if(options.shortName && options.shortName === attr.shortName) {\n rval = attr;\n }\n }\n return rval;\n}\n\n/**\n * Converts signature parameters from ASN.1 structure.\n *\n * Currently only RSASSA-PSS supported. The PKCS#1 v1.5 signature scheme had\n * no parameters.\n *\n * RSASSA-PSS-params ::= SEQUENCE {\n * hashAlgorithm [0] HashAlgorithm DEFAULT\n * sha1Identifier,\n * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT\n * mgf1SHA1Identifier,\n * saltLength [2] INTEGER DEFAULT 20,\n * trailerField [3] INTEGER DEFAULT 1\n * }\n *\n * HashAlgorithm ::= AlgorithmIdentifier\n *\n * MaskGenAlgorithm ::= AlgorithmIdentifier\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * @param oid The OID specifying the signature algorithm\n * @param obj The ASN.1 structure holding the parameters\n * @param fillDefaults Whether to use return default values where omitted\n * @return signature parameter object\n */\nvar _readSignatureParameters = function(oid, obj, fillDefaults) {\n var params = {};\n\n if(oid !== oids['RSASSA-PSS']) {\n return params;\n }\n\n if(fillDefaults) {\n params = {\n hash: {\n algorithmOid: oids['sha1']\n },\n mgf: {\n algorithmOid: oids['mgf1'],\n hash: {\n algorithmOid: oids['sha1']\n }\n },\n saltLength: 20\n };\n }\n\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) {\n var error = new Error('Cannot read RSASSA-PSS parameter block.');\n error.errors = errors;\n throw error;\n }\n\n if(capture.hashOid !== undefined) {\n params.hash = params.hash || {};\n params.hash.algorithmOid = asn1.derToOid(capture.hashOid);\n }\n\n if(capture.maskGenOid !== undefined) {\n params.mgf = params.mgf || {};\n params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid);\n params.mgf.hash = params.mgf.hash || {};\n params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid);\n }\n\n if(capture.saltLength !== undefined) {\n params.saltLength = capture.saltLength.charCodeAt(0);\n }\n\n return params;\n};\n\n/**\n * Create signature digest for OID.\n *\n * @param options\n * signatureOid: the OID specifying the signature algorithm.\n * type: a human readable type for error messages\n * @return a created md instance. throws if unknown oid.\n */\nvar _createSignatureDigest = function(options) {\n switch(oids[options.signatureOid]) {\n case 'sha1WithRSAEncryption':\n // deprecated alias\n case 'sha1WithRSASignature':\n return forge.md.sha1.create();\n case 'md5WithRSAEncryption':\n return forge.md.md5.create();\n case 'sha256WithRSAEncryption':\n return forge.md.sha256.create();\n case 'sha384WithRSAEncryption':\n return forge.md.sha384.create();\n case 'sha512WithRSAEncryption':\n return forge.md.sha512.create();\n case 'RSASSA-PSS':\n return forge.md.sha256.create();\n default:\n var error = new Error(\n 'Could not compute ' + options.type + ' digest. ' +\n 'Unknown signature OID.');\n error.signatureOid = options.signatureOid;\n throw error;\n }\n};\n\n/**\n * Verify signature on certificate or CSR.\n *\n * @param options:\n * certificate the certificate or CSR to verify.\n * md the signature digest.\n * signature the signature\n * @return a created md instance. throws if unknown oid.\n */\nvar _verifySignature = function(options) {\n var cert = options.certificate;\n var scheme;\n\n switch(cert.signatureOid) {\n case oids.sha1WithRSAEncryption:\n // deprecated alias\n case oids.sha1WithRSASignature:\n /* use PKCS#1 v1.5 padding scheme */\n break;\n case oids['RSASSA-PSS']:\n var hash, mgf;\n\n /* initialize mgf */\n hash = oids[cert.signatureParameters.mgf.hash.algorithmOid];\n if(hash === undefined || forge.md[hash] === undefined) {\n var error = new Error('Unsupported MGF hash function.');\n error.oid = cert.signatureParameters.mgf.hash.algorithmOid;\n error.name = hash;\n throw error;\n }\n\n mgf = oids[cert.signatureParameters.mgf.algorithmOid];\n if(mgf === undefined || forge.mgf[mgf] === undefined) {\n var error = new Error('Unsupported MGF function.');\n error.oid = cert.signatureParameters.mgf.algorithmOid;\n error.name = mgf;\n throw error;\n }\n\n mgf = forge.mgf[mgf].create(forge.md[hash].create());\n\n /* initialize hash function */\n hash = oids[cert.signatureParameters.hash.algorithmOid];\n if(hash === undefined || forge.md[hash] === undefined) {\n var error = new Error('Unsupported RSASSA-PSS hash function.');\n error.oid = cert.signatureParameters.hash.algorithmOid;\n error.name = hash;\n throw error;\n }\n\n scheme = forge.pss.create(\n forge.md[hash].create(), mgf, cert.signatureParameters.saltLength\n );\n break;\n }\n\n // verify signature on cert using public key\n return cert.publicKey.verify(\n options.md.digest().getBytes(), options.signature, scheme\n );\n};\n\n/**\n * Converts an X.509 certificate from PEM format.\n *\n * Note: If the certificate is to be verified then compute hash should\n * be set to true. This will scan the TBSCertificate part of the ASN.1\n * object while it is converted so it doesn't need to be converted back\n * to ASN.1-DER-encoding later.\n *\n * @param pem the PEM-formatted certificate.\n * @param computeHash true to compute the hash for verification.\n * @param strict true to be strict when checking ASN.1 value lengths, false to\n * allow truncated values (default: true).\n *\n * @return the certificate.\n */\npki.certificateFromPem = function(pem, computeHash, strict) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'CERTIFICATE' &&\n msg.type !== 'X509 CERTIFICATE' &&\n msg.type !== 'TRUSTED CERTIFICATE') {\n var error = new Error(\n 'Could not convert certificate from PEM; PEM header type ' +\n 'is not \"CERTIFICATE\", \"X509 CERTIFICATE\", or \"TRUSTED CERTIFICATE\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error(\n 'Could not convert certificate from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body, strict);\n\n return pki.certificateFromAsn1(obj, computeHash);\n};\n\n/**\n * Converts an X.509 certificate to PEM format.\n *\n * @param cert the certificate.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted certificate.\n */\npki.certificateToPem = function(cert, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'CERTIFICATE',\n body: asn1.toDer(pki.certificateToAsn1(cert)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts an RSA public key from PEM format.\n *\n * @param pem the PEM-formatted public key.\n *\n * @return the public key.\n */\npki.publicKeyFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'PUBLIC KEY' && msg.type !== 'RSA PUBLIC KEY') {\n var error = new Error('Could not convert public key from PEM; PEM header ' +\n 'type is not \"PUBLIC KEY\" or \"RSA PUBLIC KEY\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert public key from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body);\n\n return pki.publicKeyFromAsn1(obj);\n};\n\n/**\n * Converts an RSA public key to PEM format (using a SubjectPublicKeyInfo).\n *\n * @param key the public key.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted public key.\n */\npki.publicKeyToPem = function(key, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'PUBLIC KEY',\n body: asn1.toDer(pki.publicKeyToAsn1(key)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts an RSA public key to PEM format (using an RSAPublicKey).\n *\n * @param key the public key.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted public key.\n */\npki.publicKeyToRSAPublicKeyPem = function(key, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'RSA PUBLIC KEY',\n body: asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Gets a fingerprint for the given public key.\n *\n * @param options the options to use.\n * [md] the message digest object to use (defaults to forge.md.sha1).\n * [type] the type of fingerprint, such as 'RSAPublicKey',\n * 'SubjectPublicKeyInfo' (defaults to 'RSAPublicKey').\n * [encoding] an alternative output encoding, such as 'hex'\n * (defaults to none, outputs a byte buffer).\n * [delimiter] the delimiter to use between bytes for 'hex' encoded\n * output, eg: ':' (defaults to none).\n *\n * @return the fingerprint as a byte buffer or other encoding based on options.\n */\npki.getPublicKeyFingerprint = function(key, options) {\n options = options || {};\n var md = options.md || forge.md.sha1.create();\n var type = options.type || 'RSAPublicKey';\n\n var bytes;\n switch(type) {\n case 'RSAPublicKey':\n bytes = asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes();\n break;\n case 'SubjectPublicKeyInfo':\n bytes = asn1.toDer(pki.publicKeyToAsn1(key)).getBytes();\n break;\n default:\n throw new Error('Unknown fingerprint type \"' + options.type + '\".');\n }\n\n // hash public key bytes\n md.start();\n md.update(bytes);\n var digest = md.digest();\n if(options.encoding === 'hex') {\n var hex = digest.toHex();\n if(options.delimiter) {\n return hex.match(/.{2}/g).join(options.delimiter);\n }\n return hex;\n } else if(options.encoding === 'binary') {\n return digest.getBytes();\n } else if(options.encoding) {\n throw new Error('Unknown encoding \"' + options.encoding + '\".');\n }\n return digest;\n};\n\n/**\n * Converts a PKCS#10 certification request (CSR) from PEM format.\n *\n * Note: If the certification request is to be verified then compute hash\n * should be set to true. This will scan the CertificationRequestInfo part of\n * the ASN.1 object while it is converted so it doesn't need to be converted\n * back to ASN.1-DER-encoding later.\n *\n * @param pem the PEM-formatted certificate.\n * @param computeHash true to compute the hash for verification.\n * @param strict true to be strict when checking ASN.1 value lengths, false to\n * allow truncated values (default: true).\n *\n * @return the certification request (CSR).\n */\npki.certificationRequestFromPem = function(pem, computeHash, strict) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'CERTIFICATE REQUEST') {\n var error = new Error('Could not convert certification request from PEM; ' +\n 'PEM header type is not \"CERTIFICATE REQUEST\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert certification request from PEM; ' +\n 'PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body, strict);\n\n return pki.certificationRequestFromAsn1(obj, computeHash);\n};\n\n/**\n * Converts a PKCS#10 certification request (CSR) to PEM format.\n *\n * @param csr the certification request.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted certification request.\n */\npki.certificationRequestToPem = function(csr, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'CERTIFICATE REQUEST',\n body: asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Creates an empty X.509v3 RSA certificate.\n *\n * @return the certificate.\n */\npki.createCertificate = function() {\n var cert = {};\n cert.version = 0x02;\n cert.serialNumber = '00';\n cert.signatureOid = null;\n cert.signature = null;\n cert.siginfo = {};\n cert.siginfo.algorithmOid = null;\n cert.validity = {};\n cert.validity.notBefore = new Date();\n cert.validity.notAfter = new Date();\n\n cert.issuer = {};\n cert.issuer.getField = function(sn) {\n return _getAttribute(cert.issuer, sn);\n };\n cert.issuer.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.issuer.attributes.push(attr);\n };\n cert.issuer.attributes = [];\n cert.issuer.hash = null;\n\n cert.subject = {};\n cert.subject.getField = function(sn) {\n return _getAttribute(cert.subject, sn);\n };\n cert.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.subject.attributes.push(attr);\n };\n cert.subject.attributes = [];\n cert.subject.hash = null;\n\n cert.extensions = [];\n cert.publicKey = null;\n cert.md = null;\n\n /**\n * Sets the subject of this certificate.\n *\n * @param attrs the array of subject attributes to use.\n * @param uniqueId an optional a unique ID to use.\n */\n cert.setSubject = function(attrs, uniqueId) {\n // set new attributes, clear hash\n _fillMissingFields(attrs);\n cert.subject.attributes = attrs;\n delete cert.subject.uniqueId;\n if(uniqueId) {\n // TODO: support arbitrary bit length ids\n cert.subject.uniqueId = uniqueId;\n }\n cert.subject.hash = null;\n };\n\n /**\n * Sets the issuer of this certificate.\n *\n * @param attrs the array of issuer attributes to use.\n * @param uniqueId an optional a unique ID to use.\n */\n cert.setIssuer = function(attrs, uniqueId) {\n // set new attributes, clear hash\n _fillMissingFields(attrs);\n cert.issuer.attributes = attrs;\n delete cert.issuer.uniqueId;\n if(uniqueId) {\n // TODO: support arbitrary bit length ids\n cert.issuer.uniqueId = uniqueId;\n }\n cert.issuer.hash = null;\n };\n\n /**\n * Sets the extensions of this certificate.\n *\n * @param exts the array of extensions to use.\n */\n cert.setExtensions = function(exts) {\n for(var i = 0; i < exts.length; ++i) {\n _fillMissingExtensionFields(exts[i], {cert: cert});\n }\n // set new extensions\n cert.extensions = exts;\n };\n\n /**\n * Gets an extension by its name or id.\n *\n * @param options the name to use or an object with:\n * name the name to use.\n * id the id to use.\n *\n * @return the extension or null if not found.\n */\n cert.getExtension = function(options) {\n if(typeof options === 'string') {\n options = {name: options};\n }\n\n var rval = null;\n var ext;\n for(var i = 0; rval === null && i < cert.extensions.length; ++i) {\n ext = cert.extensions[i];\n if(options.id && ext.id === options.id) {\n rval = ext;\n } else if(options.name && ext.name === options.name) {\n rval = ext;\n }\n }\n return rval;\n };\n\n /**\n * Signs this certificate using the given private key.\n *\n * @param key the private key to sign with.\n * @param md the message digest object to use (defaults to forge.md.sha1).\n */\n cert.sign = function(key, md) {\n // TODO: get signature OID from private key\n cert.md = md || forge.md.sha1.create();\n var algorithmOid = oids[cert.md.algorithm + 'WithRSAEncryption'];\n if(!algorithmOid) {\n var error = new Error('Could not compute certificate digest. ' +\n 'Unknown message digest algorithm OID.');\n error.algorithm = cert.md.algorithm;\n throw error;\n }\n cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid;\n\n // get TBSCertificate, convert to DER\n cert.tbsCertificate = pki.getTBSCertificate(cert);\n var bytes = asn1.toDer(cert.tbsCertificate);\n\n // digest and sign\n cert.md.update(bytes.getBytes());\n cert.signature = key.sign(cert.md);\n };\n\n /**\n * Attempts verify the signature on the passed certificate using this\n * certificate's public key.\n *\n * @param child the certificate to verify.\n *\n * @return true if verified, false if not.\n */\n cert.verify = function(child) {\n var rval = false;\n\n if(!cert.issued(child)) {\n var issuer = child.issuer;\n var subject = cert.subject;\n var error = new Error(\n 'The parent certificate did not issue the given child ' +\n 'certificate; the child certificate\\'s issuer does not match the ' +\n 'parent\\'s subject.');\n error.expectedIssuer = subject.attributes;\n error.actualIssuer = issuer.attributes;\n throw error;\n }\n\n var md = child.md;\n if(md === null) {\n // create digest for OID signature types\n md = _createSignatureDigest({\n signatureOid: child.signatureOid,\n type: 'certificate'\n });\n\n // produce DER formatted TBSCertificate and digest it\n var tbsCertificate = child.tbsCertificate || pki.getTBSCertificate(child);\n var bytes = asn1.toDer(tbsCertificate);\n md.update(bytes.getBytes());\n }\n\n if(md !== null) {\n rval = _verifySignature({\n certificate: cert, md: md, signature: child.signature\n });\n }\n\n return rval;\n };\n\n /**\n * Returns true if this certificate's issuer matches the passed\n * certificate's subject. Note that no signature check is performed.\n *\n * @param parent the certificate to check.\n *\n * @return true if this certificate's issuer matches the passed certificate's\n * subject.\n */\n cert.isIssuer = function(parent) {\n var rval = false;\n\n var i = cert.issuer;\n var s = parent.subject;\n\n // compare hashes if present\n if(i.hash && s.hash) {\n rval = (i.hash === s.hash);\n } else if(i.attributes.length === s.attributes.length) {\n // all attributes are the same so issuer matches subject\n rval = true;\n var iattr, sattr;\n for(var n = 0; rval && n < i.attributes.length; ++n) {\n iattr = i.attributes[n];\n sattr = s.attributes[n];\n if(iattr.type !== sattr.type || iattr.value !== sattr.value) {\n // attribute mismatch\n rval = false;\n }\n }\n }\n\n return rval;\n };\n\n /**\n * Returns true if this certificate's subject matches the issuer of the\n * given certificate). Note that not signature check is performed.\n *\n * @param child the certificate to check.\n *\n * @return true if this certificate's subject matches the passed\n * certificate's issuer.\n */\n cert.issued = function(child) {\n return child.isIssuer(cert);\n };\n\n /**\n * Generates the subjectKeyIdentifier for this certificate as byte buffer.\n *\n * @return the subjectKeyIdentifier for this certificate as byte buffer.\n */\n cert.generateSubjectKeyIdentifier = function() {\n /* See: 4.2.1.2 section of the the RFC3280, keyIdentifier is either:\n\n (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the\n value of the BIT STRING subjectPublicKey (excluding the tag,\n length, and number of unused bits).\n\n (2) The keyIdentifier is composed of a four bit type field with\n the value 0100 followed by the least significant 60 bits of the\n SHA-1 hash of the value of the BIT STRING subjectPublicKey\n (excluding the tag, length, and number of unused bit string bits).\n */\n\n // skipping the tag, length, and number of unused bits is the same\n // as just using the RSAPublicKey (for RSA keys, which are the\n // only ones supported)\n return pki.getPublicKeyFingerprint(cert.publicKey, {type: 'RSAPublicKey'});\n };\n\n /**\n * Verifies the subjectKeyIdentifier extension value for this certificate\n * against its public key. If no extension is found, false will be\n * returned.\n *\n * @return true if verified, false if not.\n */\n cert.verifySubjectKeyIdentifier = function() {\n var oid = oids['subjectKeyIdentifier'];\n for(var i = 0; i < cert.extensions.length; ++i) {\n var ext = cert.extensions[i];\n if(ext.id === oid) {\n var ski = cert.generateSubjectKeyIdentifier().getBytes();\n return (forge.util.hexToBytes(ext.subjectKeyIdentifier) === ski);\n }\n }\n return false;\n };\n\n return cert;\n};\n\n/**\n * Converts an X.509v3 RSA certificate from an ASN.1 object.\n *\n * Note: If the certificate is to be verified then compute hash should\n * be set to true. There is currently no implementation for converting\n * a certificate back to ASN.1 so the TBSCertificate part of the ASN.1\n * object needs to be scanned before the cert object is created.\n *\n * @param obj the asn1 representation of an X.509v3 RSA certificate.\n * @param computeHash true to compute the hash for verification.\n *\n * @return the certificate.\n */\npki.certificateFromAsn1 = function(obj, computeHash) {\n // validate certificate and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, x509CertificateValidator, capture, errors)) {\n var error = new Error('Cannot read X.509 certificate. ' +\n 'ASN.1 object is not an X509v3 Certificate.');\n error.errors = errors;\n throw error;\n }\n\n // get oid\n var oid = asn1.derToOid(capture.publicKeyOid);\n if(oid !== pki.oids.rsaEncryption) {\n throw new Error('Cannot read public key. OID is not RSA.');\n }\n\n // create certificate\n var cert = pki.createCertificate();\n cert.version = capture.certVersion ?\n capture.certVersion.charCodeAt(0) : 0;\n var serial = forge.util.createBuffer(capture.certSerialNumber);\n cert.serialNumber = serial.toHex();\n cert.signatureOid = forge.asn1.derToOid(capture.certSignatureOid);\n cert.signatureParameters = _readSignatureParameters(\n cert.signatureOid, capture.certSignatureParams, true);\n cert.siginfo.algorithmOid = forge.asn1.derToOid(capture.certinfoSignatureOid);\n cert.siginfo.parameters = _readSignatureParameters(cert.siginfo.algorithmOid,\n capture.certinfoSignatureParams, false);\n cert.signature = capture.certSignature;\n\n var validity = [];\n if(capture.certValidity1UTCTime !== undefined) {\n validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime));\n }\n if(capture.certValidity2GeneralizedTime !== undefined) {\n validity.push(asn1.generalizedTimeToDate(\n capture.certValidity2GeneralizedTime));\n }\n if(capture.certValidity3UTCTime !== undefined) {\n validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime));\n }\n if(capture.certValidity4GeneralizedTime !== undefined) {\n validity.push(asn1.generalizedTimeToDate(\n capture.certValidity4GeneralizedTime));\n }\n if(validity.length > 2) {\n throw new Error('Cannot read notBefore/notAfter validity times; more ' +\n 'than two times were provided in the certificate.');\n }\n if(validity.length < 2) {\n throw new Error('Cannot read notBefore/notAfter validity times; they ' +\n 'were not provided as either UTCTime or GeneralizedTime.');\n }\n cert.validity.notBefore = validity[0];\n cert.validity.notAfter = validity[1];\n\n // keep TBSCertificate to preserve signature when exporting\n cert.tbsCertificate = capture.tbsCertificate;\n\n if(computeHash) {\n // create digest for OID signature type\n cert.md = _createSignatureDigest({\n signatureOid: cert.signatureOid,\n type: 'certificate'\n });\n\n // produce DER formatted TBSCertificate and digest it\n var bytes = asn1.toDer(cert.tbsCertificate);\n cert.md.update(bytes.getBytes());\n }\n\n // handle issuer, build issuer message digest\n var imd = forge.md.sha1.create();\n var ibytes = asn1.toDer(capture.certIssuer);\n imd.update(ibytes.getBytes());\n cert.issuer.getField = function(sn) {\n return _getAttribute(cert.issuer, sn);\n };\n cert.issuer.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.issuer.attributes.push(attr);\n };\n cert.issuer.attributes = pki.RDNAttributesAsArray(capture.certIssuer);\n if(capture.certIssuerUniqueId) {\n cert.issuer.uniqueId = capture.certIssuerUniqueId;\n }\n cert.issuer.hash = imd.digest().toHex();\n\n // handle subject, build subject message digest\n var smd = forge.md.sha1.create();\n var sbytes = asn1.toDer(capture.certSubject);\n smd.update(sbytes.getBytes());\n cert.subject.getField = function(sn) {\n return _getAttribute(cert.subject, sn);\n };\n cert.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.subject.attributes.push(attr);\n };\n cert.subject.attributes = pki.RDNAttributesAsArray(capture.certSubject);\n if(capture.certSubjectUniqueId) {\n cert.subject.uniqueId = capture.certSubjectUniqueId;\n }\n cert.subject.hash = smd.digest().toHex();\n\n // handle extensions\n if(capture.certExtensions) {\n cert.extensions = pki.certificateExtensionsFromAsn1(capture.certExtensions);\n } else {\n cert.extensions = [];\n }\n\n // convert RSA public key from ASN.1\n cert.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);\n\n return cert;\n};\n\n/**\n * Converts an ASN.1 extensions object (with extension sequences as its\n * values) into an array of extension objects with types and values.\n *\n * Supported extensions:\n *\n * id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 }\n * KeyUsage ::= BIT STRING {\n * digitalSignature (0),\n * nonRepudiation (1),\n * keyEncipherment (2),\n * dataEncipherment (3),\n * keyAgreement (4),\n * keyCertSign (5),\n * cRLSign (6),\n * encipherOnly (7),\n * decipherOnly (8)\n * }\n *\n * id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 }\n * BasicConstraints ::= SEQUENCE {\n * cA BOOLEAN DEFAULT FALSE,\n * pathLenConstraint INTEGER (0..MAX) OPTIONAL\n * }\n *\n * subjectAltName EXTENSION ::= {\n * SYNTAX GeneralNames\n * IDENTIFIED BY id-ce-subjectAltName\n * }\n *\n * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName\n *\n * GeneralName ::= CHOICE {\n * otherName [0] INSTANCE OF OTHER-NAME,\n * rfc822Name [1] IA5String,\n * dNSName [2] IA5String,\n * x400Address [3] ORAddress,\n * directoryName [4] Name,\n * ediPartyName [5] EDIPartyName,\n * uniformResourceIdentifier [6] IA5String,\n * IPAddress [7] OCTET STRING,\n * registeredID [8] OBJECT IDENTIFIER\n * }\n *\n * OTHER-NAME ::= TYPE-IDENTIFIER\n *\n * EDIPartyName ::= SEQUENCE {\n * nameAssigner [0] DirectoryString {ub-name} OPTIONAL,\n * partyName [1] DirectoryString {ub-name}\n * }\n *\n * @param exts the extensions ASN.1 with extension sequences to parse.\n *\n * @return the array.\n */\npki.certificateExtensionsFromAsn1 = function(exts) {\n var rval = [];\n for(var i = 0; i < exts.value.length; ++i) {\n // get extension sequence\n var extseq = exts.value[i];\n for(var ei = 0; ei < extseq.value.length; ++ei) {\n rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei]));\n }\n }\n\n return rval;\n};\n\n/**\n * Parses a single certificate extension from ASN.1.\n *\n * @param ext the extension in ASN.1 format.\n *\n * @return the parsed extension as an object.\n */\npki.certificateExtensionFromAsn1 = function(ext) {\n // an extension has:\n // [0] extnID OBJECT IDENTIFIER\n // [1] critical BOOLEAN DEFAULT FALSE\n // [2] extnValue OCTET STRING\n var e = {};\n e.id = asn1.derToOid(ext.value[0].value);\n e.critical = false;\n if(ext.value[1].type === asn1.Type.BOOLEAN) {\n e.critical = (ext.value[1].value.charCodeAt(0) !== 0x00);\n e.value = ext.value[2].value;\n } else {\n e.value = ext.value[1].value;\n }\n // if the oid is known, get its name\n if(e.id in oids) {\n e.name = oids[e.id];\n\n // handle key usage\n if(e.name === 'keyUsage') {\n // get value as BIT STRING\n var ev = asn1.fromDer(e.value);\n var b2 = 0x00;\n var b3 = 0x00;\n if(ev.value.length > 1) {\n // skip first byte, just indicates unused bits which\n // will be padded with 0s anyway\n // get bytes with flag bits\n b2 = ev.value.charCodeAt(1);\n b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0;\n }\n // set flags\n e.digitalSignature = (b2 & 0x80) === 0x80;\n e.nonRepudiation = (b2 & 0x40) === 0x40;\n e.keyEncipherment = (b2 & 0x20) === 0x20;\n e.dataEncipherment = (b2 & 0x10) === 0x10;\n e.keyAgreement = (b2 & 0x08) === 0x08;\n e.keyCertSign = (b2 & 0x04) === 0x04;\n e.cRLSign = (b2 & 0x02) === 0x02;\n e.encipherOnly = (b2 & 0x01) === 0x01;\n e.decipherOnly = (b3 & 0x80) === 0x80;\n } else if(e.name === 'basicConstraints') {\n // handle basic constraints\n // get value as SEQUENCE\n var ev = asn1.fromDer(e.value);\n // get cA BOOLEAN flag (defaults to false)\n if(ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) {\n e.cA = (ev.value[0].value.charCodeAt(0) !== 0x00);\n } else {\n e.cA = false;\n }\n // get path length constraint\n var value = null;\n if(ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) {\n value = ev.value[0].value;\n } else if(ev.value.length > 1) {\n value = ev.value[1].value;\n }\n if(value !== null) {\n e.pathLenConstraint = asn1.derToInteger(value);\n }\n } else if(e.name === 'extKeyUsage') {\n // handle extKeyUsage\n // value is a SEQUENCE of OIDs\n var ev = asn1.fromDer(e.value);\n for(var vi = 0; vi < ev.value.length; ++vi) {\n var oid = asn1.derToOid(ev.value[vi].value);\n if(oid in oids) {\n e[oids[oid]] = true;\n } else {\n e[oid] = true;\n }\n }\n } else if(e.name === 'nsCertType') {\n // handle nsCertType\n // get value as BIT STRING\n var ev = asn1.fromDer(e.value);\n var b2 = 0x00;\n if(ev.value.length > 1) {\n // skip first byte, just indicates unused bits which\n // will be padded with 0s anyway\n // get bytes with flag bits\n b2 = ev.value.charCodeAt(1);\n }\n // set flags\n e.client = (b2 & 0x80) === 0x80;\n e.server = (b2 & 0x40) === 0x40;\n e.email = (b2 & 0x20) === 0x20;\n e.objsign = (b2 & 0x10) === 0x10;\n e.reserved = (b2 & 0x08) === 0x08;\n e.sslCA = (b2 & 0x04) === 0x04;\n e.emailCA = (b2 & 0x02) === 0x02;\n e.objCA = (b2 & 0x01) === 0x01;\n } else if(\n e.name === 'subjectAltName' ||\n e.name === 'issuerAltName') {\n // handle subjectAltName/issuerAltName\n e.altNames = [];\n\n // ev is a SYNTAX SEQUENCE\n var gn;\n var ev = asn1.fromDer(e.value);\n for(var n = 0; n < ev.value.length; ++n) {\n // get GeneralName\n gn = ev.value[n];\n\n var altName = {\n type: gn.type,\n value: gn.value\n };\n e.altNames.push(altName);\n\n // Note: Support for types 1,2,6,7,8\n switch(gn.type) {\n // rfc822Name\n case 1:\n // dNSName\n case 2:\n // uniformResourceIdentifier (URI)\n case 6:\n break;\n // IPAddress\n case 7:\n // convert to IPv4/IPv6 string representation\n altName.ip = forge.util.bytesToIP(gn.value);\n break;\n // registeredID\n case 8:\n altName.oid = asn1.derToOid(gn.value);\n break;\n default:\n // unsupported\n }\n }\n } else if(e.name === 'subjectKeyIdentifier') {\n // value is an OCTETSTRING w/the hash of the key-type specific\n // public key structure (eg: RSAPublicKey)\n var ev = asn1.fromDer(e.value);\n e.subjectKeyIdentifier = forge.util.bytesToHex(ev.value);\n }\n }\n return e;\n};\n\n/**\n * Converts a PKCS#10 certification request (CSR) from an ASN.1 object.\n *\n * Note: If the certification request is to be verified then compute hash\n * should be set to true. There is currently no implementation for converting\n * a certificate back to ASN.1 so the CertificationRequestInfo part of the\n * ASN.1 object needs to be scanned before the csr object is created.\n *\n * @param obj the asn1 representation of a PKCS#10 certification request (CSR).\n * @param computeHash true to compute the hash for verification.\n *\n * @return the certification request (CSR).\n */\npki.certificationRequestFromAsn1 = function(obj, computeHash) {\n // validate certification request and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, certificationRequestValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#10 certificate request. ' +\n 'ASN.1 object is not a PKCS#10 CertificationRequest.');\n error.errors = errors;\n throw error;\n }\n\n // get oid\n var oid = asn1.derToOid(capture.publicKeyOid);\n if(oid !== pki.oids.rsaEncryption) {\n throw new Error('Cannot read public key. OID is not RSA.');\n }\n\n // create certification request\n var csr = pki.createCertificationRequest();\n csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0;\n csr.signatureOid = forge.asn1.derToOid(capture.csrSignatureOid);\n csr.signatureParameters = _readSignatureParameters(\n csr.signatureOid, capture.csrSignatureParams, true);\n csr.siginfo.algorithmOid = forge.asn1.derToOid(capture.csrSignatureOid);\n csr.siginfo.parameters = _readSignatureParameters(\n csr.siginfo.algorithmOid, capture.csrSignatureParams, false);\n csr.signature = capture.csrSignature;\n\n // keep CertificationRequestInfo to preserve signature when exporting\n csr.certificationRequestInfo = capture.certificationRequestInfo;\n\n if(computeHash) {\n // create digest for OID signature type\n csr.md = _createSignatureDigest({\n signatureOid: csr.signatureOid,\n type: 'certification request'\n });\n\n // produce DER formatted CertificationRequestInfo and digest it\n var bytes = asn1.toDer(csr.certificationRequestInfo);\n csr.md.update(bytes.getBytes());\n }\n\n // handle subject, build subject message digest\n var smd = forge.md.sha1.create();\n csr.subject.getField = function(sn) {\n return _getAttribute(csr.subject, sn);\n };\n csr.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n csr.subject.attributes.push(attr);\n };\n csr.subject.attributes = pki.RDNAttributesAsArray(\n capture.certificationRequestInfoSubject, smd);\n csr.subject.hash = smd.digest().toHex();\n\n // convert RSA public key from ASN.1\n csr.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);\n\n // convert attributes from ASN.1\n csr.getAttribute = function(sn) {\n return _getAttribute(csr, sn);\n };\n csr.addAttribute = function(attr) {\n _fillMissingFields([attr]);\n csr.attributes.push(attr);\n };\n csr.attributes = pki.CRIAttributesAsArray(\n capture.certificationRequestInfoAttributes || []);\n\n return csr;\n};\n\n/**\n * Creates an empty certification request (a CSR or certificate signing\n * request). Once created, its public key and attributes can be set and then\n * it can be signed.\n *\n * @return the empty certification request.\n */\npki.createCertificationRequest = function() {\n var csr = {};\n csr.version = 0x00;\n csr.signatureOid = null;\n csr.signature = null;\n csr.siginfo = {};\n csr.siginfo.algorithmOid = null;\n\n csr.subject = {};\n csr.subject.getField = function(sn) {\n return _getAttribute(csr.subject, sn);\n };\n csr.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n csr.subject.attributes.push(attr);\n };\n csr.subject.attributes = [];\n csr.subject.hash = null;\n\n csr.publicKey = null;\n csr.attributes = [];\n csr.getAttribute = function(sn) {\n return _getAttribute(csr, sn);\n };\n csr.addAttribute = function(attr) {\n _fillMissingFields([attr]);\n csr.attributes.push(attr);\n };\n csr.md = null;\n\n /**\n * Sets the subject of this certification request.\n *\n * @param attrs the array of subject attributes to use.\n */\n csr.setSubject = function(attrs) {\n // set new attributes\n _fillMissingFields(attrs);\n csr.subject.attributes = attrs;\n csr.subject.hash = null;\n };\n\n /**\n * Sets the attributes of this certification request.\n *\n * @param attrs the array of attributes to use.\n */\n csr.setAttributes = function(attrs) {\n // set new attributes\n _fillMissingFields(attrs);\n csr.attributes = attrs;\n };\n\n /**\n * Signs this certification request using the given private key.\n *\n * @param key the private key to sign with.\n * @param md the message digest object to use (defaults to forge.md.sha1).\n */\n csr.sign = function(key, md) {\n // TODO: get signature OID from private key\n csr.md = md || forge.md.sha1.create();\n var algorithmOid = oids[csr.md.algorithm + 'WithRSAEncryption'];\n if(!algorithmOid) {\n var error = new Error('Could not compute certification request digest. ' +\n 'Unknown message digest algorithm OID.');\n error.algorithm = csr.md.algorithm;\n throw error;\n }\n csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid;\n\n // get CertificationRequestInfo, convert to DER\n csr.certificationRequestInfo = pki.getCertificationRequestInfo(csr);\n var bytes = asn1.toDer(csr.certificationRequestInfo);\n\n // digest and sign\n csr.md.update(bytes.getBytes());\n csr.signature = key.sign(csr.md);\n };\n\n /**\n * Attempts verify the signature on the passed certification request using\n * its public key.\n *\n * A CSR that has been exported to a file in PEM format can be verified using\n * OpenSSL using this command:\n *\n * openssl req -in <the-csr-pem-file> -verify -noout -text\n *\n * @return true if verified, false if not.\n */\n csr.verify = function() {\n var rval = false;\n\n var md = csr.md;\n if(md === null) {\n md = _createSignatureDigest({\n signatureOid: csr.signatureOid,\n type: 'certification request'\n });\n\n // produce DER formatted CertificationRequestInfo and digest it\n var cri = csr.certificationRequestInfo ||\n pki.getCertificationRequestInfo(csr);\n var bytes = asn1.toDer(cri);\n md.update(bytes.getBytes());\n }\n\n if(md !== null) {\n rval = _verifySignature({\n certificate: csr, md: md, signature: csr.signature\n });\n }\n\n return rval;\n };\n\n return csr;\n};\n\n/**\n * Converts an X.509 subject or issuer to an ASN.1 RDNSequence.\n *\n * @param obj the subject or issuer (distinguished name).\n *\n * @return the ASN.1 RDNSequence.\n */\nfunction _dnToAsn1(obj) {\n // create an empty RDNSequence\n var rval = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // iterate over attributes\n var attr, set;\n var attrs = obj.attributes;\n for(var i = 0; i < attrs.length; ++i) {\n attr = attrs[i];\n var value = attr.value;\n\n // reuse tag class for attribute value if available\n var valueTagClass = asn1.Type.PRINTABLESTRING;\n if('valueTagClass' in attr) {\n valueTagClass = attr.valueTagClass;\n\n if(valueTagClass === asn1.Type.UTF8) {\n value = forge.util.encodeUtf8(value);\n }\n // FIXME: handle more encodings\n }\n\n // create a RelativeDistinguishedName set\n // each value in the set is an AttributeTypeAndValue first\n // containing the type (an OID) and second the value\n set = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AttributeType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.type).getBytes()),\n // AttributeValue\n asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value)\n ])\n ]);\n rval.value.push(set);\n }\n\n return rval;\n}\n\n/**\n * Gets all printable attributes (typically of an issuer or subject) in a\n * simplified JSON format for display.\n *\n * @param attrs the attributes.\n *\n * @return the JSON for display.\n */\nfunction _getAttributesAsJson(attrs) {\n var rval = {};\n for(var i = 0; i < attrs.length; ++i) {\n var attr = attrs[i];\n if(attr.shortName && (\n attr.valueTagClass === asn1.Type.UTF8 ||\n attr.valueTagClass === asn1.Type.PRINTABLESTRING ||\n attr.valueTagClass === asn1.Type.IA5STRING)) {\n var value = attr.value;\n if(attr.valueTagClass === asn1.Type.UTF8) {\n value = forge.util.encodeUtf8(attr.value);\n }\n if(!(attr.shortName in rval)) {\n rval[attr.shortName] = value;\n } else if(forge.util.isArray(rval[attr.shortName])) {\n rval[attr.shortName].push(value);\n } else {\n rval[attr.shortName] = [rval[attr.shortName], value];\n }\n }\n }\n return rval;\n}\n\n/**\n * Fills in missing fields in attributes.\n *\n * @param attrs the attributes to fill missing fields in.\n */\nfunction _fillMissingFields(attrs) {\n var attr;\n for(var i = 0; i < attrs.length; ++i) {\n attr = attrs[i];\n\n // populate missing name\n if(typeof attr.name === 'undefined') {\n if(attr.type && attr.type in pki.oids) {\n attr.name = pki.oids[attr.type];\n } else if(attr.shortName && attr.shortName in _shortNames) {\n attr.name = pki.oids[_shortNames[attr.shortName]];\n }\n }\n\n // populate missing type (OID)\n if(typeof attr.type === 'undefined') {\n if(attr.name && attr.name in pki.oids) {\n attr.type = pki.oids[attr.name];\n } else {\n var error = new Error('Attribute type not specified.');\n error.attribute = attr;\n throw error;\n }\n }\n\n // populate missing shortname\n if(typeof attr.shortName === 'undefined') {\n if(attr.name && attr.name in _shortNames) {\n attr.shortName = _shortNames[attr.name];\n }\n }\n\n // convert extensions to value\n if(attr.type === oids.extensionRequest) {\n attr.valueConstructed = true;\n attr.valueTagClass = asn1.Type.SEQUENCE;\n if(!attr.value && attr.extensions) {\n attr.value = [];\n for(var ei = 0; ei < attr.extensions.length; ++ei) {\n attr.value.push(pki.certificateExtensionToAsn1(\n _fillMissingExtensionFields(attr.extensions[ei])));\n }\n }\n }\n\n if(typeof attr.value === 'undefined') {\n var error = new Error('Attribute value not specified.');\n error.attribute = attr;\n throw error;\n }\n }\n}\n\n/**\n * Fills in missing fields in certificate extensions.\n *\n * @param e the extension.\n * @param [options] the options to use.\n * [cert] the certificate the extensions are for.\n *\n * @return the extension.\n */\nfunction _fillMissingExtensionFields(e, options) {\n options = options || {};\n\n // populate missing name\n if(typeof e.name === 'undefined') {\n if(e.id && e.id in pki.oids) {\n e.name = pki.oids[e.id];\n }\n }\n\n // populate missing id\n if(typeof e.id === 'undefined') {\n if(e.name && e.name in pki.oids) {\n e.id = pki.oids[e.name];\n } else {\n var error = new Error('Extension ID not specified.');\n error.extension = e;\n throw error;\n }\n }\n\n if(typeof e.value !== 'undefined') {\n return e;\n }\n\n // handle missing value:\n\n // value is a BIT STRING\n if(e.name === 'keyUsage') {\n // build flags\n var unused = 0;\n var b2 = 0x00;\n var b3 = 0x00;\n if(e.digitalSignature) {\n b2 |= 0x80;\n unused = 7;\n }\n if(e.nonRepudiation) {\n b2 |= 0x40;\n unused = 6;\n }\n if(e.keyEncipherment) {\n b2 |= 0x20;\n unused = 5;\n }\n if(e.dataEncipherment) {\n b2 |= 0x10;\n unused = 4;\n }\n if(e.keyAgreement) {\n b2 |= 0x08;\n unused = 3;\n }\n if(e.keyCertSign) {\n b2 |= 0x04;\n unused = 2;\n }\n if(e.cRLSign) {\n b2 |= 0x02;\n unused = 1;\n }\n if(e.encipherOnly) {\n b2 |= 0x01;\n unused = 0;\n }\n if(e.decipherOnly) {\n b3 |= 0x80;\n unused = 7;\n }\n\n // create bit string\n var value = String.fromCharCode(unused);\n if(b3 !== 0) {\n value += String.fromCharCode(b2) + String.fromCharCode(b3);\n } else if(b2 !== 0) {\n value += String.fromCharCode(b2);\n }\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);\n } else if(e.name === 'basicConstraints') {\n // basicConstraints is a SEQUENCE\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n // cA BOOLEAN flag defaults to false\n if(e.cA) {\n e.value.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,\n String.fromCharCode(0xFF)));\n }\n if('pathLenConstraint' in e) {\n e.value.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(e.pathLenConstraint).getBytes()));\n }\n } else if(e.name === 'extKeyUsage') {\n // extKeyUsage is a SEQUENCE of OIDs\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n for(var key in e) {\n if(e[key] !== true) {\n continue;\n }\n // key is name in OID map\n if(key in oids) {\n seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,\n false, asn1.oidToDer(oids[key]).getBytes()));\n } else if(key.indexOf('.') !== -1) {\n // assume key is an OID\n seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,\n false, asn1.oidToDer(key).getBytes()));\n }\n }\n } else if(e.name === 'nsCertType') {\n // nsCertType is a BIT STRING\n // build flags\n var unused = 0;\n var b2 = 0x00;\n\n if(e.client) {\n b2 |= 0x80;\n unused = 7;\n }\n if(e.server) {\n b2 |= 0x40;\n unused = 6;\n }\n if(e.email) {\n b2 |= 0x20;\n unused = 5;\n }\n if(e.objsign) {\n b2 |= 0x10;\n unused = 4;\n }\n if(e.reserved) {\n b2 |= 0x08;\n unused = 3;\n }\n if(e.sslCA) {\n b2 |= 0x04;\n unused = 2;\n }\n if(e.emailCA) {\n b2 |= 0x02;\n unused = 1;\n }\n if(e.objCA) {\n b2 |= 0x01;\n unused = 0;\n }\n\n // create bit string\n var value = String.fromCharCode(unused);\n if(b2 !== 0) {\n value += String.fromCharCode(b2);\n }\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);\n } else if(e.name === 'subjectAltName' || e.name === 'issuerAltName') {\n // SYNTAX SEQUENCE\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n var altName;\n for(var n = 0; n < e.altNames.length; ++n) {\n altName = e.altNames[n];\n var value = altName.value;\n // handle IP\n if(altName.type === 7 && altName.ip) {\n value = forge.util.bytesFromIP(altName.ip);\n if(value === null) {\n var error = new Error(\n 'Extension \"ip\" value is not a valid IPv4 or IPv6 address.');\n error.extension = e;\n throw error;\n }\n } else if(altName.type === 8) {\n // handle OID\n if(altName.oid) {\n value = asn1.oidToDer(asn1.oidToDer(altName.oid));\n } else {\n // deprecated ... convert value to OID\n value = asn1.oidToDer(value);\n }\n }\n e.value.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, altName.type, false,\n value));\n }\n } else if(e.name === 'nsComment' && options.cert) {\n // sanity check value is ASCII (req'd) and not too big\n if(!(/^[\\x00-\\x7F]*$/.test(e.comment)) ||\n (e.comment.length < 1) || (e.comment.length > 128)) {\n throw new Error('Invalid \"nsComment\" content.');\n }\n // IA5STRING opaque comment\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.IA5STRING, false, e.comment);\n } else if(e.name === 'subjectKeyIdentifier' && options.cert) {\n var ski = options.cert.generateSubjectKeyIdentifier();\n e.subjectKeyIdentifier = ski.toHex();\n // OCTETSTRING w/digest\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ski.getBytes());\n } else if(e.name === 'authorityKeyIdentifier' && options.cert) {\n // SYNTAX SEQUENCE\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n\n if(e.keyIdentifier) {\n var keyIdentifier = (e.keyIdentifier === true ?\n options.cert.generateSubjectKeyIdentifier().getBytes() :\n e.keyIdentifier);\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier));\n }\n\n if(e.authorityCertIssuer) {\n var authorityCertIssuer = [\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [\n _dnToAsn1(e.authorityCertIssuer === true ?\n options.cert.issuer : e.authorityCertIssuer)\n ])\n ];\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer));\n }\n\n if(e.serialNumber) {\n var serialNumber = forge.util.hexToBytes(e.serialNumber === true ?\n options.cert.serialNumber : e.serialNumber);\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber));\n }\n } else if(e.name === 'cRLDistributionPoints') {\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n\n // Create sub SEQUENCE of DistributionPointName\n var subSeq = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // Create fullName CHOICE\n var fullNameGeneralNames = asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n var altName;\n for(var n = 0; n < e.altNames.length; ++n) {\n altName = e.altNames[n];\n var value = altName.value;\n // handle IP\n if(altName.type === 7 && altName.ip) {\n value = forge.util.bytesFromIP(altName.ip);\n if(value === null) {\n var error = new Error(\n 'Extension \"ip\" value is not a valid IPv4 or IPv6 address.');\n error.extension = e;\n throw error;\n }\n } else if(altName.type === 8) {\n // handle OID\n if(altName.oid) {\n value = asn1.oidToDer(asn1.oidToDer(altName.oid));\n } else {\n // deprecated ... convert value to OID\n value = asn1.oidToDer(value);\n }\n }\n fullNameGeneralNames.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, altName.type, false,\n value));\n }\n\n // Add to the parent SEQUENCE\n subSeq.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames]));\n seq.push(subSeq);\n }\n\n // ensure value has been defined by now\n if(typeof e.value === 'undefined') {\n var error = new Error('Extension value not specified.');\n error.extension = e;\n throw error;\n }\n\n return e;\n}\n\n/**\n * Convert signature parameters object to ASN.1\n *\n * @param {String} oid Signature algorithm OID\n * @param params The signature parametrs object\n * @return ASN.1 object representing signature parameters\n */\nfunction _signatureParametersToAsn1(oid, params) {\n switch(oid) {\n case oids['RSASSA-PSS']:\n var parts = [];\n\n if(params.hash.algorithmOid !== undefined) {\n parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(params.hash.algorithmOid).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ])\n ]));\n }\n\n if(params.mgf.algorithmOid !== undefined) {\n parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(params.mgf.algorithmOid).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ])\n ])\n ]));\n }\n\n if(params.saltLength !== undefined) {\n parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(params.saltLength).getBytes())\n ]));\n }\n\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts);\n\n default:\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '');\n }\n}\n\n/**\n * Converts a certification request's attributes to an ASN.1 set of\n * CRIAttributes.\n *\n * @param csr certification request.\n *\n * @return the ASN.1 set of CRIAttributes.\n */\nfunction _CRIAttributesToAsn1(csr) {\n // create an empty context-specific container\n var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n\n // no attributes, return empty container\n if(csr.attributes.length === 0) {\n return rval;\n }\n\n // each attribute has a sequence with a type and a set of values\n var attrs = csr.attributes;\n for(var i = 0; i < attrs.length; ++i) {\n var attr = attrs[i];\n var value = attr.value;\n\n // reuse tag class for attribute value if available\n var valueTagClass = asn1.Type.UTF8;\n if('valueTagClass' in attr) {\n valueTagClass = attr.valueTagClass;\n }\n if(valueTagClass === asn1.Type.UTF8) {\n value = forge.util.encodeUtf8(value);\n }\n var valueConstructed = false;\n if('valueConstructed' in attr) {\n valueConstructed = attr.valueConstructed;\n }\n // FIXME: handle more encodings\n\n // create a RelativeDistinguishedName set\n // each value in the set is an AttributeTypeAndValue first\n // containing the type (an OID) and second the value\n var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AttributeType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.type).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n // AttributeValue\n asn1.create(\n asn1.Class.UNIVERSAL, valueTagClass, valueConstructed, value)\n ])\n ]);\n rval.value.push(seq);\n }\n\n return rval;\n}\n\nvar jan_1_1950 = new Date('1950-01-01T00:00:00Z');\nvar jan_1_2050 = new Date('2050-01-01T00:00:00Z');\n\n/**\n * Converts a Date object to ASN.1\n * Handles the different format before and after 1st January 2050\n *\n * @param date date object.\n *\n * @return the ASN.1 object representing the date.\n */\nfunction _dateToAsn1(date) {\n if(date >= jan_1_1950 && date < jan_1_2050) {\n return asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false,\n asn1.dateToUtcTime(date));\n } else {\n return asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false,\n asn1.dateToGeneralizedTime(date));\n }\n}\n\n/**\n * Gets the ASN.1 TBSCertificate part of an X.509v3 certificate.\n *\n * @param cert the certificate.\n *\n * @return the asn1 TBSCertificate.\n */\npki.getTBSCertificate = function(cert) {\n // TBSCertificate\n var notBefore = _dateToAsn1(cert.validity.notBefore);\n var notAfter = _dateToAsn1(cert.validity.notAfter);\n var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n // integer\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(cert.version).getBytes())\n ]),\n // serialNumber\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(cert.serialNumber)),\n // signature\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(cert.siginfo.algorithmOid).getBytes()),\n // parameters\n _signatureParametersToAsn1(\n cert.siginfo.algorithmOid, cert.siginfo.parameters)\n ]),\n // issuer\n _dnToAsn1(cert.issuer),\n // validity\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n notBefore,\n notAfter\n ]),\n // subject\n _dnToAsn1(cert.subject),\n // SubjectPublicKeyInfo\n pki.publicKeyToAsn1(cert.publicKey)\n ]);\n\n if(cert.issuer.uniqueId) {\n // issuerUniqueID (optional)\n tbs.value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n // TODO: support arbitrary bit length ids\n String.fromCharCode(0x00) +\n cert.issuer.uniqueId\n )\n ])\n );\n }\n if(cert.subject.uniqueId) {\n // subjectUniqueID (optional)\n tbs.value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n // TODO: support arbitrary bit length ids\n String.fromCharCode(0x00) +\n cert.subject.uniqueId\n )\n ])\n );\n }\n\n if(cert.extensions.length > 0) {\n // extensions (optional)\n tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions));\n }\n\n return tbs;\n};\n\n/**\n * Gets the ASN.1 CertificationRequestInfo part of a\n * PKCS#10 CertificationRequest.\n *\n * @param csr the certification request.\n *\n * @return the asn1 CertificationRequestInfo.\n */\npki.getCertificationRequestInfo = function(csr) {\n // CertificationRequestInfo\n var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(csr.version).getBytes()),\n // subject\n _dnToAsn1(csr.subject),\n // SubjectPublicKeyInfo\n pki.publicKeyToAsn1(csr.publicKey),\n // attributes\n _CRIAttributesToAsn1(csr)\n ]);\n\n return cri;\n};\n\n/**\n * Converts a DistinguishedName (subject or issuer) to an ASN.1 object.\n *\n * @param dn the DistinguishedName.\n *\n * @return the asn1 representation of a DistinguishedName.\n */\npki.distinguishedNameToAsn1 = function(dn) {\n return _dnToAsn1(dn);\n};\n\n/**\n * Converts an X.509v3 RSA certificate to an ASN.1 object.\n *\n * @param cert the certificate.\n *\n * @return the asn1 representation of an X.509v3 RSA certificate.\n */\npki.certificateToAsn1 = function(cert) {\n // prefer cached TBSCertificate over generating one\n var tbsCertificate = cert.tbsCertificate || pki.getTBSCertificate(cert);\n\n // Certificate\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // TBSCertificate\n tbsCertificate,\n // AlgorithmIdentifier (signature algorithm)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(cert.signatureOid).getBytes()),\n // parameters\n _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters)\n ]),\n // SignatureValue\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n String.fromCharCode(0x00) + cert.signature)\n ]);\n};\n\n/**\n * Converts X.509v3 certificate extensions to ASN.1.\n *\n * @param exts the extensions to convert.\n *\n * @return the extensions in ASN.1 format.\n */\npki.certificateExtensionsToAsn1 = function(exts) {\n // create top-level extension container\n var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []);\n\n // create extension sequence (stores a sequence for each extension)\n var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n rval.value.push(seq);\n\n for(var i = 0; i < exts.length; ++i) {\n seq.value.push(pki.certificateExtensionToAsn1(exts[i]));\n }\n\n return rval;\n};\n\n/**\n * Converts a single certificate extension to ASN.1.\n *\n * @param ext the extension to convert.\n *\n * @return the extension in ASN.1 format.\n */\npki.certificateExtensionToAsn1 = function(ext) {\n // create a sequence for each extension\n var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // extnID (OID)\n extseq.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(ext.id).getBytes()));\n\n // critical defaults to false\n if(ext.critical) {\n // critical BOOLEAN DEFAULT FALSE\n extseq.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,\n String.fromCharCode(0xFF)));\n }\n\n var value = ext.value;\n if(typeof ext.value !== 'string') {\n // value is asn.1\n value = asn1.toDer(value).getBytes();\n }\n\n // extnValue (OCTET STRING)\n extseq.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, value));\n\n return extseq;\n};\n\n/**\n * Converts a PKCS#10 certification request to an ASN.1 object.\n *\n * @param csr the certification request.\n *\n * @return the asn1 representation of a certification request.\n */\npki.certificationRequestToAsn1 = function(csr) {\n // prefer cached CertificationRequestInfo over generating one\n var cri = csr.certificationRequestInfo ||\n pki.getCertificationRequestInfo(csr);\n\n // Certificate\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // CertificationRequestInfo\n cri,\n // AlgorithmIdentifier (signature algorithm)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(csr.signatureOid).getBytes()),\n // parameters\n _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters)\n ]),\n // signature\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n String.fromCharCode(0x00) + csr.signature)\n ]);\n};\n\n/**\n * Creates a CA store.\n *\n * @param certs an optional array of certificate objects or PEM-formatted\n * certificate strings to add to the CA store.\n *\n * @return the CA store.\n */\npki.createCaStore = function(certs) {\n // create CA store\n var caStore = {\n // stored certificates\n certs: {}\n };\n\n /**\n * Gets the certificate that issued the passed certificate or its\n * 'parent'.\n *\n * @param cert the certificate to get the parent for.\n *\n * @return the parent certificate or null if none was found.\n */\n caStore.getIssuer = function(cert) {\n var rval = getBySubject(cert.issuer);\n\n // see if there are multiple matches\n /*if(forge.util.isArray(rval)) {\n // TODO: resolve multiple matches by checking\n // authorityKey/subjectKey/issuerUniqueID/other identifiers, etc.\n // FIXME: or alternatively do authority key mapping\n // if possible (X.509v1 certs can't work?)\n throw new Error('Resolving multiple issuer matches not implemented yet.');\n }*/\n\n return rval;\n };\n\n /**\n * Adds a trusted certificate to the store.\n *\n * @param cert the certificate to add as a trusted certificate (either a\n * pki.certificate object or a PEM-formatted certificate).\n */\n caStore.addCertificate = function(cert) {\n // convert from pem if necessary\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n\n ensureSubjectHasHash(cert.subject);\n\n if(!caStore.hasCertificate(cert)) { // avoid duplicate certificates in store\n if(cert.subject.hash in caStore.certs) {\n // subject hash already exists, append to array\n var tmp = caStore.certs[cert.subject.hash];\n if(!forge.util.isArray(tmp)) {\n tmp = [tmp];\n }\n tmp.push(cert);\n caStore.certs[cert.subject.hash] = tmp;\n } else {\n caStore.certs[cert.subject.hash] = cert;\n }\n }\n };\n\n /**\n * Checks to see if the given certificate is in the store.\n *\n * @param cert the certificate to check (either a pki.certificate or a\n * PEM-formatted certificate).\n *\n * @return true if the certificate is in the store, false if not.\n */\n caStore.hasCertificate = function(cert) {\n // convert from pem if necessary\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n\n var match = getBySubject(cert.subject);\n if(!match) {\n return false;\n }\n if(!forge.util.isArray(match)) {\n match = [match];\n }\n // compare DER-encoding of certificates\n var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes();\n for(var i = 0; i < match.length; ++i) {\n var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes();\n if(der1 === der2) {\n return true;\n }\n }\n return false;\n };\n\n /**\n * Lists all of the certificates kept in the store.\n *\n * @return an array of all of the pki.certificate objects in the store.\n */\n caStore.listAllCertificates = function() {\n var certList = [];\n\n for(var hash in caStore.certs) {\n if(caStore.certs.hasOwnProperty(hash)) {\n var value = caStore.certs[hash];\n if(!forge.util.isArray(value)) {\n certList.push(value);\n } else {\n for(var i = 0; i < value.length; ++i) {\n certList.push(value[i]);\n }\n }\n }\n }\n\n return certList;\n };\n\n /**\n * Removes a certificate from the store.\n *\n * @param cert the certificate to remove (either a pki.certificate or a\n * PEM-formatted certificate).\n *\n * @return the certificate that was removed or null if the certificate\n * wasn't in store.\n */\n caStore.removeCertificate = function(cert) {\n var result;\n\n // convert from pem if necessary\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n ensureSubjectHasHash(cert.subject);\n if(!caStore.hasCertificate(cert)) {\n return null;\n }\n\n var match = getBySubject(cert.subject);\n\n if(!forge.util.isArray(match)) {\n result = caStore.certs[cert.subject.hash];\n delete caStore.certs[cert.subject.hash];\n return result;\n }\n\n // compare DER-encoding of certificates\n var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes();\n for(var i = 0; i < match.length; ++i) {\n var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes();\n if(der1 === der2) {\n result = match[i];\n match.splice(i, 1);\n }\n }\n if(match.length === 0) {\n delete caStore.certs[cert.subject.hash];\n }\n\n return result;\n };\n\n function getBySubject(subject) {\n ensureSubjectHasHash(subject);\n return caStore.certs[subject.hash] || null;\n }\n\n function ensureSubjectHasHash(subject) {\n // produce subject hash if it doesn't exist\n if(!subject.hash) {\n var md = forge.md.sha1.create();\n subject.attributes = pki.RDNAttributesAsArray(_dnToAsn1(subject), md);\n subject.hash = md.digest().toHex();\n }\n }\n\n // auto-add passed in certs\n if(certs) {\n // parse PEM-formatted certificates as necessary\n for(var i = 0; i < certs.length; ++i) {\n var cert = certs[i];\n caStore.addCertificate(cert);\n }\n }\n\n return caStore;\n};\n\n/**\n * Certificate verification errors, based on TLS.\n */\npki.certificateError = {\n bad_certificate: 'forge.pki.BadCertificate',\n unsupported_certificate: 'forge.pki.UnsupportedCertificate',\n certificate_revoked: 'forge.pki.CertificateRevoked',\n certificate_expired: 'forge.pki.CertificateExpired',\n certificate_unknown: 'forge.pki.CertificateUnknown',\n unknown_ca: 'forge.pki.UnknownCertificateAuthority'\n};\n\n/**\n * Verifies a certificate chain against the given Certificate Authority store\n * with an optional custom verify callback.\n *\n * @param caStore a certificate store to verify against.\n * @param chain the certificate chain to verify, with the root or highest\n * authority at the end (an array of certificates).\n * @param options a callback to be called for every certificate in the chain or\n * an object with:\n * verify a callback to be called for every certificate in the\n * chain\n * validityCheckDate the date against which the certificate\n * validity period should be checked. Pass null to not check\n * the validity period. By default, the current date is used.\n *\n * The verify callback has the following signature:\n *\n * verified - Set to true if certificate was verified, otherwise the\n * pki.certificateError for why the certificate failed.\n * depth - The current index in the chain, where 0 is the end point's cert.\n * certs - The certificate chain, *NOTE* an empty chain indicates an anonymous\n * end point.\n *\n * The function returns true on success and on failure either the appropriate\n * pki.certificateError or an object with 'error' set to the appropriate\n * pki.certificateError and 'message' set to a custom error message.\n *\n * @return true if successful, error thrown if not.\n */\npki.verifyCertificateChain = function(caStore, chain, options) {\n /* From: RFC3280 - Internet X.509 Public Key Infrastructure Certificate\n Section 6: Certification Path Validation\n See inline parentheticals related to this particular implementation.\n\n The primary goal of path validation is to verify the binding between\n a subject distinguished name or a subject alternative name and subject\n public key, as represented in the end entity certificate, based on the\n public key of the trust anchor. This requires obtaining a sequence of\n certificates that support that binding. That sequence should be provided\n in the passed 'chain'. The trust anchor should be in the given CA\n store. The 'end entity' certificate is the certificate provided by the\n end point (typically a server) and is the first in the chain.\n\n To meet this goal, the path validation process verifies, among other\n things, that a prospective certification path (a sequence of n\n certificates or a 'chain') satisfies the following conditions:\n\n (a) for all x in {1, ..., n-1}, the subject of certificate x is\n the issuer of certificate x+1;\n\n (b) certificate 1 is issued by the trust anchor;\n\n (c) certificate n is the certificate to be validated; and\n\n (d) for all x in {1, ..., n}, the certificate was valid at the\n time in question.\n\n Note that here 'n' is index 0 in the chain and 1 is the last certificate\n in the chain and it must be signed by a certificate in the connection's\n CA store.\n\n The path validation process also determines the set of certificate\n policies that are valid for this path, based on the certificate policies\n extension, policy mapping extension, policy constraints extension, and\n inhibit any-policy extension.\n\n Note: Policy mapping extension not supported (Not Required).\n\n Note: If the certificate has an unsupported critical extension, then it\n must be rejected.\n\n Note: A certificate is self-issued if the DNs that appear in the subject\n and issuer fields are identical and are not empty.\n\n The path validation algorithm assumes the following seven inputs are\n provided to the path processing logic. What this specific implementation\n will use is provided parenthetically:\n\n (a) a prospective certification path of length n (the 'chain')\n (b) the current date/time: ('now').\n (c) user-initial-policy-set: A set of certificate policy identifiers\n naming the policies that are acceptable to the certificate user.\n The user-initial-policy-set contains the special value any-policy\n if the user is not concerned about certificate policy\n (Not implemented. Any policy is accepted).\n (d) trust anchor information, describing a CA that serves as a trust\n anchor for the certification path. The trust anchor information\n includes:\n\n (1) the trusted issuer name,\n (2) the trusted public key algorithm,\n (3) the trusted public key, and\n (4) optionally, the trusted public key parameters associated\n with the public key.\n\n (Trust anchors are provided via certificates in the CA store).\n\n The trust anchor information may be provided to the path processing\n procedure in the form of a self-signed certificate. The trusted anchor\n information is trusted because it was delivered to the path processing\n procedure by some trustworthy out-of-band procedure. If the trusted\n public key algorithm requires parameters, then the parameters are\n provided along with the trusted public key (No parameters used in this\n implementation).\n\n (e) initial-policy-mapping-inhibit, which indicates if policy mapping is\n allowed in the certification path.\n (Not implemented, no policy checking)\n\n (f) initial-explicit-policy, which indicates if the path must be valid\n for at least one of the certificate policies in the user-initial-\n policy-set.\n (Not implemented, no policy checking)\n\n (g) initial-any-policy-inhibit, which indicates whether the\n anyPolicy OID should be processed if it is included in a\n certificate.\n (Not implemented, so any policy is valid provided that it is\n not marked as critical) */\n\n /* Basic Path Processing:\n\n For each certificate in the 'chain', the following is checked:\n\n 1. The certificate validity period includes the current time.\n 2. The certificate was signed by its parent (where the parent is either\n the next in the chain or from the CA store). Allow processing to\n continue to the next step if no parent is found but the certificate is\n in the CA store.\n 3. TODO: The certificate has not been revoked.\n 4. The certificate issuer name matches the parent's subject name.\n 5. TODO: If the certificate is self-issued and not the final certificate\n in the chain, skip this step, otherwise verify that the subject name\n is within one of the permitted subtrees of X.500 distinguished names\n and that each of the alternative names in the subjectAltName extension\n (critical or non-critical) is within one of the permitted subtrees for\n that name type.\n 6. TODO: If the certificate is self-issued and not the final certificate\n in the chain, skip this step, otherwise verify that the subject name\n is not within one of the excluded subtrees for X.500 distinguished\n names and none of the subjectAltName extension names are excluded for\n that name type.\n 7. The other steps in the algorithm for basic path processing involve\n handling the policy extension which is not presently supported in this\n implementation. Instead, if a critical policy extension is found, the\n certificate is rejected as not supported.\n 8. If the certificate is not the first or if its the only certificate in\n the chain (having no parent from the CA store or is self-signed) and it\n has a critical key usage extension, verify that the keyCertSign bit is\n set. If the key usage extension exists, verify that the basic\n constraints extension exists. If the basic constraints extension exists,\n verify that the cA flag is set. If pathLenConstraint is set, ensure that\n the number of certificates that precede in the chain (come earlier\n in the chain as implemented below), excluding the very first in the\n chain (typically the end-entity one), isn't greater than the\n pathLenConstraint. This constraint limits the number of intermediate\n CAs that may appear below a CA before only end-entity certificates\n may be issued. */\n\n // if a verify callback is passed as the third parameter, package it within\n // the options object. This is to support a legacy function signature that\n // expected the verify callback as the third parameter.\n if(typeof options === 'function') {\n options = {verify: options};\n }\n options = options || {};\n\n // copy cert chain references to another array to protect against changes\n // in verify callback\n chain = chain.slice(0);\n var certs = chain.slice(0);\n\n var validityCheckDate = options.validityCheckDate;\n // if no validityCheckDate is specified, default to the current date. Make\n // sure to maintain the value null because it indicates that the validity\n // period should not be checked.\n if(typeof validityCheckDate === 'undefined') {\n validityCheckDate = new Date();\n }\n\n // verify each cert in the chain using its parent, where the parent\n // is either the next in the chain or from the CA store\n var first = true;\n var error = null;\n var depth = 0;\n do {\n var cert = chain.shift();\n var parent = null;\n var selfSigned = false;\n\n if(validityCheckDate) {\n // 1. check valid time\n if(validityCheckDate < cert.validity.notBefore ||\n validityCheckDate > cert.validity.notAfter) {\n error = {\n message: 'Certificate is not valid yet or has expired.',\n error: pki.certificateError.certificate_expired,\n notBefore: cert.validity.notBefore,\n notAfter: cert.validity.notAfter,\n // TODO: we might want to reconsider renaming 'now' to\n // 'validityCheckDate' should this API be changed in the future.\n now: validityCheckDate\n };\n }\n }\n\n // 2. verify with parent from chain or CA store\n if(error === null) {\n parent = chain[0] || caStore.getIssuer(cert);\n if(parent === null) {\n // check for self-signed cert\n if(cert.isIssuer(cert)) {\n selfSigned = true;\n parent = cert;\n }\n }\n\n if(parent) {\n // FIXME: current CA store implementation might have multiple\n // certificates where the issuer can't be determined from the\n // certificate (happens rarely with, eg: old certificates) so normalize\n // by always putting parents into an array\n // TODO: there's may be an extreme degenerate case currently uncovered\n // where an old intermediate certificate seems to have a matching parent\n // but none of the parents actually verify ... but the intermediate\n // is in the CA and it should pass this check; needs investigation\n var parents = parent;\n if(!forge.util.isArray(parents)) {\n parents = [parents];\n }\n\n // try to verify with each possible parent (typically only one)\n var verified = false;\n while(!verified && parents.length > 0) {\n parent = parents.shift();\n try {\n verified = parent.verify(cert);\n } catch(ex) {\n // failure to verify, don't care why, try next one\n }\n }\n\n if(!verified) {\n error = {\n message: 'Certificate signature is invalid.',\n error: pki.certificateError.bad_certificate\n };\n }\n }\n\n if(error === null && (!parent || selfSigned) &&\n !caStore.hasCertificate(cert)) {\n // no parent issuer and certificate itself is not trusted\n error = {\n message: 'Certificate is not trusted.',\n error: pki.certificateError.unknown_ca\n };\n }\n }\n\n // TODO: 3. check revoked\n\n // 4. check for matching issuer/subject\n if(error === null && parent && !cert.isIssuer(parent)) {\n // parent is not issuer\n error = {\n message: 'Certificate issuer is invalid.',\n error: pki.certificateError.bad_certificate\n };\n }\n\n // 5. TODO: check names with permitted names tree\n\n // 6. TODO: check names against excluded names tree\n\n // 7. check for unsupported critical extensions\n if(error === null) {\n // supported extensions\n var se = {\n keyUsage: true,\n basicConstraints: true\n };\n for(var i = 0; error === null && i < cert.extensions.length; ++i) {\n var ext = cert.extensions[i];\n if(ext.critical && !(ext.name in se)) {\n error = {\n message:\n 'Certificate has an unsupported critical extension.',\n error: pki.certificateError.unsupported_certificate\n };\n }\n }\n }\n\n // 8. check for CA if cert is not first or is the only certificate\n // remaining in chain with no parent or is self-signed\n if(error === null &&\n (!first || (chain.length === 0 && (!parent || selfSigned)))) {\n // first check keyUsage extension and then basic constraints\n var bcExt = cert.getExtension('basicConstraints');\n var keyUsageExt = cert.getExtension('keyUsage');\n if(keyUsageExt !== null) {\n // keyCertSign must be true and there must be a basic\n // constraints extension\n if(!keyUsageExt.keyCertSign || bcExt === null) {\n // bad certificate\n error = {\n message:\n 'Certificate keyUsage or basicConstraints conflict ' +\n 'or indicate that the certificate is not a CA. ' +\n 'If the certificate is the only one in the chain or ' +\n 'isn\\'t the first then the certificate must be a ' +\n 'valid CA.',\n error: pki.certificateError.bad_certificate\n };\n }\n }\n // basic constraints cA flag must be set\n if(error === null && bcExt !== null && !bcExt.cA) {\n // bad certificate\n error = {\n message:\n 'Certificate basicConstraints indicates the certificate ' +\n 'is not a CA.',\n error: pki.certificateError.bad_certificate\n };\n }\n // if error is not null and keyUsage is available, then we know it\n // has keyCertSign and there is a basic constraints extension too,\n // which means we can check pathLenConstraint (if it exists)\n if(error === null && keyUsageExt !== null &&\n 'pathLenConstraint' in bcExt) {\n // pathLen is the maximum # of intermediate CA certs that can be\n // found between the current certificate and the end-entity (depth 0)\n // certificate; this number does not include the end-entity (depth 0,\n // last in the chain) even if it happens to be a CA certificate itself\n var pathLen = depth - 1;\n if(pathLen > bcExt.pathLenConstraint) {\n // pathLenConstraint violated, bad certificate\n error = {\n message:\n 'Certificate basicConstraints pathLenConstraint violated.',\n error: pki.certificateError.bad_certificate\n };\n }\n }\n }\n\n // call application callback\n var vfd = (error === null) ? true : error.error;\n var ret = options.verify ? options.verify(vfd, depth, certs) : vfd;\n if(ret === true) {\n // clear any set error\n error = null;\n } else {\n // if passed basic tests, set default message and alert\n if(vfd === true) {\n error = {\n message: 'The application rejected the certificate.',\n error: pki.certificateError.bad_certificate\n };\n }\n\n // check for custom error info\n if(ret || ret === 0) {\n // set custom message and error\n if(typeof ret === 'object' && !forge.util.isArray(ret)) {\n if(ret.message) {\n error.message = ret.message;\n }\n if(ret.error) {\n error.error = ret.error;\n }\n } else if(typeof ret === 'string') {\n // set custom error\n error.error = ret;\n }\n }\n\n // throw error\n throw error;\n }\n\n // no longer first cert in chain\n first = false;\n ++depth;\n } while(chain.length > 0);\n\n return true;\n};\n","/**\n * Javascript implementation of PKCS#12.\n *\n * @author Dave Longley\n * @author Stefan Siegl <stesie@brokenpipe.de>\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>\n *\n * The ASN.1 representation of PKCS#12 is as follows\n * (see ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12-tc1.pdf for details)\n *\n * PFX ::= SEQUENCE {\n * version INTEGER {v3(3)}(v3,...),\n * authSafe ContentInfo,\n * macData MacData OPTIONAL\n * }\n *\n * MacData ::= SEQUENCE {\n * mac DigestInfo,\n * macSalt OCTET STRING,\n * iterations INTEGER DEFAULT 1\n * }\n * Note: The iterations default is for historical reasons and its use is\n * deprecated. A higher value, like 1024, is recommended.\n *\n * DigestInfo is defined in PKCS#7 as follows:\n *\n * DigestInfo ::= SEQUENCE {\n * digestAlgorithm DigestAlgorithmIdentifier,\n * digest Digest\n * }\n *\n * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters\n * for the algorithm, if any. In the case of SHA1 there is none.\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * Digest ::= OCTET STRING\n *\n *\n * ContentInfo ::= SEQUENCE {\n * contentType ContentType,\n * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL\n * }\n *\n * ContentType ::= OBJECT IDENTIFIER\n *\n * AuthenticatedSafe ::= SEQUENCE OF ContentInfo\n * -- Data if unencrypted\n * -- EncryptedData if password-encrypted\n * -- EnvelopedData if public key-encrypted\n *\n *\n * SafeContents ::= SEQUENCE OF SafeBag\n *\n * SafeBag ::= SEQUENCE {\n * bagId BAG-TYPE.&id ({PKCS12BagSet})\n * bagValue [0] EXPLICIT BAG-TYPE.&Type({PKCS12BagSet}{@bagId}),\n * bagAttributes SET OF PKCS12Attribute OPTIONAL\n * }\n *\n * PKCS12Attribute ::= SEQUENCE {\n * attrId ATTRIBUTE.&id ({PKCS12AttrSet}),\n * attrValues SET OF ATTRIBUTE.&Type ({PKCS12AttrSet}{@attrId})\n * } -- This type is compatible with the X.500 type 'Attribute'\n *\n * PKCS12AttrSet ATTRIBUTE ::= {\n * friendlyName | -- from PKCS #9\n * localKeyId, -- from PKCS #9\n * ... -- Other attributes are allowed\n * }\n *\n * CertBag ::= SEQUENCE {\n * certId BAG-TYPE.&id ({CertTypes}),\n * certValue [0] EXPLICIT BAG-TYPE.&Type ({CertTypes}{@certId})\n * }\n *\n * x509Certificate BAG-TYPE ::= {OCTET STRING IDENTIFIED BY {certTypes 1}}\n * -- DER-encoded X.509 certificate stored in OCTET STRING\n *\n * sdsiCertificate BAG-TYPE ::= {IA5String IDENTIFIED BY {certTypes 2}}\n * -- Base64-encoded SDSI certificate stored in IA5String\n *\n * CertTypes BAG-TYPE ::= {\n * x509Certificate |\n * sdsiCertificate,\n * ... -- For future extensions\n * }\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./hmac');\nrequire('./oids');\nrequire('./pkcs7asn1');\nrequire('./pbe');\nrequire('./random');\nrequire('./rsa');\nrequire('./sha1');\nrequire('./util');\nrequire('./x509');\n\n// shortcut for asn.1 & PKI API\nvar asn1 = forge.asn1;\nvar pki = forge.pki;\n\n// shortcut for PKCS#12 API\nvar p12 = module.exports = forge.pkcs12 = forge.pkcs12 || {};\n\nvar contentInfoValidator = {\n name: 'ContentInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE, // a ContentInfo\n constructed: true,\n value: [{\n name: 'ContentInfo.contentType',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'contentType'\n }, {\n name: 'ContentInfo.content',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n constructed: true,\n captureAsn1: 'content'\n }]\n};\n\nvar pfxValidator = {\n name: 'PFX',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PFX.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n },\n contentInfoValidator, {\n name: 'PFX.macData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n captureAsn1: 'mac',\n value: [{\n name: 'PFX.macData.mac',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE, // DigestInfo\n constructed: true,\n value: [{\n name: 'PFX.macData.mac.digestAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE, // DigestAlgorithmIdentifier\n constructed: true,\n value: [{\n name: 'PFX.macData.mac.digestAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'macAlgorithm'\n }, {\n name: 'PFX.macData.mac.digestAlgorithm.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n captureAsn1: 'macAlgorithmParameters'\n }]\n }, {\n name: 'PFX.macData.mac.digest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'macDigest'\n }]\n }, {\n name: 'PFX.macData.macSalt',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'macSalt'\n }, {\n name: 'PFX.macData.iterations',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n optional: true,\n capture: 'macIterations'\n }]\n }]\n};\n\nvar safeBagValidator = {\n name: 'SafeBag',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SafeBag.bagId',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'bagId'\n }, {\n name: 'SafeBag.bagValue',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n constructed: true,\n captureAsn1: 'bagValue'\n }, {\n name: 'SafeBag.bagAttributes',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n optional: true,\n capture: 'bagAttributes'\n }]\n};\n\nvar attributeValidator = {\n name: 'Attribute',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'Attribute.attrId',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'oid'\n }, {\n name: 'Attribute.attrValues',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n capture: 'values'\n }]\n};\n\nvar certBagValidator = {\n name: 'CertBag',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'CertBag.certId',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'certId'\n }, {\n name: 'CertBag.certValue',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n constructed: true,\n /* So far we only support X.509 certificates (which are wrapped in\n an OCTET STRING, hence hard code that here). */\n value: [{\n name: 'CertBag.certValue[0]',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.OCTETSTRING,\n constructed: false,\n capture: 'cert'\n }]\n }]\n};\n\n/**\n * Search SafeContents structure for bags with matching attributes.\n *\n * The search can optionally be narrowed by a certain bag type.\n *\n * @param safeContents the SafeContents structure to search in.\n * @param attrName the name of the attribute to compare against.\n * @param attrValue the attribute value to search for.\n * @param [bagType] bag type to narrow search by.\n *\n * @return an array of matching bags.\n */\nfunction _getBagsByAttribute(safeContents, attrName, attrValue, bagType) {\n var result = [];\n\n for(var i = 0; i < safeContents.length; i++) {\n for(var j = 0; j < safeContents[i].safeBags.length; j++) {\n var bag = safeContents[i].safeBags[j];\n if(bagType !== undefined && bag.type !== bagType) {\n continue;\n }\n // only filter by bag type, no attribute specified\n if(attrName === null) {\n result.push(bag);\n continue;\n }\n if(bag.attributes[attrName] !== undefined &&\n bag.attributes[attrName].indexOf(attrValue) >= 0) {\n result.push(bag);\n }\n }\n }\n\n return result;\n}\n\n/**\n * Converts a PKCS#12 PFX in ASN.1 notation into a PFX object.\n *\n * @param obj The PKCS#12 PFX in ASN.1 notation.\n * @param strict true to use strict DER decoding, false not to (default: true).\n * @param {String} password Password to decrypt with (optional).\n *\n * @return PKCS#12 PFX object.\n */\np12.pkcs12FromAsn1 = function(obj, strict, password) {\n // handle args\n if(typeof strict === 'string') {\n password = strict;\n strict = true;\n } else if(strict === undefined) {\n strict = true;\n }\n\n // validate PFX and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, pfxValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#12 PFX. ' +\n 'ASN.1 object is not an PKCS#12 PFX.');\n error.errors = error;\n throw error;\n }\n\n var pfx = {\n version: capture.version.charCodeAt(0),\n safeContents: [],\n\n /**\n * Gets bags with matching attributes.\n *\n * @param filter the attributes to filter by:\n * [localKeyId] the localKeyId to search for.\n * [localKeyIdHex] the localKeyId in hex to search for.\n * [friendlyName] the friendly name to search for.\n * [bagType] bag type to narrow each attribute search by.\n *\n * @return a map of attribute type to an array of matching bags or, if no\n * attribute was given but a bag type, the map key will be the\n * bag type.\n */\n getBags: function(filter) {\n var rval = {};\n\n var localKeyId;\n if('localKeyId' in filter) {\n localKeyId = filter.localKeyId;\n } else if('localKeyIdHex' in filter) {\n localKeyId = forge.util.hexToBytes(filter.localKeyIdHex);\n }\n\n // filter on bagType only\n if(localKeyId === undefined && !('friendlyName' in filter) &&\n 'bagType' in filter) {\n rval[filter.bagType] = _getBagsByAttribute(\n pfx.safeContents, null, null, filter.bagType);\n }\n\n if(localKeyId !== undefined) {\n rval.localKeyId = _getBagsByAttribute(\n pfx.safeContents, 'localKeyId',\n localKeyId, filter.bagType);\n }\n if('friendlyName' in filter) {\n rval.friendlyName = _getBagsByAttribute(\n pfx.safeContents, 'friendlyName',\n filter.friendlyName, filter.bagType);\n }\n\n return rval;\n },\n\n /**\n * DEPRECATED: use getBags() instead.\n *\n * Get bags with matching friendlyName attribute.\n *\n * @param friendlyName the friendly name to search for.\n * @param [bagType] bag type to narrow search by.\n *\n * @return an array of bags with matching friendlyName attribute.\n */\n getBagsByFriendlyName: function(friendlyName, bagType) {\n return _getBagsByAttribute(\n pfx.safeContents, 'friendlyName', friendlyName, bagType);\n },\n\n /**\n * DEPRECATED: use getBags() instead.\n *\n * Get bags with matching localKeyId attribute.\n *\n * @param localKeyId the localKeyId to search for.\n * @param [bagType] bag type to narrow search by.\n *\n * @return an array of bags with matching localKeyId attribute.\n */\n getBagsByLocalKeyId: function(localKeyId, bagType) {\n return _getBagsByAttribute(\n pfx.safeContents, 'localKeyId', localKeyId, bagType);\n }\n };\n\n if(capture.version.charCodeAt(0) !== 3) {\n var error = new Error('PKCS#12 PFX of version other than 3 not supported.');\n error.version = capture.version.charCodeAt(0);\n throw error;\n }\n\n if(asn1.derToOid(capture.contentType) !== pki.oids.data) {\n var error = new Error('Only PKCS#12 PFX in password integrity mode supported.');\n error.oid = asn1.derToOid(capture.contentType);\n throw error;\n }\n\n var data = capture.content.value[0];\n if(data.tagClass !== asn1.Class.UNIVERSAL ||\n data.type !== asn1.Type.OCTETSTRING) {\n throw new Error('PKCS#12 authSafe content data is not an OCTET STRING.');\n }\n data = _decodePkcs7Data(data);\n\n // check for MAC\n if(capture.mac) {\n var md = null;\n var macKeyBytes = 0;\n var macAlgorithm = asn1.derToOid(capture.macAlgorithm);\n switch(macAlgorithm) {\n case pki.oids.sha1:\n md = forge.md.sha1.create();\n macKeyBytes = 20;\n break;\n case pki.oids.sha256:\n md = forge.md.sha256.create();\n macKeyBytes = 32;\n break;\n case pki.oids.sha384:\n md = forge.md.sha384.create();\n macKeyBytes = 48;\n break;\n case pki.oids.sha512:\n md = forge.md.sha512.create();\n macKeyBytes = 64;\n break;\n case pki.oids.md5:\n md = forge.md.md5.create();\n macKeyBytes = 16;\n break;\n }\n if(md === null) {\n throw new Error('PKCS#12 uses unsupported MAC algorithm: ' + macAlgorithm);\n }\n\n // verify MAC (iterations default to 1)\n var macSalt = new forge.util.ByteBuffer(capture.macSalt);\n var macIterations = (('macIterations' in capture) ?\n parseInt(forge.util.bytesToHex(capture.macIterations), 16) : 1);\n var macKey = p12.generateKey(\n password, macSalt, 3, macIterations, macKeyBytes, md);\n var mac = forge.hmac.create();\n mac.start(md, macKey);\n mac.update(data.value);\n var macValue = mac.getMac();\n if(macValue.getBytes() !== capture.macDigest) {\n throw new Error('PKCS#12 MAC could not be verified. Invalid password?');\n }\n }\n\n _decodeAuthenticatedSafe(pfx, data.value, strict, password);\n return pfx;\n};\n\n/**\n * Decodes PKCS#7 Data. PKCS#7 (RFC 2315) defines \"Data\" as an OCTET STRING,\n * but it is sometimes an OCTET STRING that is composed/constructed of chunks,\n * each its own OCTET STRING. This is BER-encoding vs. DER-encoding. This\n * function transforms this corner-case into the usual simple,\n * non-composed/constructed OCTET STRING.\n *\n * This function may be moved to ASN.1 at some point to better deal with\n * more BER-encoding issues, should they arise.\n *\n * @param data the ASN.1 Data object to transform.\n */\nfunction _decodePkcs7Data(data) {\n // handle special case of \"chunked\" data content: an octet string composed\n // of other octet strings\n if(data.composed || data.constructed) {\n var value = forge.util.createBuffer();\n for(var i = 0; i < data.value.length; ++i) {\n value.putBytes(data.value[i].value);\n }\n data.composed = data.constructed = false;\n data.value = value.getBytes();\n }\n return data;\n}\n\n/**\n * Decode PKCS#12 AuthenticatedSafe (BER encoded) into PFX object.\n *\n * The AuthenticatedSafe is a BER-encoded SEQUENCE OF ContentInfo.\n *\n * @param pfx The PKCS#12 PFX object to fill.\n * @param {String} authSafe BER-encoded AuthenticatedSafe.\n * @param strict true to use strict DER decoding, false not to.\n * @param {String} password Password to decrypt with (optional).\n */\nfunction _decodeAuthenticatedSafe(pfx, authSafe, strict, password) {\n authSafe = asn1.fromDer(authSafe, strict); /* actually it's BER encoded */\n\n if(authSafe.tagClass !== asn1.Class.UNIVERSAL ||\n authSafe.type !== asn1.Type.SEQUENCE ||\n authSafe.constructed !== true) {\n throw new Error('PKCS#12 AuthenticatedSafe expected to be a ' +\n 'SEQUENCE OF ContentInfo');\n }\n\n for(var i = 0; i < authSafe.value.length; i++) {\n var contentInfo = authSafe.value[i];\n\n // validate contentInfo and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(contentInfo, contentInfoValidator, capture, errors)) {\n var error = new Error('Cannot read ContentInfo.');\n error.errors = errors;\n throw error;\n }\n\n var obj = {\n encrypted: false\n };\n var safeContents = null;\n var data = capture.content.value[0];\n switch(asn1.derToOid(capture.contentType)) {\n case pki.oids.data:\n if(data.tagClass !== asn1.Class.UNIVERSAL ||\n data.type !== asn1.Type.OCTETSTRING) {\n throw new Error('PKCS#12 SafeContents Data is not an OCTET STRING.');\n }\n safeContents = _decodePkcs7Data(data).value;\n break;\n case pki.oids.encryptedData:\n safeContents = _decryptSafeContents(data, password);\n obj.encrypted = true;\n break;\n default:\n var error = new Error('Unsupported PKCS#12 contentType.');\n error.contentType = asn1.derToOid(capture.contentType);\n throw error;\n }\n\n obj.safeBags = _decodeSafeContents(safeContents, strict, password);\n pfx.safeContents.push(obj);\n }\n}\n\n/**\n * Decrypt PKCS#7 EncryptedData structure.\n *\n * @param data ASN.1 encoded EncryptedContentInfo object.\n * @param password The user-provided password.\n *\n * @return The decrypted SafeContents (ASN.1 object).\n */\nfunction _decryptSafeContents(data, password) {\n var capture = {};\n var errors = [];\n if(!asn1.validate(\n data, forge.pkcs7.asn1.encryptedDataValidator, capture, errors)) {\n var error = new Error('Cannot read EncryptedContentInfo.');\n error.errors = errors;\n throw error;\n }\n\n var oid = asn1.derToOid(capture.contentType);\n if(oid !== pki.oids.data) {\n var error = new Error(\n 'PKCS#12 EncryptedContentInfo ContentType is not Data.');\n error.oid = oid;\n throw error;\n }\n\n // get cipher\n oid = asn1.derToOid(capture.encAlgorithm);\n var cipher = pki.pbe.getCipher(oid, capture.encParameter, password);\n\n // get encrypted data\n var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1);\n var encrypted = forge.util.createBuffer(encryptedContentAsn1.value);\n\n cipher.update(encrypted);\n if(!cipher.finish()) {\n throw new Error('Failed to decrypt PKCS#12 SafeContents.');\n }\n\n return cipher.output.getBytes();\n}\n\n/**\n * Decode PKCS#12 SafeContents (BER-encoded) into array of Bag objects.\n *\n * The safeContents is a BER-encoded SEQUENCE OF SafeBag.\n *\n * @param {String} safeContents BER-encoded safeContents.\n * @param strict true to use strict DER decoding, false not to.\n * @param {String} password Password to decrypt with (optional).\n *\n * @return {Array} Array of Bag objects.\n */\nfunction _decodeSafeContents(safeContents, strict, password) {\n // if strict and no safe contents, return empty safes\n if(!strict && safeContents.length === 0) {\n return [];\n }\n\n // actually it's BER-encoded\n safeContents = asn1.fromDer(safeContents, strict);\n\n if(safeContents.tagClass !== asn1.Class.UNIVERSAL ||\n safeContents.type !== asn1.Type.SEQUENCE ||\n safeContents.constructed !== true) {\n throw new Error(\n 'PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.');\n }\n\n var res = [];\n for(var i = 0; i < safeContents.value.length; i++) {\n var safeBag = safeContents.value[i];\n\n // validate SafeBag and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(safeBag, safeBagValidator, capture, errors)) {\n var error = new Error('Cannot read SafeBag.');\n error.errors = errors;\n throw error;\n }\n\n /* Create bag object and push to result array. */\n var bag = {\n type: asn1.derToOid(capture.bagId),\n attributes: _decodeBagAttributes(capture.bagAttributes)\n };\n res.push(bag);\n\n var validator, decoder;\n var bagAsn1 = capture.bagValue.value[0];\n switch(bag.type) {\n case pki.oids.pkcs8ShroudedKeyBag:\n /* bagAsn1 has a EncryptedPrivateKeyInfo, which we need to decrypt.\n Afterwards we can handle it like a keyBag,\n which is a PrivateKeyInfo. */\n bagAsn1 = pki.decryptPrivateKeyInfo(bagAsn1, password);\n if(bagAsn1 === null) {\n throw new Error(\n 'Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?');\n }\n\n /* fall through */\n case pki.oids.keyBag:\n /* A PKCS#12 keyBag is a simple PrivateKeyInfo as understood by our\n PKI module, hence we don't have to do validation/capturing here,\n just pass what we already got. */\n try {\n bag.key = pki.privateKeyFromAsn1(bagAsn1);\n } catch(e) {\n // ignore unknown key type, pass asn1 value\n bag.key = null;\n bag.asn1 = bagAsn1;\n }\n continue; /* Nothing more to do. */\n\n case pki.oids.certBag:\n /* A PKCS#12 certBag can wrap both X.509 and sdsi certificates.\n Therefore put the SafeBag content through another validator to\n capture the fields. Afterwards check & store the results. */\n validator = certBagValidator;\n decoder = function() {\n if(asn1.derToOid(capture.certId) !== pki.oids.x509Certificate) {\n var error = new Error(\n 'Unsupported certificate type, only X.509 supported.');\n error.oid = asn1.derToOid(capture.certId);\n throw error;\n }\n\n // true=produce cert hash\n var certAsn1 = asn1.fromDer(capture.cert, strict);\n try {\n bag.cert = pki.certificateFromAsn1(certAsn1, true);\n } catch(e) {\n // ignore unknown cert type, pass asn1 value\n bag.cert = null;\n bag.asn1 = certAsn1;\n }\n };\n break;\n\n default:\n var error = new Error('Unsupported PKCS#12 SafeBag type.');\n error.oid = bag.type;\n throw error;\n }\n\n /* Validate SafeBag value (i.e. CertBag, etc.) and capture data if needed. */\n if(validator !== undefined &&\n !asn1.validate(bagAsn1, validator, capture, errors)) {\n var error = new Error('Cannot read PKCS#12 ' + validator.name);\n error.errors = errors;\n throw error;\n }\n\n /* Call decoder function from above to store the results. */\n decoder();\n }\n\n return res;\n}\n\n/**\n * Decode PKCS#12 SET OF PKCS12Attribute into JavaScript object.\n *\n * @param attributes SET OF PKCS12Attribute (ASN.1 object).\n *\n * @return the decoded attributes.\n */\nfunction _decodeBagAttributes(attributes) {\n var decodedAttrs = {};\n\n if(attributes !== undefined) {\n for(var i = 0; i < attributes.length; ++i) {\n var capture = {};\n var errors = [];\n if(!asn1.validate(attributes[i], attributeValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#12 BagAttribute.');\n error.errors = errors;\n throw error;\n }\n\n var oid = asn1.derToOid(capture.oid);\n if(pki.oids[oid] === undefined) {\n // unsupported attribute type, ignore.\n continue;\n }\n\n decodedAttrs[pki.oids[oid]] = [];\n for(var j = 0; j < capture.values.length; ++j) {\n decodedAttrs[pki.oids[oid]].push(capture.values[j].value);\n }\n }\n }\n\n return decodedAttrs;\n}\n\n/**\n * Wraps a private key and certificate in a PKCS#12 PFX wrapper. If a\n * password is provided then the private key will be encrypted.\n *\n * An entire certificate chain may also be included. To do this, pass\n * an array for the \"cert\" parameter where the first certificate is\n * the one that is paired with the private key and each subsequent one\n * verifies the previous one. The certificates may be in PEM format or\n * have been already parsed by Forge.\n *\n * @todo implement password-based-encryption for the whole package\n *\n * @param key the private key.\n * @param cert the certificate (may be an array of certificates in order\n * to specify a certificate chain).\n * @param password the password to use, null for none.\n * @param options:\n * algorithm the encryption algorithm to use\n * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'.\n * count the iteration count to use.\n * saltSize the salt size to use.\n * useMac true to include a MAC, false not to, defaults to true.\n * localKeyId the local key ID to use, in hex.\n * friendlyName the friendly name to use.\n * generateLocalKeyId true to generate a random local key ID,\n * false not to, defaults to true.\n *\n * @return the PKCS#12 PFX ASN.1 object.\n */\np12.toPkcs12Asn1 = function(key, cert, password, options) {\n // set default options\n options = options || {};\n options.saltSize = options.saltSize || 8;\n options.count = options.count || 2048;\n options.algorithm = options.algorithm || options.encAlgorithm || 'aes128';\n if(!('useMac' in options)) {\n options.useMac = true;\n }\n if(!('localKeyId' in options)) {\n options.localKeyId = null;\n }\n if(!('generateLocalKeyId' in options)) {\n options.generateLocalKeyId = true;\n }\n\n var localKeyId = options.localKeyId;\n var bagAttrs;\n if(localKeyId !== null) {\n localKeyId = forge.util.hexToBytes(localKeyId);\n } else if(options.generateLocalKeyId) {\n // use SHA-1 of paired cert, if available\n if(cert) {\n var pairedCert = forge.util.isArray(cert) ? cert[0] : cert;\n if(typeof pairedCert === 'string') {\n pairedCert = pki.certificateFromPem(pairedCert);\n }\n var sha1 = forge.md.sha1.create();\n sha1.update(asn1.toDer(pki.certificateToAsn1(pairedCert)).getBytes());\n localKeyId = sha1.digest().getBytes();\n } else {\n // FIXME: consider using SHA-1 of public key (which can be generated\n // from private key components), see: cert.generateSubjectKeyIdentifier\n // generate random bytes\n localKeyId = forge.random.getBytes(20);\n }\n }\n\n var attrs = [];\n if(localKeyId !== null) {\n attrs.push(\n // localKeyID\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // attrId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.localKeyId).getBytes()),\n // attrValues\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n localKeyId)\n ])\n ]));\n }\n if('friendlyName' in options) {\n attrs.push(\n // friendlyName\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // attrId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.friendlyName).getBytes()),\n // attrValues\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BMPSTRING, false,\n options.friendlyName)\n ])\n ]));\n }\n\n if(attrs.length > 0) {\n bagAttrs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, attrs);\n }\n\n // collect contents for AuthenticatedSafe\n var contents = [];\n\n // create safe bag(s) for certificate chain\n var chain = [];\n if(cert !== null) {\n if(forge.util.isArray(cert)) {\n chain = cert;\n } else {\n chain = [cert];\n }\n }\n\n var certSafeBags = [];\n for(var i = 0; i < chain.length; ++i) {\n // convert cert from PEM as necessary\n cert = chain[i];\n if(typeof cert === 'string') {\n cert = pki.certificateFromPem(cert);\n }\n\n // SafeBag\n var certBagAttrs = (i === 0) ? bagAttrs : undefined;\n var certAsn1 = pki.certificateToAsn1(cert);\n var certSafeBag =\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // bagId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.certBag).getBytes()),\n // bagValue\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n // CertBag\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // certId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.x509Certificate).getBytes()),\n // certValue (x509Certificate)\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(certAsn1).getBytes())\n ])])]),\n // bagAttributes (OPTIONAL)\n certBagAttrs\n ]);\n certSafeBags.push(certSafeBag);\n }\n\n if(certSafeBags.length > 0) {\n // SafeContents\n var certSafeContents = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, certSafeBags);\n\n // ContentInfo\n var certCI =\n // PKCS#7 ContentInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // contentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n // OID for the content type is 'data'\n asn1.oidToDer(pki.oids.data).getBytes()),\n // content\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(certSafeContents).getBytes())\n ])\n ]);\n contents.push(certCI);\n }\n\n // create safe contents for private key\n var keyBag = null;\n if(key !== null) {\n // SafeBag\n var pkAsn1 = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(key));\n if(password === null) {\n // no encryption\n keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // bagId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.keyBag).getBytes()),\n // bagValue\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n // PrivateKeyInfo\n pkAsn1\n ]),\n // bagAttributes (OPTIONAL)\n bagAttrs\n ]);\n } else {\n // encrypted PrivateKeyInfo\n keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // bagId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.pkcs8ShroudedKeyBag).getBytes()),\n // bagValue\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n // EncryptedPrivateKeyInfo\n pki.encryptPrivateKeyInfo(pkAsn1, password, options)\n ]),\n // bagAttributes (OPTIONAL)\n bagAttrs\n ]);\n }\n\n // SafeContents\n var keySafeContents =\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [keyBag]);\n\n // ContentInfo\n var keyCI =\n // PKCS#7 ContentInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // contentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n // OID for the content type is 'data'\n asn1.oidToDer(pki.oids.data).getBytes()),\n // content\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(keySafeContents).getBytes())\n ])\n ]);\n contents.push(keyCI);\n }\n\n // create AuthenticatedSafe by stringing together the contents\n var safe = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, contents);\n\n var macData;\n if(options.useMac) {\n // MacData\n var sha1 = forge.md.sha1.create();\n var macSalt = new forge.util.ByteBuffer(\n forge.random.getBytes(options.saltSize));\n var count = options.count;\n // 160-bit key\n var key = p12.generateKey(password, macSalt, 3, count, 20);\n var mac = forge.hmac.create();\n mac.start(sha1, key);\n mac.update(asn1.toDer(safe).getBytes());\n var macValue = mac.getMac();\n macData = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // mac DigestInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // digestAlgorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm = SHA-1\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.sha1).getBytes()),\n // parameters = Null\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // digest\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING,\n false, macValue.getBytes())\n ]),\n // macSalt OCTET STRING\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, macSalt.getBytes()),\n // iterations INTEGER (XXX: Only support count < 65536)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(count).getBytes()\n )\n ]);\n }\n\n // PFX\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version (3)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(3).getBytes()),\n // PKCS#7 ContentInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // contentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n // OID for the content type is 'data'\n asn1.oidToDer(pki.oids.data).getBytes()),\n // content\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(safe).getBytes())\n ])\n ]),\n macData\n ]);\n};\n\n/**\n * Derives a PKCS#12 key.\n *\n * @param password the password to derive the key material from, null or\n * undefined for none.\n * @param salt the salt, as a ByteBuffer, to use.\n * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC).\n * @param iter the iteration count.\n * @param n the number of bytes to derive from the password.\n * @param md the message digest to use, defaults to SHA-1.\n *\n * @return a ByteBuffer with the bytes derived from the password.\n */\np12.generateKey = forge.pbe.generatePkcs12Key;\n","/**\n * Javascript implementation of a basic Public Key Infrastructure, including\n * support for RSA public and private keys.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./oids');\nrequire('./pbe');\nrequire('./pem');\nrequire('./pbkdf2');\nrequire('./pkcs12');\nrequire('./pss');\nrequire('./rsa');\nrequire('./util');\nrequire('./x509');\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n/* Public Key Infrastructure (PKI) implementation. */\nvar pki = module.exports = forge.pki = forge.pki || {};\n\n/**\n * NOTE: THIS METHOD IS DEPRECATED. Use pem.decode() instead.\n *\n * Converts PEM-formatted data to DER.\n *\n * @param pem the PEM-formatted data.\n *\n * @return the DER-formatted data.\n */\npki.pemToDer = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert PEM to DER; PEM is encrypted.');\n }\n return forge.util.createBuffer(msg.body);\n};\n\n/**\n * Converts an RSA private key from PEM format.\n *\n * @param pem the PEM-formatted private key.\n *\n * @return the private key.\n */\npki.privateKeyFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'PRIVATE KEY' && msg.type !== 'RSA PRIVATE KEY') {\n var error = new Error('Could not convert private key from PEM; PEM ' +\n 'header type is not \"PRIVATE KEY\" or \"RSA PRIVATE KEY\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert private key from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body);\n\n return pki.privateKeyFromAsn1(obj);\n};\n\n/**\n * Converts an RSA private key to PEM format.\n *\n * @param key the private key.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted private key.\n */\npki.privateKeyToPem = function(key, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'RSA PRIVATE KEY',\n body: asn1.toDer(pki.privateKeyToAsn1(key)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts a PrivateKeyInfo to PEM format.\n *\n * @param pki the PrivateKeyInfo.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted private key.\n */\npki.privateKeyInfoToPem = function(pki, maxline) {\n // convert to DER, then PEM-encode\n var msg = {\n type: 'PRIVATE KEY',\n body: asn1.toDer(pki).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n","/**\n * A Javascript implementation of Transport Layer Security (TLS).\n *\n * @author Dave Longley\n *\n * Copyright (c) 2009-2014 Digital Bazaar, Inc.\n *\n * The TLS Handshake Protocol involves the following steps:\n *\n * - Exchange hello messages to agree on algorithms, exchange random values,\n * and check for session resumption.\n *\n * - Exchange the necessary cryptographic parameters to allow the client and\n * server to agree on a premaster secret.\n *\n * - Exchange certificates and cryptographic information to allow the client\n * and server to authenticate themselves.\n *\n * - Generate a master secret from the premaster secret and exchanged random\n * values.\n *\n * - Provide security parameters to the record layer.\n *\n * - Allow the client and server to verify that their peer has calculated the\n * same security parameters and that the handshake occurred without tampering\n * by an attacker.\n *\n * Up to 4 different messages may be sent during a key exchange. The server\n * certificate, the server key exchange, the client certificate, and the\n * client key exchange.\n *\n * A typical handshake (from the client's perspective).\n *\n * 1. Client sends ClientHello.\n * 2. Client receives ServerHello.\n * 3. Client receives optional Certificate.\n * 4. Client receives optional ServerKeyExchange.\n * 5. Client receives ServerHelloDone.\n * 6. Client sends optional Certificate.\n * 7. Client sends ClientKeyExchange.\n * 8. Client sends optional CertificateVerify.\n * 9. Client sends ChangeCipherSpec.\n * 10. Client sends Finished.\n * 11. Client receives ChangeCipherSpec.\n * 12. Client receives Finished.\n * 13. Client sends/receives application data.\n *\n * To reuse an existing session:\n *\n * 1. Client sends ClientHello with session ID for reuse.\n * 2. Client receives ServerHello with same session ID if reusing.\n * 3. Client receives ChangeCipherSpec message if reusing.\n * 4. Client receives Finished.\n * 5. Client sends ChangeCipherSpec.\n * 6. Client sends Finished.\n *\n * Note: Client ignores HelloRequest if in the middle of a handshake.\n *\n * Record Layer:\n *\n * The record layer fragments information blocks into TLSPlaintext records\n * carrying data in chunks of 2^14 bytes or less. Client message boundaries are\n * not preserved in the record layer (i.e., multiple client messages of the\n * same ContentType MAY be coalesced into a single TLSPlaintext record, or a\n * single message MAY be fragmented across several records).\n *\n * struct {\n * uint8 major;\n * uint8 minor;\n * } ProtocolVersion;\n *\n * struct {\n * ContentType type;\n * ProtocolVersion version;\n * uint16 length;\n * opaque fragment[TLSPlaintext.length];\n * } TLSPlaintext;\n *\n * type:\n * The higher-level protocol used to process the enclosed fragment.\n *\n * version:\n * The version of the protocol being employed. TLS Version 1.2 uses version\n * {3, 3}. TLS Version 1.0 uses version {3, 1}. Note that a client that\n * supports multiple versions of TLS may not know what version will be\n * employed before it receives the ServerHello.\n *\n * length:\n * The length (in bytes) of the following TLSPlaintext.fragment. The length\n * MUST NOT exceed 2^14 = 16384 bytes.\n *\n * fragment:\n * The application data. This data is transparent and treated as an\n * independent block to be dealt with by the higher-level protocol specified\n * by the type field.\n *\n * Implementations MUST NOT send zero-length fragments of Handshake, Alert, or\n * ChangeCipherSpec content types. Zero-length fragments of Application data\n * MAY be sent as they are potentially useful as a traffic analysis\n * countermeasure.\n *\n * Note: Data of different TLS record layer content types MAY be interleaved.\n * Application data is generally of lower precedence for transmission than\n * other content types. However, records MUST be delivered to the network in\n * the same order as they are protected by the record layer. Recipients MUST\n * receive and process interleaved application layer traffic during handshakes\n * subsequent to the first one on a connection.\n *\n * struct {\n * ContentType type; // same as TLSPlaintext.type\n * ProtocolVersion version;// same as TLSPlaintext.version\n * uint16 length;\n * opaque fragment[TLSCompressed.length];\n * } TLSCompressed;\n *\n * length:\n * The length (in bytes) of the following TLSCompressed.fragment.\n * The length MUST NOT exceed 2^14 + 1024.\n *\n * fragment:\n * The compressed form of TLSPlaintext.fragment.\n *\n * Note: A CompressionMethod.null operation is an identity operation; no fields\n * are altered. In this implementation, since no compression is supported,\n * uncompressed records are always the same as compressed records.\n *\n * Encryption Information:\n *\n * The encryption and MAC functions translate a TLSCompressed structure into a\n * TLSCiphertext. The decryption functions reverse the process. The MAC of the\n * record also includes a sequence number so that missing, extra, or repeated\n * messages are detectable.\n *\n * struct {\n * ContentType type;\n * ProtocolVersion version;\n * uint16 length;\n * select (SecurityParameters.cipher_type) {\n * case stream: GenericStreamCipher;\n * case block: GenericBlockCipher;\n * case aead: GenericAEADCipher;\n * } fragment;\n * } TLSCiphertext;\n *\n * type:\n * The type field is identical to TLSCompressed.type.\n *\n * version:\n * The version field is identical to TLSCompressed.version.\n *\n * length:\n * The length (in bytes) of the following TLSCiphertext.fragment.\n * The length MUST NOT exceed 2^14 + 2048.\n *\n * fragment:\n * The encrypted form of TLSCompressed.fragment, with the MAC.\n *\n * Note: Only CBC Block Ciphers are supported by this implementation.\n *\n * The TLSCompressed.fragment structures are converted to/from block\n * TLSCiphertext.fragment structures.\n *\n * struct {\n * opaque IV[SecurityParameters.record_iv_length];\n * block-ciphered struct {\n * opaque content[TLSCompressed.length];\n * opaque MAC[SecurityParameters.mac_length];\n * uint8 padding[GenericBlockCipher.padding_length];\n * uint8 padding_length;\n * };\n * } GenericBlockCipher;\n *\n * The MAC is generated as described in Section 6.2.3.1.\n *\n * IV:\n * The Initialization Vector (IV) SHOULD be chosen at random, and MUST be\n * unpredictable. Note that in versions of TLS prior to 1.1, there was no\n * IV field, and the last ciphertext block of the previous record (the \"CBC\n * residue\") was used as the IV. This was changed to prevent the attacks\n * described in [CBCATT]. For block ciphers, the IV length is of length\n * SecurityParameters.record_iv_length, which is equal to the\n * SecurityParameters.block_size.\n *\n * padding:\n * Padding that is added to force the length of the plaintext to be an\n * integral multiple of the block cipher's block length. The padding MAY be\n * any length up to 255 bytes, as long as it results in the\n * TLSCiphertext.length being an integral multiple of the block length.\n * Lengths longer than necessary might be desirable to frustrate attacks on\n * a protocol that are based on analysis of the lengths of exchanged\n * messages. Each uint8 in the padding data vector MUST be filled with the\n * padding length value. The receiver MUST check this padding and MUST use\n * the bad_record_mac alert to indicate padding errors.\n *\n * padding_length:\n * The padding length MUST be such that the total size of the\n * GenericBlockCipher structure is a multiple of the cipher's block length.\n * Legal values range from zero to 255, inclusive. This length specifies the\n * length of the padding field exclusive of the padding_length field itself.\n *\n * The encrypted data length (TLSCiphertext.length) is one more than the sum of\n * SecurityParameters.block_length, TLSCompressed.length,\n * SecurityParameters.mac_length, and padding_length.\n *\n * Example: If the block length is 8 bytes, the content length\n * (TLSCompressed.length) is 61 bytes, and the MAC length is 20 bytes, then the\n * length before padding is 82 bytes (this does not include the IV. Thus, the\n * padding length modulo 8 must be equal to 6 in order to make the total length\n * an even multiple of 8 bytes (the block length). The padding length can be\n * 6, 14, 22, and so on, through 254. If the padding length were the minimum\n * necessary, 6, the padding would be 6 bytes, each containing the value 6.\n * Thus, the last 8 octets of the GenericBlockCipher before block encryption\n * would be xx 06 06 06 06 06 06 06, where xx is the last octet of the MAC.\n *\n * Note: With block ciphers in CBC mode (Cipher Block Chaining), it is critical\n * that the entire plaintext of the record be known before any ciphertext is\n * transmitted. Otherwise, it is possible for the attacker to mount the attack\n * described in [CBCATT].\n *\n * Implementation note: Canvel et al. [CBCTIME] have demonstrated a timing\n * attack on CBC padding based on the time required to compute the MAC. In\n * order to defend against this attack, implementations MUST ensure that\n * record processing time is essentially the same whether or not the padding\n * is correct. In general, the best way to do this is to compute the MAC even\n * if the padding is incorrect, and only then reject the packet. For instance,\n * if the pad appears to be incorrect, the implementation might assume a\n * zero-length pad and then compute the MAC. This leaves a small timing\n * channel, since MAC performance depends, to some extent, on the size of the\n * data fragment, but it is not believed to be large enough to be exploitable,\n * due to the large block size of existing MACs and the small size of the\n * timing signal.\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./hmac');\nrequire('./md5');\nrequire('./pem');\nrequire('./pki');\nrequire('./random');\nrequire('./sha1');\nrequire('./util');\n\n/**\n * Generates pseudo random bytes by mixing the result of two hash functions,\n * MD5 and SHA-1.\n *\n * prf_TLS1(secret, label, seed) =\n * P_MD5(S1, label + seed) XOR P_SHA-1(S2, label + seed);\n *\n * Each P_hash function functions as follows:\n *\n * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +\n * HMAC_hash(secret, A(2) + seed) +\n * HMAC_hash(secret, A(3) + seed) + ...\n * A() is defined as:\n * A(0) = seed\n * A(i) = HMAC_hash(secret, A(i-1))\n *\n * The '+' operator denotes concatenation.\n *\n * As many iterations A(N) as are needed are performed to generate enough\n * pseudo random byte output. If an iteration creates more data than is\n * necessary, then it is truncated.\n *\n * Therefore:\n * A(1) = HMAC_hash(secret, A(0))\n * = HMAC_hash(secret, seed)\n * A(2) = HMAC_hash(secret, A(1))\n * = HMAC_hash(secret, HMAC_hash(secret, seed))\n *\n * Therefore:\n * P_hash(secret, seed) =\n * HMAC_hash(secret, HMAC_hash(secret, A(0)) + seed) +\n * HMAC_hash(secret, HMAC_hash(secret, A(1)) + seed) +\n * ...\n *\n * Therefore:\n * P_hash(secret, seed) =\n * HMAC_hash(secret, HMAC_hash(secret, seed) + seed) +\n * HMAC_hash(secret, HMAC_hash(secret, HMAC_hash(secret, seed)) + seed) +\n * ...\n *\n * @param secret the secret to use.\n * @param label the label to use.\n * @param seed the seed value to use.\n * @param length the number of bytes to generate.\n *\n * @return the pseudo random bytes in a byte buffer.\n */\nvar prf_TLS1 = function(secret, label, seed, length) {\n var rval = forge.util.createBuffer();\n\n /* For TLS 1.0, the secret is split in half, into two secrets of equal\n length. If the secret has an odd length then the last byte of the first\n half will be the same as the first byte of the second. The length of the\n two secrets is half of the secret rounded up. */\n var idx = (secret.length >> 1);\n var slen = idx + (secret.length & 1);\n var s1 = secret.substr(0, slen);\n var s2 = secret.substr(idx, slen);\n var ai = forge.util.createBuffer();\n var hmac = forge.hmac.create();\n seed = label + seed;\n\n // determine the number of iterations that must be performed to generate\n // enough output bytes, md5 creates 16 byte hashes, sha1 creates 20\n var md5itr = Math.ceil(length / 16);\n var sha1itr = Math.ceil(length / 20);\n\n // do md5 iterations\n hmac.start('MD5', s1);\n var md5bytes = forge.util.createBuffer();\n ai.putBytes(seed);\n for(var i = 0; i < md5itr; ++i) {\n // HMAC_hash(secret, A(i-1))\n hmac.start(null, null);\n hmac.update(ai.getBytes());\n ai.putBuffer(hmac.digest());\n\n // HMAC_hash(secret, A(i) + seed)\n hmac.start(null, null);\n hmac.update(ai.bytes() + seed);\n md5bytes.putBuffer(hmac.digest());\n }\n\n // do sha1 iterations\n hmac.start('SHA1', s2);\n var sha1bytes = forge.util.createBuffer();\n ai.clear();\n ai.putBytes(seed);\n for(var i = 0; i < sha1itr; ++i) {\n // HMAC_hash(secret, A(i-1))\n hmac.start(null, null);\n hmac.update(ai.getBytes());\n ai.putBuffer(hmac.digest());\n\n // HMAC_hash(secret, A(i) + seed)\n hmac.start(null, null);\n hmac.update(ai.bytes() + seed);\n sha1bytes.putBuffer(hmac.digest());\n }\n\n // XOR the md5 bytes with the sha1 bytes\n rval.putBytes(forge.util.xorBytes(\n md5bytes.getBytes(), sha1bytes.getBytes(), length));\n\n return rval;\n};\n\n/**\n * Generates pseudo random bytes using a SHA256 algorithm. For TLS 1.2.\n *\n * @param secret the secret to use.\n * @param label the label to use.\n * @param seed the seed value to use.\n * @param length the number of bytes to generate.\n *\n * @return the pseudo random bytes in a byte buffer.\n */\nvar prf_sha256 = function(secret, label, seed, length) {\n // FIXME: implement me for TLS 1.2\n};\n\n/**\n * Gets a MAC for a record using the SHA-1 hash algorithm.\n *\n * @param key the mac key.\n * @param state the sequence number (array of two 32-bit integers).\n * @param record the record.\n *\n * @return the sha-1 hash (20 bytes) for the given record.\n */\nvar hmac_sha1 = function(key, seqNum, record) {\n /* MAC is computed like so:\n HMAC_hash(\n key, seqNum +\n TLSCompressed.type +\n TLSCompressed.version +\n TLSCompressed.length +\n TLSCompressed.fragment)\n */\n var hmac = forge.hmac.create();\n hmac.start('SHA1', key);\n var b = forge.util.createBuffer();\n b.putInt32(seqNum[0]);\n b.putInt32(seqNum[1]);\n b.putByte(record.type);\n b.putByte(record.version.major);\n b.putByte(record.version.minor);\n b.putInt16(record.length);\n b.putBytes(record.fragment.bytes());\n hmac.update(b.getBytes());\n return hmac.digest().getBytes();\n};\n\n/**\n * Compresses the TLSPlaintext record into a TLSCompressed record using the\n * deflate algorithm.\n *\n * @param c the TLS connection.\n * @param record the TLSPlaintext record to compress.\n * @param s the ConnectionState to use.\n *\n * @return true on success, false on failure.\n */\nvar deflate = function(c, record, s) {\n var rval = false;\n\n try {\n var bytes = c.deflate(record.fragment.getBytes());\n record.fragment = forge.util.createBuffer(bytes);\n record.length = bytes.length;\n rval = true;\n } catch(ex) {\n // deflate error, fail out\n }\n\n return rval;\n};\n\n/**\n * Decompresses the TLSCompressed record into a TLSPlaintext record using the\n * deflate algorithm.\n *\n * @param c the TLS connection.\n * @param record the TLSCompressed record to decompress.\n * @param s the ConnectionState to use.\n *\n * @return true on success, false on failure.\n */\nvar inflate = function(c, record, s) {\n var rval = false;\n\n try {\n var bytes = c.inflate(record.fragment.getBytes());\n record.fragment = forge.util.createBuffer(bytes);\n record.length = bytes.length;\n rval = true;\n } catch(ex) {\n // inflate error, fail out\n }\n\n return rval;\n};\n\n/**\n * Reads a TLS variable-length vector from a byte buffer.\n *\n * Variable-length vectors are defined by specifying a subrange of legal\n * lengths, inclusively, using the notation <floor..ceiling>. When these are\n * encoded, the actual length precedes the vector's contents in the byte\n * stream. The length will be in the form of a number consuming as many bytes\n * as required to hold the vector's specified maximum (ceiling) length. A\n * variable-length vector with an actual length field of zero is referred to\n * as an empty vector.\n *\n * @param b the byte buffer.\n * @param lenBytes the number of bytes required to store the length.\n *\n * @return the resulting byte buffer.\n */\nvar readVector = function(b, lenBytes) {\n var len = 0;\n switch(lenBytes) {\n case 1:\n len = b.getByte();\n break;\n case 2:\n len = b.getInt16();\n break;\n case 3:\n len = b.getInt24();\n break;\n case 4:\n len = b.getInt32();\n break;\n }\n\n // read vector bytes into a new buffer\n return forge.util.createBuffer(b.getBytes(len));\n};\n\n/**\n * Writes a TLS variable-length vector to a byte buffer.\n *\n * @param b the byte buffer.\n * @param lenBytes the number of bytes required to store the length.\n * @param v the byte buffer vector.\n */\nvar writeVector = function(b, lenBytes, v) {\n // encode length at the start of the vector, where the number of bytes for\n // the length is the maximum number of bytes it would take to encode the\n // vector's ceiling\n b.putInt(v.length(), lenBytes << 3);\n b.putBuffer(v);\n};\n\n/**\n * The tls implementation.\n */\nvar tls = {};\n\n/**\n * Version: TLS 1.2 = 3.3, TLS 1.1 = 3.2, TLS 1.0 = 3.1. Both TLS 1.1 and\n * TLS 1.2 were still too new (ie: openSSL didn't implement them) at the time\n * of this implementation so TLS 1.0 was implemented instead.\n */\ntls.Versions = {\n TLS_1_0: {major: 3, minor: 1},\n TLS_1_1: {major: 3, minor: 2},\n TLS_1_2: {major: 3, minor: 3}\n};\ntls.SupportedVersions = [\n tls.Versions.TLS_1_1,\n tls.Versions.TLS_1_0\n];\ntls.Version = tls.SupportedVersions[0];\n\n/**\n * Maximum fragment size. True maximum is 16384, but we fragment before that\n * to allow for unusual small increases during compression.\n */\ntls.MaxFragment = 16384 - 1024;\n\n/**\n * Whether this entity is considered the \"client\" or \"server\".\n * enum { server, client } ConnectionEnd;\n */\ntls.ConnectionEnd = {\n server: 0,\n client: 1\n};\n\n/**\n * Pseudo-random function algorithm used to generate keys from the master\n * secret.\n * enum { tls_prf_sha256 } PRFAlgorithm;\n */\ntls.PRFAlgorithm = {\n tls_prf_sha256: 0\n};\n\n/**\n * Bulk encryption algorithms.\n * enum { null, rc4, des3, aes } BulkCipherAlgorithm;\n */\ntls.BulkCipherAlgorithm = {\n none: null,\n rc4: 0,\n des3: 1,\n aes: 2\n};\n\n/**\n * Cipher types.\n * enum { stream, block, aead } CipherType;\n */\ntls.CipherType = {\n stream: 0,\n block: 1,\n aead: 2\n};\n\n/**\n * MAC (Message Authentication Code) algorithms.\n * enum { null, hmac_md5, hmac_sha1, hmac_sha256,\n * hmac_sha384, hmac_sha512} MACAlgorithm;\n */\ntls.MACAlgorithm = {\n none: null,\n hmac_md5: 0,\n hmac_sha1: 1,\n hmac_sha256: 2,\n hmac_sha384: 3,\n hmac_sha512: 4\n};\n\n/**\n * Compression algorithms.\n * enum { null(0), deflate(1), (255) } CompressionMethod;\n */\ntls.CompressionMethod = {\n none: 0,\n deflate: 1\n};\n\n/**\n * TLS record content types.\n * enum {\n * change_cipher_spec(20), alert(21), handshake(22),\n * application_data(23), (255)\n * } ContentType;\n */\ntls.ContentType = {\n change_cipher_spec: 20,\n alert: 21,\n handshake: 22,\n application_data: 23,\n heartbeat: 24\n};\n\n/**\n * TLS handshake types.\n * enum {\n * hello_request(0), client_hello(1), server_hello(2),\n * certificate(11), server_key_exchange (12),\n * certificate_request(13), server_hello_done(14),\n * certificate_verify(15), client_key_exchange(16),\n * finished(20), (255)\n * } HandshakeType;\n */\ntls.HandshakeType = {\n hello_request: 0,\n client_hello: 1,\n server_hello: 2,\n certificate: 11,\n server_key_exchange: 12,\n certificate_request: 13,\n server_hello_done: 14,\n certificate_verify: 15,\n client_key_exchange: 16,\n finished: 20\n};\n\n/**\n * TLS Alert Protocol.\n *\n * enum { warning(1), fatal(2), (255) } AlertLevel;\n *\n * enum {\n * close_notify(0),\n * unexpected_message(10),\n * bad_record_mac(20),\n * decryption_failed(21),\n * record_overflow(22),\n * decompression_failure(30),\n * handshake_failure(40),\n * bad_certificate(42),\n * unsupported_certificate(43),\n * certificate_revoked(44),\n * certificate_expired(45),\n * certificate_unknown(46),\n * illegal_parameter(47),\n * unknown_ca(48),\n * access_denied(49),\n * decode_error(50),\n * decrypt_error(51),\n * export_restriction(60),\n * protocol_version(70),\n * insufficient_security(71),\n * internal_error(80),\n * user_canceled(90),\n * no_renegotiation(100),\n * (255)\n * } AlertDescription;\n *\n * struct {\n * AlertLevel level;\n * AlertDescription description;\n * } Alert;\n */\ntls.Alert = {};\ntls.Alert.Level = {\n warning: 1,\n fatal: 2\n};\ntls.Alert.Description = {\n close_notify: 0,\n unexpected_message: 10,\n bad_record_mac: 20,\n decryption_failed: 21,\n record_overflow: 22,\n decompression_failure: 30,\n handshake_failure: 40,\n bad_certificate: 42,\n unsupported_certificate: 43,\n certificate_revoked: 44,\n certificate_expired: 45,\n certificate_unknown: 46,\n illegal_parameter: 47,\n unknown_ca: 48,\n access_denied: 49,\n decode_error: 50,\n decrypt_error: 51,\n export_restriction: 60,\n protocol_version: 70,\n insufficient_security: 71,\n internal_error: 80,\n user_canceled: 90,\n no_renegotiation: 100\n};\n\n/**\n * TLS Heartbeat Message types.\n * enum {\n * heartbeat_request(1),\n * heartbeat_response(2),\n * (255)\n * } HeartbeatMessageType;\n */\ntls.HeartbeatMessageType = {\n heartbeat_request: 1,\n heartbeat_response: 2\n};\n\n/**\n * Supported cipher suites.\n */\ntls.CipherSuites = {};\n\n/**\n * Gets a supported cipher suite from its 2 byte ID.\n *\n * @param twoBytes two bytes in a string.\n *\n * @return the matching supported cipher suite or null.\n */\ntls.getCipherSuite = function(twoBytes) {\n var rval = null;\n for(var key in tls.CipherSuites) {\n var cs = tls.CipherSuites[key];\n if(cs.id[0] === twoBytes.charCodeAt(0) &&\n cs.id[1] === twoBytes.charCodeAt(1)) {\n rval = cs;\n break;\n }\n }\n return rval;\n};\n\n/**\n * Called when an unexpected record is encountered.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleUnexpected = function(c, record) {\n // if connection is client and closed, ignore unexpected messages\n var ignore = (!c.open && c.entity === tls.ConnectionEnd.client);\n if(!ignore) {\n c.error(c, {\n message: 'Unexpected message. Received TLS record out of order.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.unexpected_message\n }\n });\n }\n};\n\n/**\n * Called when a client receives a HelloRequest record.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleHelloRequest = function(c, record, length) {\n // ignore renegotiation requests from the server during a handshake, but\n // if handshaking, send a warning alert that renegotation is denied\n if(!c.handshaking && c.handshakes > 0) {\n // send alert warning\n tls.queue(c, tls.createAlert(c, {\n level: tls.Alert.Level.warning,\n description: tls.Alert.Description.no_renegotiation\n }));\n tls.flush(c);\n }\n\n // continue\n c.process();\n};\n\n/**\n * Parses a hello message from a ClientHello or ServerHello record.\n *\n * @param record the record to parse.\n *\n * @return the parsed message.\n */\ntls.parseHelloMessage = function(c, record, length) {\n var msg = null;\n\n var client = (c.entity === tls.ConnectionEnd.client);\n\n // minimum of 38 bytes in message\n if(length < 38) {\n c.error(c, {\n message: client ?\n 'Invalid ServerHello message. Message too short.' :\n 'Invalid ClientHello message. Message too short.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n } else {\n // use 'remaining' to calculate # of remaining bytes in the message\n var b = record.fragment;\n var remaining = b.length();\n msg = {\n version: {\n major: b.getByte(),\n minor: b.getByte()\n },\n random: forge.util.createBuffer(b.getBytes(32)),\n session_id: readVector(b, 1),\n extensions: []\n };\n if(client) {\n msg.cipher_suite = b.getBytes(2);\n msg.compression_method = b.getByte();\n } else {\n msg.cipher_suites = readVector(b, 2);\n msg.compression_methods = readVector(b, 1);\n }\n\n // read extensions if there are any bytes left in the message\n remaining = length - (remaining - b.length());\n if(remaining > 0) {\n // parse extensions\n var exts = readVector(b, 2);\n while(exts.length() > 0) {\n msg.extensions.push({\n type: [exts.getByte(), exts.getByte()],\n data: readVector(exts, 2)\n });\n }\n\n // TODO: make extension support modular\n if(!client) {\n for(var i = 0; i < msg.extensions.length; ++i) {\n var ext = msg.extensions[i];\n\n // support SNI extension\n if(ext.type[0] === 0x00 && ext.type[1] === 0x00) {\n // get server name list\n var snl = readVector(ext.data, 2);\n while(snl.length() > 0) {\n // read server name type\n var snType = snl.getByte();\n\n // only HostName type (0x00) is known, break out if\n // another type is detected\n if(snType !== 0x00) {\n break;\n }\n\n // add host name to server name list\n c.session.extensions.server_name.serverNameList.push(\n readVector(snl, 2).getBytes());\n }\n }\n }\n }\n }\n\n // version already set, do not allow version change\n if(c.session.version) {\n if(msg.version.major !== c.session.version.major ||\n msg.version.minor !== c.session.version.minor) {\n return c.error(c, {\n message: 'TLS version change is disallowed during renegotiation.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.protocol_version\n }\n });\n }\n }\n\n // get the chosen (ServerHello) cipher suite\n if(client) {\n // FIXME: should be checking configured acceptable cipher suites\n c.session.cipherSuite = tls.getCipherSuite(msg.cipher_suite);\n } else {\n // get a supported preferred (ClientHello) cipher suite\n // choose the first supported cipher suite\n var tmp = forge.util.createBuffer(msg.cipher_suites.bytes());\n while(tmp.length() > 0) {\n // FIXME: should be checking configured acceptable suites\n // cipher suites take up 2 bytes\n c.session.cipherSuite = tls.getCipherSuite(tmp.getBytes(2));\n if(c.session.cipherSuite !== null) {\n break;\n }\n }\n }\n\n // cipher suite not supported\n if(c.session.cipherSuite === null) {\n return c.error(c, {\n message: 'No cipher suites in common.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.handshake_failure\n },\n cipherSuite: forge.util.bytesToHex(msg.cipher_suite)\n });\n }\n\n // TODO: handle compression methods\n if(client) {\n c.session.compressionMethod = msg.compression_method;\n } else {\n // no compression\n c.session.compressionMethod = tls.CompressionMethod.none;\n }\n }\n\n return msg;\n};\n\n/**\n * Creates security parameters for the given connection based on the given\n * hello message.\n *\n * @param c the TLS connection.\n * @param msg the hello message.\n */\ntls.createSecurityParameters = function(c, msg) {\n /* Note: security params are from TLS 1.2, some values like prf_algorithm\n are ignored for TLS 1.0/1.1 and the builtin as specified in the spec is\n used. */\n\n // TODO: handle other options from server when more supported\n\n // get client and server randoms\n var client = (c.entity === tls.ConnectionEnd.client);\n var msgRandom = msg.random.bytes();\n var cRandom = client ? c.session.sp.client_random : msgRandom;\n var sRandom = client ? msgRandom : tls.createRandom().getBytes();\n\n // create new security parameters\n c.session.sp = {\n entity: c.entity,\n prf_algorithm: tls.PRFAlgorithm.tls_prf_sha256,\n bulk_cipher_algorithm: null,\n cipher_type: null,\n enc_key_length: null,\n block_length: null,\n fixed_iv_length: null,\n record_iv_length: null,\n mac_algorithm: null,\n mac_length: null,\n mac_key_length: null,\n compression_algorithm: c.session.compressionMethod,\n pre_master_secret: null,\n master_secret: null,\n client_random: cRandom,\n server_random: sRandom\n };\n};\n\n/**\n * Called when a client receives a ServerHello record.\n *\n * When a ServerHello message will be sent:\n * The server will send this message in response to a client hello message\n * when it was able to find an acceptable set of algorithms. If it cannot\n * find such a match, it will respond with a handshake failure alert.\n *\n * uint24 length;\n * struct {\n * ProtocolVersion server_version;\n * Random random;\n * SessionID session_id;\n * CipherSuite cipher_suite;\n * CompressionMethod compression_method;\n * select(extensions_present) {\n * case false:\n * struct {};\n * case true:\n * Extension extensions<0..2^16-1>;\n * };\n * } ServerHello;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleServerHello = function(c, record, length) {\n var msg = tls.parseHelloMessage(c, record, length);\n if(c.fail) {\n return;\n }\n\n // ensure server version is compatible\n if(msg.version.minor <= c.version.minor) {\n c.version.minor = msg.version.minor;\n } else {\n return c.error(c, {\n message: 'Incompatible TLS version.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.protocol_version\n }\n });\n }\n\n // indicate session version has been set\n c.session.version = c.version;\n\n // get the session ID from the message\n var sessionId = msg.session_id.bytes();\n\n // if the session ID is not blank and matches the cached one, resume\n // the session\n if(sessionId.length > 0 && sessionId === c.session.id) {\n // resuming session, expect a ChangeCipherSpec next\n c.expect = SCC;\n c.session.resuming = true;\n\n // get new server random\n c.session.sp.server_random = msg.random.bytes();\n } else {\n // not resuming, expect a server Certificate message next\n c.expect = SCE;\n c.session.resuming = false;\n\n // create new security parameters\n tls.createSecurityParameters(c, msg);\n }\n\n // set new session ID\n c.session.id = sessionId;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a server receives a ClientHello record.\n *\n * When a ClientHello message will be sent:\n * When a client first connects to a server it is required to send the\n * client hello as its first message. The client can also send a client\n * hello in response to a hello request or on its own initiative in order\n * to renegotiate the security parameters in an existing connection.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleClientHello = function(c, record, length) {\n var msg = tls.parseHelloMessage(c, record, length);\n if(c.fail) {\n return;\n }\n\n // get the session ID from the message\n var sessionId = msg.session_id.bytes();\n\n // see if the given session ID is in the cache\n var session = null;\n if(c.sessionCache) {\n session = c.sessionCache.getSession(sessionId);\n if(session === null) {\n // session ID not found\n sessionId = '';\n } else if(session.version.major !== msg.version.major ||\n session.version.minor > msg.version.minor) {\n // if session version is incompatible with client version, do not resume\n session = null;\n sessionId = '';\n }\n }\n\n // no session found to resume, generate a new session ID\n if(sessionId.length === 0) {\n sessionId = forge.random.getBytes(32);\n }\n\n // update session\n c.session.id = sessionId;\n c.session.clientHelloVersion = msg.version;\n c.session.sp = {};\n if(session) {\n // use version and security parameters from resumed session\n c.version = c.session.version = session.version;\n c.session.sp = session.sp;\n } else {\n // use highest compatible minor version\n var version;\n for(var i = 1; i < tls.SupportedVersions.length; ++i) {\n version = tls.SupportedVersions[i];\n if(version.minor <= msg.version.minor) {\n break;\n }\n }\n c.version = {major: version.major, minor: version.minor};\n c.session.version = c.version;\n }\n\n // if a session is set, resume it\n if(session !== null) {\n // resuming session, expect a ChangeCipherSpec next\n c.expect = CCC;\n c.session.resuming = true;\n\n // get new client random\n c.session.sp.client_random = msg.random.bytes();\n } else {\n // not resuming, expect a Certificate or ClientKeyExchange\n c.expect = (c.verifyClient !== false) ? CCE : CKE;\n c.session.resuming = false;\n\n // create new security parameters\n tls.createSecurityParameters(c, msg);\n }\n\n // connection now open\n c.open = true;\n\n // queue server hello\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createServerHello(c)\n }));\n\n if(c.session.resuming) {\n // queue change cipher spec message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.change_cipher_spec,\n data: tls.createChangeCipherSpec()\n }));\n\n // create pending state\n c.state.pending = tls.createConnectionState(c);\n\n // change current write state to pending write state\n c.state.current.write = c.state.pending.write;\n\n // queue finished\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createFinished(c)\n }));\n } else {\n // queue server certificate\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createCertificate(c)\n }));\n\n if(!c.fail) {\n // queue server key exchange\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createServerKeyExchange(c)\n }));\n\n // request client certificate if set\n if(c.verifyClient !== false) {\n // queue certificate request\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createCertificateRequest(c)\n }));\n }\n\n // queue server hello done\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createServerHelloDone(c)\n }));\n }\n }\n\n // send records\n tls.flush(c);\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a Certificate record.\n *\n * When this message will be sent:\n * The server must send a certificate whenever the agreed-upon key exchange\n * method is not an anonymous one. This message will always immediately\n * follow the server hello message.\n *\n * Meaning of this message:\n * The certificate type must be appropriate for the selected cipher suite's\n * key exchange algorithm, and is generally an X.509v3 certificate. It must\n * contain a key which matches the key exchange method, as follows. Unless\n * otherwise specified, the signing algorithm for the certificate must be\n * the same as the algorithm for the certificate key. Unless otherwise\n * specified, the public key may be of any length.\n *\n * opaque ASN.1Cert<1..2^24-1>;\n * struct {\n * ASN.1Cert certificate_list<1..2^24-1>;\n * } Certificate;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleCertificate = function(c, record, length) {\n // minimum of 3 bytes in message\n if(length < 3) {\n return c.error(c, {\n message: 'Invalid Certificate message. Message too short.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n }\n\n var b = record.fragment;\n var msg = {\n certificate_list: readVector(b, 3)\n };\n\n /* The sender's certificate will be first in the list (chain), each\n subsequent one that follows will certify the previous one, but root\n certificates (self-signed) that specify the certificate authority may\n be omitted under the assumption that clients must already possess it. */\n var cert, asn1;\n var certs = [];\n try {\n while(msg.certificate_list.length() > 0) {\n // each entry in msg.certificate_list is a vector with 3 len bytes\n cert = readVector(msg.certificate_list, 3);\n asn1 = forge.asn1.fromDer(cert);\n cert = forge.pki.certificateFromAsn1(asn1, true);\n certs.push(cert);\n }\n } catch(ex) {\n return c.error(c, {\n message: 'Could not parse certificate list.',\n cause: ex,\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.bad_certificate\n }\n });\n }\n\n // ensure at least 1 certificate was provided if in client-mode\n // or if verifyClient was set to true to require a certificate\n // (as opposed to 'optional')\n var client = (c.entity === tls.ConnectionEnd.client);\n if((client || c.verifyClient === true) && certs.length === 0) {\n // error, no certificate\n c.error(c, {\n message: client ?\n 'No server certificate provided.' :\n 'No client certificate provided.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n } else if(certs.length === 0) {\n // no certs to verify\n // expect a ServerKeyExchange or ClientKeyExchange message next\n c.expect = client ? SKE : CKE;\n } else {\n // save certificate in session\n if(client) {\n c.session.serverCertificate = certs[0];\n } else {\n c.session.clientCertificate = certs[0];\n }\n\n if(tls.verifyCertificateChain(c, certs)) {\n // expect a ServerKeyExchange or ClientKeyExchange message next\n c.expect = client ? SKE : CKE;\n }\n }\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a ServerKeyExchange record.\n *\n * When this message will be sent:\n * This message will be sent immediately after the server certificate\n * message (or the server hello message, if this is an anonymous\n * negotiation).\n *\n * The server key exchange message is sent by the server only when the\n * server certificate message (if sent) does not contain enough data to\n * allow the client to exchange a premaster secret.\n *\n * Meaning of this message:\n * This message conveys cryptographic information to allow the client to\n * communicate the premaster secret: either an RSA public key to encrypt\n * the premaster secret with, or a Diffie-Hellman public key with which the\n * client can complete a key exchange (with the result being the premaster\n * secret.)\n *\n * enum {\n * dhe_dss, dhe_rsa, dh_anon, rsa, dh_dss, dh_rsa\n * } KeyExchangeAlgorithm;\n *\n * struct {\n * opaque dh_p<1..2^16-1>;\n * opaque dh_g<1..2^16-1>;\n * opaque dh_Ys<1..2^16-1>;\n * } ServerDHParams;\n *\n * struct {\n * select(KeyExchangeAlgorithm) {\n * case dh_anon:\n * ServerDHParams params;\n * case dhe_dss:\n * case dhe_rsa:\n * ServerDHParams params;\n * digitally-signed struct {\n * opaque client_random[32];\n * opaque server_random[32];\n * ServerDHParams params;\n * } signed_params;\n * case rsa:\n * case dh_dss:\n * case dh_rsa:\n * struct {};\n * };\n * } ServerKeyExchange;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleServerKeyExchange = function(c, record, length) {\n // this implementation only supports RSA, no Diffie-Hellman support\n // so any length > 0 is invalid\n if(length > 0) {\n return c.error(c, {\n message: 'Invalid key parameters. Only RSA is supported.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.unsupported_certificate\n }\n });\n }\n\n // expect an optional CertificateRequest message next\n c.expect = SCR;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a ClientKeyExchange record.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleClientKeyExchange = function(c, record, length) {\n // this implementation only supports RSA, no Diffie-Hellman support\n // so any length < 48 is invalid\n if(length < 48) {\n return c.error(c, {\n message: 'Invalid key parameters. Only RSA is supported.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.unsupported_certificate\n }\n });\n }\n\n var b = record.fragment;\n var msg = {\n enc_pre_master_secret: readVector(b, 2).getBytes()\n };\n\n // do rsa decryption\n var privateKey = null;\n if(c.getPrivateKey) {\n try {\n privateKey = c.getPrivateKey(c, c.session.serverCertificate);\n privateKey = forge.pki.privateKeyFromPem(privateKey);\n } catch(ex) {\n c.error(c, {\n message: 'Could not get private key.',\n cause: ex,\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n }\n }\n\n if(privateKey === null) {\n return c.error(c, {\n message: 'No private key set.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n }\n\n try {\n // decrypt 48-byte pre-master secret\n var sp = c.session.sp;\n sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret);\n\n // ensure client hello version matches first 2 bytes\n var version = c.session.clientHelloVersion;\n if(version.major !== sp.pre_master_secret.charCodeAt(0) ||\n version.minor !== sp.pre_master_secret.charCodeAt(1)) {\n // error, do not send alert (see BLEI attack below)\n throw new Error('TLS version rollback attack detected.');\n }\n } catch(ex) {\n /* Note: Daniel Bleichenbacher [BLEI] can be used to attack a\n TLS server which is using PKCS#1 encoded RSA, so instead of\n failing here, we generate 48 random bytes and use that as\n the pre-master secret. */\n sp.pre_master_secret = forge.random.getBytes(48);\n }\n\n // expect a CertificateVerify message if a Certificate was received that\n // does not have fixed Diffie-Hellman params, otherwise expect\n // ChangeCipherSpec\n c.expect = CCC;\n if(c.session.clientCertificate !== null) {\n // only RSA support, so expect CertificateVerify\n // TODO: support Diffie-Hellman\n c.expect = CCV;\n }\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a CertificateRequest record.\n *\n * When this message will be sent:\n * A non-anonymous server can optionally request a certificate from the\n * client, if appropriate for the selected cipher suite. This message, if\n * sent, will immediately follow the Server Key Exchange message (if it is\n * sent; otherwise, the Server Certificate message).\n *\n * enum {\n * rsa_sign(1), dss_sign(2), rsa_fixed_dh(3), dss_fixed_dh(4),\n * rsa_ephemeral_dh_RESERVED(5), dss_ephemeral_dh_RESERVED(6),\n * fortezza_dms_RESERVED(20), (255)\n * } ClientCertificateType;\n *\n * opaque DistinguishedName<1..2^16-1>;\n *\n * struct {\n * ClientCertificateType certificate_types<1..2^8-1>;\n * SignatureAndHashAlgorithm supported_signature_algorithms<2^16-1>;\n * DistinguishedName certificate_authorities<0..2^16-1>;\n * } CertificateRequest;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleCertificateRequest = function(c, record, length) {\n // minimum of 3 bytes in message\n if(length < 3) {\n return c.error(c, {\n message: 'Invalid CertificateRequest. Message too short.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n }\n\n // TODO: TLS 1.2+ has different format including\n // SignatureAndHashAlgorithm after cert types\n var b = record.fragment;\n var msg = {\n certificate_types: readVector(b, 1),\n certificate_authorities: readVector(b, 2)\n };\n\n // save certificate request in session\n c.session.certificateRequest = msg;\n\n // expect a ServerHelloDone message next\n c.expect = SHD;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a server receives a CertificateVerify record.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleCertificateVerify = function(c, record, length) {\n if(length < 2) {\n return c.error(c, {\n message: 'Invalid CertificateVerify. Message too short.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n }\n\n // rewind to get full bytes for message so it can be manually\n // digested below (special case for CertificateVerify messages because\n // they must be digested *after* handling as opposed to all others)\n var b = record.fragment;\n b.read -= 4;\n var msgBytes = b.bytes();\n b.read += 4;\n\n var msg = {\n signature: readVector(b, 2).getBytes()\n };\n\n // TODO: add support for DSA\n\n // generate data to verify\n var verify = forge.util.createBuffer();\n verify.putBuffer(c.session.md5.digest());\n verify.putBuffer(c.session.sha1.digest());\n verify = verify.getBytes();\n\n try {\n var cert = c.session.clientCertificate;\n /*b = forge.pki.rsa.decrypt(\n msg.signature, cert.publicKey, true, verify.length);\n if(b !== verify) {*/\n if(!cert.publicKey.verify(verify, msg.signature, 'NONE')) {\n throw new Error('CertificateVerify signature does not match.');\n }\n\n // digest message now that it has been handled\n c.session.md5.update(msgBytes);\n c.session.sha1.update(msgBytes);\n } catch(ex) {\n return c.error(c, {\n message: 'Bad signature in CertificateVerify.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.handshake_failure\n }\n });\n }\n\n // expect ChangeCipherSpec\n c.expect = CCC;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a ServerHelloDone record.\n *\n * When this message will be sent:\n * The server hello done message is sent by the server to indicate the end\n * of the server hello and associated messages. After sending this message\n * the server will wait for a client response.\n *\n * Meaning of this message:\n * This message means that the server is done sending messages to support\n * the key exchange, and the client can proceed with its phase of the key\n * exchange.\n *\n * Upon receipt of the server hello done message the client should verify\n * that the server provided a valid certificate if required and check that\n * the server hello parameters are acceptable.\n *\n * struct {} ServerHelloDone;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleServerHelloDone = function(c, record, length) {\n // len must be 0 bytes\n if(length > 0) {\n return c.error(c, {\n message: 'Invalid ServerHelloDone message. Invalid length.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.record_overflow\n }\n });\n }\n\n if(c.serverCertificate === null) {\n // no server certificate was provided\n var error = {\n message: 'No server certificate provided. Not enough security.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.insufficient_security\n }\n };\n\n // call application callback\n var depth = 0;\n var ret = c.verify(c, error.alert.description, depth, []);\n if(ret !== true) {\n // check for custom alert info\n if(ret || ret === 0) {\n // set custom message and alert description\n if(typeof ret === 'object' && !forge.util.isArray(ret)) {\n if(ret.message) {\n error.message = ret.message;\n }\n if(ret.alert) {\n error.alert.description = ret.alert;\n }\n } else if(typeof ret === 'number') {\n // set custom alert description\n error.alert.description = ret;\n }\n }\n\n // send error\n return c.error(c, error);\n }\n }\n\n // create client certificate message if requested\n if(c.session.certificateRequest !== null) {\n record = tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createCertificate(c)\n });\n tls.queue(c, record);\n }\n\n // create client key exchange message\n record = tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createClientKeyExchange(c)\n });\n tls.queue(c, record);\n\n // expect no messages until the following callback has been called\n c.expect = SER;\n\n // create callback to handle client signature (for client-certs)\n var callback = function(c, signature) {\n if(c.session.certificateRequest !== null &&\n c.session.clientCertificate !== null) {\n // create certificate verify message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createCertificateVerify(c, signature)\n }));\n }\n\n // create change cipher spec message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.change_cipher_spec,\n data: tls.createChangeCipherSpec()\n }));\n\n // create pending state\n c.state.pending = tls.createConnectionState(c);\n\n // change current write state to pending write state\n c.state.current.write = c.state.pending.write;\n\n // create finished message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createFinished(c)\n }));\n\n // expect a server ChangeCipherSpec message next\n c.expect = SCC;\n\n // send records\n tls.flush(c);\n\n // continue\n c.process();\n };\n\n // if there is no certificate request or no client certificate, do\n // callback immediately\n if(c.session.certificateRequest === null ||\n c.session.clientCertificate === null) {\n return callback(c, null);\n }\n\n // otherwise get the client signature\n tls.getClientSignature(c, callback);\n};\n\n/**\n * Called when a ChangeCipherSpec record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleChangeCipherSpec = function(c, record) {\n if(record.fragment.getByte() !== 0x01) {\n return c.error(c, {\n message: 'Invalid ChangeCipherSpec message received.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n }\n\n // create pending state if:\n // 1. Resuming session in client mode OR\n // 2. NOT resuming session in server mode\n var client = (c.entity === tls.ConnectionEnd.client);\n if((c.session.resuming && client) || (!c.session.resuming && !client)) {\n c.state.pending = tls.createConnectionState(c);\n }\n\n // change current read state to pending read state\n c.state.current.read = c.state.pending.read;\n\n // clear pending state if:\n // 1. NOT resuming session in client mode OR\n // 2. resuming a session in server mode\n if((!c.session.resuming && client) || (c.session.resuming && !client)) {\n c.state.pending = null;\n }\n\n // expect a Finished record next\n c.expect = client ? SFI : CFI;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a Finished record is received.\n *\n * When this message will be sent:\n * A finished message is always sent immediately after a change\n * cipher spec message to verify that the key exchange and\n * authentication processes were successful. It is essential that a\n * change cipher spec message be received between the other\n * handshake messages and the Finished message.\n *\n * Meaning of this message:\n * The finished message is the first protected with the just-\n * negotiated algorithms, keys, and secrets. Recipients of finished\n * messages must verify that the contents are correct. Once a side\n * has sent its Finished message and received and validated the\n * Finished message from its peer, it may begin to send and receive\n * application data over the connection.\n *\n * struct {\n * opaque verify_data[verify_data_length];\n * } Finished;\n *\n * verify_data\n * PRF(master_secret, finished_label, Hash(handshake_messages))\n * [0..verify_data_length-1];\n *\n * finished_label\n * For Finished messages sent by the client, the string\n * \"client finished\". For Finished messages sent by the server, the\n * string \"server finished\".\n *\n * verify_data_length depends on the cipher suite. If it is not specified\n * by the cipher suite, then it is 12. Versions of TLS < 1.2 always used\n * 12 bytes.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleFinished = function(c, record, length) {\n // rewind to get full bytes for message so it can be manually\n // digested below (special case for Finished messages because they\n // must be digested *after* handling as opposed to all others)\n var b = record.fragment;\n b.read -= 4;\n var msgBytes = b.bytes();\n b.read += 4;\n\n // message contains only verify_data\n var vd = record.fragment.getBytes();\n\n // ensure verify data is correct\n b = forge.util.createBuffer();\n b.putBuffer(c.session.md5.digest());\n b.putBuffer(c.session.sha1.digest());\n\n // set label based on entity type\n var client = (c.entity === tls.ConnectionEnd.client);\n var label = client ? 'server finished' : 'client finished';\n\n // TODO: determine prf function and verify length for TLS 1.2\n var sp = c.session.sp;\n var vdl = 12;\n var prf = prf_TLS1;\n b = prf(sp.master_secret, label, b.getBytes(), vdl);\n if(b.getBytes() !== vd) {\n return c.error(c, {\n message: 'Invalid verify_data in Finished message.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.decrypt_error\n }\n });\n }\n\n // digest finished message now that it has been handled\n c.session.md5.update(msgBytes);\n c.session.sha1.update(msgBytes);\n\n // resuming session as client or NOT resuming session as server\n if((c.session.resuming && client) || (!c.session.resuming && !client)) {\n // create change cipher spec message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.change_cipher_spec,\n data: tls.createChangeCipherSpec()\n }));\n\n // change current write state to pending write state, clear pending\n c.state.current.write = c.state.pending.write;\n c.state.pending = null;\n\n // create finished message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createFinished(c)\n }));\n }\n\n // expect application data next\n c.expect = client ? SAD : CAD;\n\n // handshake complete\n c.handshaking = false;\n ++c.handshakes;\n\n // save access to peer certificate\n c.peerCertificate = client ?\n c.session.serverCertificate : c.session.clientCertificate;\n\n // send records\n tls.flush(c);\n\n // now connected\n c.isConnected = true;\n c.connected(c);\n\n // continue\n c.process();\n};\n\n/**\n * Called when an Alert record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleAlert = function(c, record) {\n // read alert\n var b = record.fragment;\n var alert = {\n level: b.getByte(),\n description: b.getByte()\n };\n\n // TODO: consider using a table?\n // get appropriate message\n var msg;\n switch(alert.description) {\n case tls.Alert.Description.close_notify:\n msg = 'Connection closed.';\n break;\n case tls.Alert.Description.unexpected_message:\n msg = 'Unexpected message.';\n break;\n case tls.Alert.Description.bad_record_mac:\n msg = 'Bad record MAC.';\n break;\n case tls.Alert.Description.decryption_failed:\n msg = 'Decryption failed.';\n break;\n case tls.Alert.Description.record_overflow:\n msg = 'Record overflow.';\n break;\n case tls.Alert.Description.decompression_failure:\n msg = 'Decompression failed.';\n break;\n case tls.Alert.Description.handshake_failure:\n msg = 'Handshake failure.';\n break;\n case tls.Alert.Description.bad_certificate:\n msg = 'Bad certificate.';\n break;\n case tls.Alert.Description.unsupported_certificate:\n msg = 'Unsupported certificate.';\n break;\n case tls.Alert.Description.certificate_revoked:\n msg = 'Certificate revoked.';\n break;\n case tls.Alert.Description.certificate_expired:\n msg = 'Certificate expired.';\n break;\n case tls.Alert.Description.certificate_unknown:\n msg = 'Certificate unknown.';\n break;\n case tls.Alert.Description.illegal_parameter:\n msg = 'Illegal parameter.';\n break;\n case tls.Alert.Description.unknown_ca:\n msg = 'Unknown certificate authority.';\n break;\n case tls.Alert.Description.access_denied:\n msg = 'Access denied.';\n break;\n case tls.Alert.Description.decode_error:\n msg = 'Decode error.';\n break;\n case tls.Alert.Description.decrypt_error:\n msg = 'Decrypt error.';\n break;\n case tls.Alert.Description.export_restriction:\n msg = 'Export restriction.';\n break;\n case tls.Alert.Description.protocol_version:\n msg = 'Unsupported protocol version.';\n break;\n case tls.Alert.Description.insufficient_security:\n msg = 'Insufficient security.';\n break;\n case tls.Alert.Description.internal_error:\n msg = 'Internal error.';\n break;\n case tls.Alert.Description.user_canceled:\n msg = 'User canceled.';\n break;\n case tls.Alert.Description.no_renegotiation:\n msg = 'Renegotiation not supported.';\n break;\n default:\n msg = 'Unknown error.';\n break;\n }\n\n // close connection on close_notify, not an error\n if(alert.description === tls.Alert.Description.close_notify) {\n return c.close();\n }\n\n // call error handler\n c.error(c, {\n message: msg,\n send: false,\n // origin is the opposite end\n origin: (c.entity === tls.ConnectionEnd.client) ? 'server' : 'client',\n alert: alert\n });\n\n // continue\n c.process();\n};\n\n/**\n * Called when a Handshake record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleHandshake = function(c, record) {\n // get the handshake type and message length\n var b = record.fragment;\n var type = b.getByte();\n var length = b.getInt24();\n\n // see if the record fragment doesn't yet contain the full message\n if(length > b.length()) {\n // cache the record, clear its fragment, and reset the buffer read\n // pointer before the type and length were read\n c.fragmented = record;\n record.fragment = forge.util.createBuffer();\n b.read -= 4;\n\n // continue\n return c.process();\n }\n\n // full message now available, clear cache, reset read pointer to\n // before type and length\n c.fragmented = null;\n b.read -= 4;\n\n // save the handshake bytes for digestion after handler is found\n // (include type and length of handshake msg)\n var bytes = b.bytes(length + 4);\n\n // restore read pointer\n b.read += 4;\n\n // handle expected message\n if(type in hsTable[c.entity][c.expect]) {\n // initialize server session\n if(c.entity === tls.ConnectionEnd.server && !c.open && !c.fail) {\n c.handshaking = true;\n c.session = {\n version: null,\n extensions: {\n server_name: {\n serverNameList: []\n }\n },\n cipherSuite: null,\n compressionMethod: null,\n serverCertificate: null,\n clientCertificate: null,\n md5: forge.md.md5.create(),\n sha1: forge.md.sha1.create()\n };\n }\n\n /* Update handshake messages digest. Finished and CertificateVerify\n messages are not digested here. They can't be digested as part of\n the verify_data that they contain. These messages are manually\n digested in their handlers. HelloRequest messages are simply never\n included in the handshake message digest according to spec. */\n if(type !== tls.HandshakeType.hello_request &&\n type !== tls.HandshakeType.certificate_verify &&\n type !== tls.HandshakeType.finished) {\n c.session.md5.update(bytes);\n c.session.sha1.update(bytes);\n }\n\n // handle specific handshake type record\n hsTable[c.entity][c.expect][type](c, record, length);\n } else {\n // unexpected record\n tls.handleUnexpected(c, record);\n }\n};\n\n/**\n * Called when an ApplicationData record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleApplicationData = function(c, record) {\n // buffer data, notify that its ready\n c.data.putBuffer(record.fragment);\n c.dataReady(c);\n\n // continue\n c.process();\n};\n\n/**\n * Called when a Heartbeat record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleHeartbeat = function(c, record) {\n // get the heartbeat type and payload\n var b = record.fragment;\n var type = b.getByte();\n var length = b.getInt16();\n var payload = b.getBytes(length);\n\n if(type === tls.HeartbeatMessageType.heartbeat_request) {\n // discard request during handshake or if length is too large\n if(c.handshaking || length > payload.length) {\n // continue\n return c.process();\n }\n // retransmit payload\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.heartbeat,\n data: tls.createHeartbeat(\n tls.HeartbeatMessageType.heartbeat_response, payload)\n }));\n tls.flush(c);\n } else if(type === tls.HeartbeatMessageType.heartbeat_response) {\n // check payload against expected payload, discard heartbeat if no match\n if(payload !== c.expectedHeartbeatPayload) {\n // continue\n return c.process();\n }\n\n // notify that a valid heartbeat was received\n if(c.heartbeatReceived) {\n c.heartbeatReceived(c, forge.util.createBuffer(payload));\n }\n }\n\n // continue\n c.process();\n};\n\n/**\n * The transistional state tables for receiving TLS records. It maps the\n * current TLS engine state and a received record to a function to handle the\n * record and update the state.\n *\n * For instance, if the current state is SHE, then the TLS engine is expecting\n * a ServerHello record. Once a record is received, the handler function is\n * looked up using the state SHE and the record's content type.\n *\n * The resulting function will either be an error handler or a record handler.\n * The function will take whatever action is appropriate and update the state\n * for the next record.\n *\n * The states are all based on possible server record types. Note that the\n * client will never specifically expect to receive a HelloRequest or an alert\n * from the server so there is no state that reflects this. These messages may\n * occur at any time.\n *\n * There are two tables for mapping states because there is a second tier of\n * types for handshake messages. Once a record with a content type of handshake\n * is received, the handshake record handler will look up the handshake type in\n * the secondary map to get its appropriate handler.\n *\n * Valid message orders are as follows:\n *\n * =======================FULL HANDSHAKE======================\n * Client Server\n *\n * ClientHello -------->\n * ServerHello\n * Certificate*\n * ServerKeyExchange*\n * CertificateRequest*\n * <-------- ServerHelloDone\n * Certificate*\n * ClientKeyExchange\n * CertificateVerify*\n * [ChangeCipherSpec]\n * Finished -------->\n * [ChangeCipherSpec]\n * <-------- Finished\n * Application Data <-------> Application Data\n *\n * =====================SESSION RESUMPTION=====================\n * Client Server\n *\n * ClientHello -------->\n * ServerHello\n * [ChangeCipherSpec]\n * <-------- Finished\n * [ChangeCipherSpec]\n * Finished -------->\n * Application Data <-------> Application Data\n */\n// client expect states (indicate which records are expected to be received)\nvar SHE = 0; // rcv server hello\nvar SCE = 1; // rcv server certificate\nvar SKE = 2; // rcv server key exchange\nvar SCR = 3; // rcv certificate request\nvar SHD = 4; // rcv server hello done\nvar SCC = 5; // rcv change cipher spec\nvar SFI = 6; // rcv finished\nvar SAD = 7; // rcv application data\nvar SER = 8; // not expecting any messages at this point\n\n// server expect states\nvar CHE = 0; // rcv client hello\nvar CCE = 1; // rcv client certificate\nvar CKE = 2; // rcv client key exchange\nvar CCV = 3; // rcv certificate verify\nvar CCC = 4; // rcv change cipher spec\nvar CFI = 5; // rcv finished\nvar CAD = 6; // rcv application data\nvar CER = 7; // not expecting any messages at this point\n\n// map client current expect state and content type to function\nvar __ = tls.handleUnexpected;\nvar R0 = tls.handleChangeCipherSpec;\nvar R1 = tls.handleAlert;\nvar R2 = tls.handleHandshake;\nvar R3 = tls.handleApplicationData;\nvar R4 = tls.handleHeartbeat;\nvar ctTable = [];\nctTable[tls.ConnectionEnd.client] = [\n// CC,AL,HS,AD,HB\n/*SHE*/[__,R1,R2,__,R4],\n/*SCE*/[__,R1,R2,__,R4],\n/*SKE*/[__,R1,R2,__,R4],\n/*SCR*/[__,R1,R2,__,R4],\n/*SHD*/[__,R1,R2,__,R4],\n/*SCC*/[R0,R1,__,__,R4],\n/*SFI*/[__,R1,R2,__,R4],\n/*SAD*/[__,R1,R2,R3,R4],\n/*SER*/[__,R1,R2,__,R4]\n];\n\n// map server current expect state and content type to function\nctTable[tls.ConnectionEnd.server] = [\n// CC,AL,HS,AD\n/*CHE*/[__,R1,R2,__,R4],\n/*CCE*/[__,R1,R2,__,R4],\n/*CKE*/[__,R1,R2,__,R4],\n/*CCV*/[__,R1,R2,__,R4],\n/*CCC*/[R0,R1,__,__,R4],\n/*CFI*/[__,R1,R2,__,R4],\n/*CAD*/[__,R1,R2,R3,R4],\n/*CER*/[__,R1,R2,__,R4]\n];\n\n// map client current expect state and handshake type to function\nvar H0 = tls.handleHelloRequest;\nvar H1 = tls.handleServerHello;\nvar H2 = tls.handleCertificate;\nvar H3 = tls.handleServerKeyExchange;\nvar H4 = tls.handleCertificateRequest;\nvar H5 = tls.handleServerHelloDone;\nvar H6 = tls.handleFinished;\nvar hsTable = [];\nhsTable[tls.ConnectionEnd.client] = [\n// HR,01,SH,03,04,05,06,07,08,09,10,SC,SK,CR,HD,15,CK,17,18,19,FI\n/*SHE*/[__,__,H1,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*SCE*/[H0,__,__,__,__,__,__,__,__,__,__,H2,H3,H4,H5,__,__,__,__,__,__],\n/*SKE*/[H0,__,__,__,__,__,__,__,__,__,__,__,H3,H4,H5,__,__,__,__,__,__],\n/*SCR*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,H4,H5,__,__,__,__,__,__],\n/*SHD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,H5,__,__,__,__,__,__],\n/*SCC*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*SFI*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],\n/*SAD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*SER*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]\n];\n\n// map server current expect state and handshake type to function\n// Note: CAD[CH] does not map to FB because renegotation is prohibited\nvar H7 = tls.handleClientHello;\nvar H8 = tls.handleClientKeyExchange;\nvar H9 = tls.handleCertificateVerify;\nhsTable[tls.ConnectionEnd.server] = [\n// 01,CH,02,03,04,05,06,07,08,09,10,CC,12,13,14,CV,CK,17,18,19,FI\n/*CHE*/[__,H7,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*CCE*/[__,__,__,__,__,__,__,__,__,__,__,H2,__,__,__,__,__,__,__,__,__],\n/*CKE*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H8,__,__,__,__],\n/*CCV*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H9,__,__,__,__,__],\n/*CCC*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*CFI*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],\n/*CAD*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*CER*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]\n];\n\n/**\n * Generates the master_secret and keys using the given security parameters.\n *\n * The security parameters for a TLS connection state are defined as such:\n *\n * struct {\n * ConnectionEnd entity;\n * PRFAlgorithm prf_algorithm;\n * BulkCipherAlgorithm bulk_cipher_algorithm;\n * CipherType cipher_type;\n * uint8 enc_key_length;\n * uint8 block_length;\n * uint8 fixed_iv_length;\n * uint8 record_iv_length;\n * MACAlgorithm mac_algorithm;\n * uint8 mac_length;\n * uint8 mac_key_length;\n * CompressionMethod compression_algorithm;\n * opaque master_secret[48];\n * opaque client_random[32];\n * opaque server_random[32];\n * } SecurityParameters;\n *\n * Note that this definition is from TLS 1.2. In TLS 1.0 some of these\n * parameters are ignored because, for instance, the PRFAlgorithm is a\n * builtin-fixed algorithm combining iterations of MD5 and SHA-1 in TLS 1.0.\n *\n * The Record Protocol requires an algorithm to generate keys required by the\n * current connection state.\n *\n * The master secret is expanded into a sequence of secure bytes, which is then\n * split to a client write MAC key, a server write MAC key, a client write\n * encryption key, and a server write encryption key. In TLS 1.0 a client write\n * IV and server write IV are also generated. Each of these is generated from\n * the byte sequence in that order. Unused values are empty. In TLS 1.2, some\n * AEAD ciphers may additionally require a client write IV and a server write\n * IV (see Section 6.2.3.3).\n *\n * When keys, MAC keys, and IVs are generated, the master secret is used as an\n * entropy source.\n *\n * To generate the key material, compute:\n *\n * master_secret = PRF(pre_master_secret, \"master secret\",\n * ClientHello.random + ServerHello.random)\n *\n * key_block = PRF(SecurityParameters.master_secret,\n * \"key expansion\",\n * SecurityParameters.server_random +\n * SecurityParameters.client_random);\n *\n * until enough output has been generated. Then, the key_block is\n * partitioned as follows:\n *\n * client_write_MAC_key[SecurityParameters.mac_key_length]\n * server_write_MAC_key[SecurityParameters.mac_key_length]\n * client_write_key[SecurityParameters.enc_key_length]\n * server_write_key[SecurityParameters.enc_key_length]\n * client_write_IV[SecurityParameters.fixed_iv_length]\n * server_write_IV[SecurityParameters.fixed_iv_length]\n *\n * In TLS 1.2, the client_write_IV and server_write_IV are only generated for\n * implicit nonce techniques as described in Section 3.2.1 of [AEAD]. This\n * implementation uses TLS 1.0 so IVs are generated.\n *\n * Implementation note: The currently defined cipher suite which requires the\n * most material is AES_256_CBC_SHA256. It requires 2 x 32 byte keys and 2 x 32\n * byte MAC keys, for a total 128 bytes of key material. In TLS 1.0 it also\n * requires 2 x 16 byte IVs, so it actually takes 160 bytes of key material.\n *\n * @param c the connection.\n * @param sp the security parameters to use.\n *\n * @return the security keys.\n */\ntls.generateKeys = function(c, sp) {\n // TLS_RSA_WITH_AES_128_CBC_SHA (required to be compliant with TLS 1.2) &\n // TLS_RSA_WITH_AES_256_CBC_SHA are the only cipher suites implemented\n // at present\n\n // TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA is required to be compliant with\n // TLS 1.0 but we don't care right now because AES is better and we have\n // an implementation for it\n\n // TODO: TLS 1.2 implementation\n /*\n // determine the PRF\n var prf;\n switch(sp.prf_algorithm) {\n case tls.PRFAlgorithm.tls_prf_sha256:\n prf = prf_sha256;\n break;\n default:\n // should never happen\n throw new Error('Invalid PRF');\n }\n */\n\n // TLS 1.0/1.1 implementation\n var prf = prf_TLS1;\n\n // concatenate server and client random\n var random = sp.client_random + sp.server_random;\n\n // only create master secret if session is new\n if(!c.session.resuming) {\n // create master secret, clean up pre-master secret\n sp.master_secret = prf(\n sp.pre_master_secret, 'master secret', random, 48).bytes();\n sp.pre_master_secret = null;\n }\n\n // generate the amount of key material needed\n random = sp.server_random + sp.client_random;\n var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length;\n\n // include IV for TLS/1.0\n var tls10 = (c.version.major === tls.Versions.TLS_1_0.major &&\n c.version.minor === tls.Versions.TLS_1_0.minor);\n if(tls10) {\n length += 2 * sp.fixed_iv_length;\n }\n var km = prf(sp.master_secret, 'key expansion', random, length);\n\n // split the key material into the MAC and encryption keys\n var rval = {\n client_write_MAC_key: km.getBytes(sp.mac_key_length),\n server_write_MAC_key: km.getBytes(sp.mac_key_length),\n client_write_key: km.getBytes(sp.enc_key_length),\n server_write_key: km.getBytes(sp.enc_key_length)\n };\n\n // include TLS 1.0 IVs\n if(tls10) {\n rval.client_write_IV = km.getBytes(sp.fixed_iv_length);\n rval.server_write_IV = km.getBytes(sp.fixed_iv_length);\n }\n\n return rval;\n};\n\n/**\n * Creates a new initialized TLS connection state. A connection state has\n * a read mode and a write mode.\n *\n * compression state:\n * The current state of the compression algorithm.\n *\n * cipher state:\n * The current state of the encryption algorithm. This will consist of the\n * scheduled key for that connection. For stream ciphers, this will also\n * contain whatever state information is necessary to allow the stream to\n * continue to encrypt or decrypt data.\n *\n * MAC key:\n * The MAC key for the connection.\n *\n * sequence number:\n * Each connection state contains a sequence number, which is maintained\n * separately for read and write states. The sequence number MUST be set to\n * zero whenever a connection state is made the active state. Sequence\n * numbers are of type uint64 and may not exceed 2^64-1. Sequence numbers do\n * not wrap. If a TLS implementation would need to wrap a sequence number,\n * it must renegotiate instead. A sequence number is incremented after each\n * record: specifically, the first record transmitted under a particular\n * connection state MUST use sequence number 0.\n *\n * @param c the connection.\n *\n * @return the new initialized TLS connection state.\n */\ntls.createConnectionState = function(c) {\n var client = (c.entity === tls.ConnectionEnd.client);\n\n var createMode = function() {\n var mode = {\n // two 32-bit numbers, first is most significant\n sequenceNumber: [0, 0],\n macKey: null,\n macLength: 0,\n macFunction: null,\n cipherState: null,\n cipherFunction: function(record) {return true;},\n compressionState: null,\n compressFunction: function(record) {return true;},\n updateSequenceNumber: function() {\n if(mode.sequenceNumber[1] === 0xFFFFFFFF) {\n mode.sequenceNumber[1] = 0;\n ++mode.sequenceNumber[0];\n } else {\n ++mode.sequenceNumber[1];\n }\n }\n };\n return mode;\n };\n var state = {\n read: createMode(),\n write: createMode()\n };\n\n // update function in read mode will decrypt then decompress a record\n state.read.update = function(c, record) {\n if(!state.read.cipherFunction(record, state.read)) {\n c.error(c, {\n message: 'Could not decrypt record or bad MAC.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n // doesn't matter if decryption failed or MAC was\n // invalid, return the same error so as not to reveal\n // which one occurred\n description: tls.Alert.Description.bad_record_mac\n }\n });\n } else if(!state.read.compressFunction(c, record, state.read)) {\n c.error(c, {\n message: 'Could not decompress record.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.decompression_failure\n }\n });\n }\n return !c.fail;\n };\n\n // update function in write mode will compress then encrypt a record\n state.write.update = function(c, record) {\n if(!state.write.compressFunction(c, record, state.write)) {\n // error, but do not send alert since it would require\n // compression as well\n c.error(c, {\n message: 'Could not compress record.',\n send: false,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n } else if(!state.write.cipherFunction(record, state.write)) {\n // error, but do not send alert since it would require\n // encryption as well\n c.error(c, {\n message: 'Could not encrypt record.',\n send: false,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n }\n return !c.fail;\n };\n\n // handle security parameters\n if(c.session) {\n var sp = c.session.sp;\n c.session.cipherSuite.initSecurityParameters(sp);\n\n // generate keys\n sp.keys = tls.generateKeys(c, sp);\n state.read.macKey = client ?\n sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key;\n state.write.macKey = client ?\n sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key;\n\n // cipher suite setup\n c.session.cipherSuite.initConnectionState(state, c, sp);\n\n // compression setup\n switch(sp.compression_algorithm) {\n case tls.CompressionMethod.none:\n break;\n case tls.CompressionMethod.deflate:\n state.read.compressFunction = inflate;\n state.write.compressFunction = deflate;\n break;\n default:\n throw new Error('Unsupported compression algorithm.');\n }\n }\n\n return state;\n};\n\n/**\n * Creates a Random structure.\n *\n * struct {\n * uint32 gmt_unix_time;\n * opaque random_bytes[28];\n * } Random;\n *\n * gmt_unix_time:\n * The current time and date in standard UNIX 32-bit format (seconds since\n * the midnight starting Jan 1, 1970, UTC, ignoring leap seconds) according\n * to the sender's internal clock. Clocks are not required to be set\n * correctly by the basic TLS protocol; higher-level or application\n * protocols may define additional requirements. Note that, for historical\n * reasons, the data element is named using GMT, the predecessor of the\n * current worldwide time base, UTC.\n * random_bytes:\n * 28 bytes generated by a secure random number generator.\n *\n * @return the Random structure as a byte array.\n */\ntls.createRandom = function() {\n // get UTC milliseconds\n var d = new Date();\n var utc = +d + d.getTimezoneOffset() * 60000;\n var rval = forge.util.createBuffer();\n rval.putInt32(utc);\n rval.putBytes(forge.random.getBytes(28));\n return rval;\n};\n\n/**\n * Creates a TLS record with the given type and data.\n *\n * @param c the connection.\n * @param options:\n * type: the record type.\n * data: the plain text data in a byte buffer.\n *\n * @return the created record.\n */\ntls.createRecord = function(c, options) {\n if(!options.data) {\n return null;\n }\n var record = {\n type: options.type,\n version: {\n major: c.version.major,\n minor: c.version.minor\n },\n length: options.data.length(),\n fragment: options.data\n };\n return record;\n};\n\n/**\n * Creates a TLS alert record.\n *\n * @param c the connection.\n * @param alert:\n * level: the TLS alert level.\n * description: the TLS alert description.\n *\n * @return the created alert record.\n */\ntls.createAlert = function(c, alert) {\n var b = forge.util.createBuffer();\n b.putByte(alert.level);\n b.putByte(alert.description);\n return tls.createRecord(c, {\n type: tls.ContentType.alert,\n data: b\n });\n};\n\n/* The structure of a TLS handshake message.\n *\n * struct {\n * HandshakeType msg_type; // handshake type\n * uint24 length; // bytes in message\n * select(HandshakeType) {\n * case hello_request: HelloRequest;\n * case client_hello: ClientHello;\n * case server_hello: ServerHello;\n * case certificate: Certificate;\n * case server_key_exchange: ServerKeyExchange;\n * case certificate_request: CertificateRequest;\n * case server_hello_done: ServerHelloDone;\n * case certificate_verify: CertificateVerify;\n * case client_key_exchange: ClientKeyExchange;\n * case finished: Finished;\n * } body;\n * } Handshake;\n */\n\n/**\n * Creates a ClientHello message.\n *\n * opaque SessionID<0..32>;\n * enum { null(0), deflate(1), (255) } CompressionMethod;\n * uint8 CipherSuite[2];\n *\n * struct {\n * ProtocolVersion client_version;\n * Random random;\n * SessionID session_id;\n * CipherSuite cipher_suites<2..2^16-2>;\n * CompressionMethod compression_methods<1..2^8-1>;\n * select(extensions_present) {\n * case false:\n * struct {};\n * case true:\n * Extension extensions<0..2^16-1>;\n * };\n * } ClientHello;\n *\n * The extension format for extended client hellos and server hellos is:\n *\n * struct {\n * ExtensionType extension_type;\n * opaque extension_data<0..2^16-1>;\n * } Extension;\n *\n * Here:\n *\n * - \"extension_type\" identifies the particular extension type.\n * - \"extension_data\" contains information specific to the particular\n * extension type.\n *\n * The extension types defined in this document are:\n *\n * enum {\n * server_name(0), max_fragment_length(1),\n * client_certificate_url(2), trusted_ca_keys(3),\n * truncated_hmac(4), status_request(5), (65535)\n * } ExtensionType;\n *\n * @param c the connection.\n *\n * @return the ClientHello byte buffer.\n */\ntls.createClientHello = function(c) {\n // save hello version\n c.session.clientHelloVersion = {\n major: c.version.major,\n minor: c.version.minor\n };\n\n // create supported cipher suites\n var cipherSuites = forge.util.createBuffer();\n for(var i = 0; i < c.cipherSuites.length; ++i) {\n var cs = c.cipherSuites[i];\n cipherSuites.putByte(cs.id[0]);\n cipherSuites.putByte(cs.id[1]);\n }\n var cSuites = cipherSuites.length();\n\n // create supported compression methods, null always supported, but\n // also support deflate if connection has inflate and deflate methods\n var compressionMethods = forge.util.createBuffer();\n compressionMethods.putByte(tls.CompressionMethod.none);\n // FIXME: deflate support disabled until issues with raw deflate data\n // without zlib headers are resolved\n /*\n if(c.inflate !== null && c.deflate !== null) {\n compressionMethods.putByte(tls.CompressionMethod.deflate);\n }\n */\n var cMethods = compressionMethods.length();\n\n // create TLS SNI (server name indication) extension if virtual host\n // has been specified, see RFC 3546\n var extensions = forge.util.createBuffer();\n if(c.virtualHost) {\n // create extension struct\n var ext = forge.util.createBuffer();\n ext.putByte(0x00); // type server_name (ExtensionType is 2 bytes)\n ext.putByte(0x00);\n\n /* In order to provide the server name, clients MAY include an\n * extension of type \"server_name\" in the (extended) client hello.\n * The \"extension_data\" field of this extension SHALL contain\n * \"ServerNameList\" where:\n *\n * struct {\n * NameType name_type;\n * select(name_type) {\n * case host_name: HostName;\n * } name;\n * } ServerName;\n *\n * enum {\n * host_name(0), (255)\n * } NameType;\n *\n * opaque HostName<1..2^16-1>;\n *\n * struct {\n * ServerName server_name_list<1..2^16-1>\n * } ServerNameList;\n */\n var serverName = forge.util.createBuffer();\n serverName.putByte(0x00); // type host_name\n writeVector(serverName, 2, forge.util.createBuffer(c.virtualHost));\n\n // ServerNameList is in extension_data\n var snList = forge.util.createBuffer();\n writeVector(snList, 2, serverName);\n writeVector(ext, 2, snList);\n extensions.putBuffer(ext);\n }\n var extLength = extensions.length();\n if(extLength > 0) {\n // add extension vector length\n extLength += 2;\n }\n\n // determine length of the handshake message\n // cipher suites and compression methods size will need to be\n // updated if more get added to the list\n var sessionId = c.session.id;\n var length =\n sessionId.length + 1 + // session ID vector\n 2 + // version (major + minor)\n 4 + 28 + // random time and random bytes\n 2 + cSuites + // cipher suites vector\n 1 + cMethods + // compression methods vector\n extLength; // extensions vector\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.client_hello);\n rval.putInt24(length); // handshake length\n rval.putByte(c.version.major); // major version\n rval.putByte(c.version.minor); // minor version\n rval.putBytes(c.session.sp.client_random); // random time + bytes\n writeVector(rval, 1, forge.util.createBuffer(sessionId));\n writeVector(rval, 2, cipherSuites);\n writeVector(rval, 1, compressionMethods);\n if(extLength > 0) {\n writeVector(rval, 2, extensions);\n }\n return rval;\n};\n\n/**\n * Creates a ServerHello message.\n *\n * @param c the connection.\n *\n * @return the ServerHello byte buffer.\n */\ntls.createServerHello = function(c) {\n // determine length of the handshake message\n var sessionId = c.session.id;\n var length =\n sessionId.length + 1 + // session ID vector\n 2 + // version (major + minor)\n 4 + 28 + // random time and random bytes\n 2 + // chosen cipher suite\n 1; // chosen compression method\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.server_hello);\n rval.putInt24(length); // handshake length\n rval.putByte(c.version.major); // major version\n rval.putByte(c.version.minor); // minor version\n rval.putBytes(c.session.sp.server_random); // random time + bytes\n writeVector(rval, 1, forge.util.createBuffer(sessionId));\n rval.putByte(c.session.cipherSuite.id[0]);\n rval.putByte(c.session.cipherSuite.id[1]);\n rval.putByte(c.session.compressionMethod);\n return rval;\n};\n\n/**\n * Creates a Certificate message.\n *\n * When this message will be sent:\n * This is the first message the client can send after receiving a server\n * hello done message and the first message the server can send after\n * sending a ServerHello. This client message is only sent if the server\n * requests a certificate. If no suitable certificate is available, the\n * client should send a certificate message containing no certificates. If\n * client authentication is required by the server for the handshake to\n * continue, it may respond with a fatal handshake failure alert.\n *\n * opaque ASN.1Cert<1..2^24-1>;\n *\n * struct {\n * ASN.1Cert certificate_list<0..2^24-1>;\n * } Certificate;\n *\n * @param c the connection.\n *\n * @return the Certificate byte buffer.\n */\ntls.createCertificate = function(c) {\n // TODO: check certificate request to ensure types are supported\n\n // get a certificate (a certificate as a PEM string)\n var client = (c.entity === tls.ConnectionEnd.client);\n var cert = null;\n if(c.getCertificate) {\n var hint;\n if(client) {\n hint = c.session.certificateRequest;\n } else {\n hint = c.session.extensions.server_name.serverNameList;\n }\n cert = c.getCertificate(c, hint);\n }\n\n // buffer to hold certificate list\n var certList = forge.util.createBuffer();\n if(cert !== null) {\n try {\n // normalize cert to a chain of certificates\n if(!forge.util.isArray(cert)) {\n cert = [cert];\n }\n var asn1 = null;\n for(var i = 0; i < cert.length; ++i) {\n var msg = forge.pem.decode(cert[i])[0];\n if(msg.type !== 'CERTIFICATE' &&\n msg.type !== 'X509 CERTIFICATE' &&\n msg.type !== 'TRUSTED CERTIFICATE') {\n var error = new Error('Could not convert certificate from PEM; PEM ' +\n 'header type is not \"CERTIFICATE\", \"X509 CERTIFICATE\", or ' +\n '\"TRUSTED CERTIFICATE\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert certificate from PEM; PEM is encrypted.');\n }\n\n var der = forge.util.createBuffer(msg.body);\n if(asn1 === null) {\n asn1 = forge.asn1.fromDer(der.bytes(), false);\n }\n\n // certificate entry is itself a vector with 3 length bytes\n var certBuffer = forge.util.createBuffer();\n writeVector(certBuffer, 3, der);\n\n // add cert vector to cert list vector\n certList.putBuffer(certBuffer);\n }\n\n // save certificate\n cert = forge.pki.certificateFromAsn1(asn1);\n if(client) {\n c.session.clientCertificate = cert;\n } else {\n c.session.serverCertificate = cert;\n }\n } catch(ex) {\n return c.error(c, {\n message: 'Could not send certificate list.',\n cause: ex,\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.bad_certificate\n }\n });\n }\n }\n\n // determine length of the handshake message\n var length = 3 + certList.length(); // cert list vector\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.certificate);\n rval.putInt24(length);\n writeVector(rval, 3, certList);\n return rval;\n};\n\n/**\n * Creates a ClientKeyExchange message.\n *\n * When this message will be sent:\n * This message is always sent by the client. It will immediately follow the\n * client certificate message, if it is sent. Otherwise it will be the first\n * message sent by the client after it receives the server hello done\n * message.\n *\n * Meaning of this message:\n * With this message, the premaster secret is set, either though direct\n * transmission of the RSA-encrypted secret, or by the transmission of\n * Diffie-Hellman parameters which will allow each side to agree upon the\n * same premaster secret. When the key exchange method is DH_RSA or DH_DSS,\n * client certification has been requested, and the client was able to\n * respond with a certificate which contained a Diffie-Hellman public key\n * whose parameters (group and generator) matched those specified by the\n * server in its certificate, this message will not contain any data.\n *\n * Meaning of this message:\n * If RSA is being used for key agreement and authentication, the client\n * generates a 48-byte premaster secret, encrypts it using the public key\n * from the server's certificate or the temporary RSA key provided in a\n * server key exchange message, and sends the result in an encrypted\n * premaster secret message. This structure is a variant of the client\n * key exchange message, not a message in itself.\n *\n * struct {\n * select(KeyExchangeAlgorithm) {\n * case rsa: EncryptedPreMasterSecret;\n * case diffie_hellman: ClientDiffieHellmanPublic;\n * } exchange_keys;\n * } ClientKeyExchange;\n *\n * struct {\n * ProtocolVersion client_version;\n * opaque random[46];\n * } PreMasterSecret;\n *\n * struct {\n * public-key-encrypted PreMasterSecret pre_master_secret;\n * } EncryptedPreMasterSecret;\n *\n * A public-key-encrypted element is encoded as a vector <0..2^16-1>.\n *\n * @param c the connection.\n *\n * @return the ClientKeyExchange byte buffer.\n */\ntls.createClientKeyExchange = function(c) {\n // create buffer to encrypt\n var b = forge.util.createBuffer();\n\n // add highest client-supported protocol to help server avoid version\n // rollback attacks\n b.putByte(c.session.clientHelloVersion.major);\n b.putByte(c.session.clientHelloVersion.minor);\n\n // generate and add 46 random bytes\n b.putBytes(forge.random.getBytes(46));\n\n // save pre-master secret\n var sp = c.session.sp;\n sp.pre_master_secret = b.getBytes();\n\n // RSA-encrypt the pre-master secret\n var key = c.session.serverCertificate.publicKey;\n b = key.encrypt(sp.pre_master_secret);\n\n /* Note: The encrypted pre-master secret will be stored in a\n public-key-encrypted opaque vector that has the length prefixed using\n 2 bytes, so include those 2 bytes in the handshake message length. This\n is done as a minor optimization instead of calling writeVector(). */\n\n // determine length of the handshake message\n var length = b.length + 2;\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.client_key_exchange);\n rval.putInt24(length);\n // add vector length bytes\n rval.putInt16(b.length);\n rval.putBytes(b);\n return rval;\n};\n\n/**\n * Creates a ServerKeyExchange message.\n *\n * @param c the connection.\n *\n * @return the ServerKeyExchange byte buffer.\n */\ntls.createServerKeyExchange = function(c) {\n // this implementation only supports RSA, no Diffie-Hellman support,\n // so this record is empty\n\n // determine length of the handshake message\n var length = 0;\n\n // build record fragment\n var rval = forge.util.createBuffer();\n if(length > 0) {\n rval.putByte(tls.HandshakeType.server_key_exchange);\n rval.putInt24(length);\n }\n return rval;\n};\n\n/**\n * Gets the signed data used to verify a client-side certificate. See\n * tls.createCertificateVerify() for details.\n *\n * @param c the connection.\n * @param callback the callback to call once the signed data is ready.\n */\ntls.getClientSignature = function(c, callback) {\n // generate data to RSA encrypt\n var b = forge.util.createBuffer();\n b.putBuffer(c.session.md5.digest());\n b.putBuffer(c.session.sha1.digest());\n b = b.getBytes();\n\n // create default signing function as necessary\n c.getSignature = c.getSignature || function(c, b, callback) {\n // do rsa encryption, call callback\n var privateKey = null;\n if(c.getPrivateKey) {\n try {\n privateKey = c.getPrivateKey(c, c.session.clientCertificate);\n privateKey = forge.pki.privateKeyFromPem(privateKey);\n } catch(ex) {\n c.error(c, {\n message: 'Could not get private key.',\n cause: ex,\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n }\n }\n if(privateKey === null) {\n c.error(c, {\n message: 'No private key set.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n } else {\n b = privateKey.sign(b, null);\n }\n callback(c, b);\n };\n\n // get client signature\n c.getSignature(c, b, callback);\n};\n\n/**\n * Creates a CertificateVerify message.\n *\n * Meaning of this message:\n * This structure conveys the client's Diffie-Hellman public value\n * (Yc) if it was not already included in the client's certificate.\n * The encoding used for Yc is determined by the enumerated\n * PublicValueEncoding. This structure is a variant of the client\n * key exchange message, not a message in itself.\n *\n * When this message will be sent:\n * This message is used to provide explicit verification of a client\n * certificate. This message is only sent following a client\n * certificate that has signing capability (i.e. all certificates\n * except those containing fixed Diffie-Hellman parameters). When\n * sent, it will immediately follow the client key exchange message.\n *\n * struct {\n * Signature signature;\n * } CertificateVerify;\n *\n * CertificateVerify.signature.md5_hash\n * MD5(handshake_messages);\n *\n * Certificate.signature.sha_hash\n * SHA(handshake_messages);\n *\n * Here handshake_messages refers to all handshake messages sent or\n * received starting at client hello up to but not including this\n * message, including the type and length fields of the handshake\n * messages.\n *\n * select(SignatureAlgorithm) {\n * case anonymous: struct { };\n * case rsa:\n * digitally-signed struct {\n * opaque md5_hash[16];\n * opaque sha_hash[20];\n * };\n * case dsa:\n * digitally-signed struct {\n * opaque sha_hash[20];\n * };\n * } Signature;\n *\n * In digital signing, one-way hash functions are used as input for a\n * signing algorithm. A digitally-signed element is encoded as an opaque\n * vector <0..2^16-1>, where the length is specified by the signing\n * algorithm and key.\n *\n * In RSA signing, a 36-byte structure of two hashes (one SHA and one\n * MD5) is signed (encrypted with the private key). It is encoded with\n * PKCS #1 block type 0 or type 1 as described in [PKCS1].\n *\n * In DSS, the 20 bytes of the SHA hash are run directly through the\n * Digital Signing Algorithm with no additional hashing.\n *\n * @param c the connection.\n * @param signature the signature to include in the message.\n *\n * @return the CertificateVerify byte buffer.\n */\ntls.createCertificateVerify = function(c, signature) {\n /* Note: The signature will be stored in a \"digitally-signed\" opaque\n vector that has the length prefixed using 2 bytes, so include those\n 2 bytes in the handshake message length. This is done as a minor\n optimization instead of calling writeVector(). */\n\n // determine length of the handshake message\n var length = signature.length + 2;\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.certificate_verify);\n rval.putInt24(length);\n // add vector length bytes\n rval.putInt16(signature.length);\n rval.putBytes(signature);\n return rval;\n};\n\n/**\n * Creates a CertificateRequest message.\n *\n * @param c the connection.\n *\n * @return the CertificateRequest byte buffer.\n */\ntls.createCertificateRequest = function(c) {\n // TODO: support other certificate types\n var certTypes = forge.util.createBuffer();\n\n // common RSA certificate type\n certTypes.putByte(0x01);\n\n // add distinguished names from CA store\n var cAs = forge.util.createBuffer();\n for(var key in c.caStore.certs) {\n var cert = c.caStore.certs[key];\n var dn = forge.pki.distinguishedNameToAsn1(cert.subject);\n var byteBuffer = forge.asn1.toDer(dn);\n cAs.putInt16(byteBuffer.length());\n cAs.putBuffer(byteBuffer);\n }\n\n // TODO: TLS 1.2+ has a different format\n\n // determine length of the handshake message\n var length =\n 1 + certTypes.length() +\n 2 + cAs.length();\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.certificate_request);\n rval.putInt24(length);\n writeVector(rval, 1, certTypes);\n writeVector(rval, 2, cAs);\n return rval;\n};\n\n/**\n * Creates a ServerHelloDone message.\n *\n * @param c the connection.\n *\n * @return the ServerHelloDone byte buffer.\n */\ntls.createServerHelloDone = function(c) {\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.server_hello_done);\n rval.putInt24(0);\n return rval;\n};\n\n/**\n * Creates a ChangeCipherSpec message.\n *\n * The change cipher spec protocol exists to signal transitions in\n * ciphering strategies. The protocol consists of a single message,\n * which is encrypted and compressed under the current (not the pending)\n * connection state. The message consists of a single byte of value 1.\n *\n * struct {\n * enum { change_cipher_spec(1), (255) } type;\n * } ChangeCipherSpec;\n *\n * @return the ChangeCipherSpec byte buffer.\n */\ntls.createChangeCipherSpec = function() {\n var rval = forge.util.createBuffer();\n rval.putByte(0x01);\n return rval;\n};\n\n/**\n * Creates a Finished message.\n *\n * struct {\n * opaque verify_data[12];\n * } Finished;\n *\n * verify_data\n * PRF(master_secret, finished_label, MD5(handshake_messages) +\n * SHA-1(handshake_messages)) [0..11];\n *\n * finished_label\n * For Finished messages sent by the client, the string \"client\n * finished\". For Finished messages sent by the server, the\n * string \"server finished\".\n *\n * handshake_messages\n * All of the data from all handshake messages up to but not\n * including this message. This is only data visible at the\n * handshake layer and does not include record layer headers.\n * This is the concatenation of all the Handshake structures as\n * defined in 7.4 exchanged thus far.\n *\n * @param c the connection.\n *\n * @return the Finished byte buffer.\n */\ntls.createFinished = function(c) {\n // generate verify_data\n var b = forge.util.createBuffer();\n b.putBuffer(c.session.md5.digest());\n b.putBuffer(c.session.sha1.digest());\n\n // TODO: determine prf function and verify length for TLS 1.2\n var client = (c.entity === tls.ConnectionEnd.client);\n var sp = c.session.sp;\n var vdl = 12;\n var prf = prf_TLS1;\n var label = client ? 'client finished' : 'server finished';\n b = prf(sp.master_secret, label, b.getBytes(), vdl);\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.finished);\n rval.putInt24(b.length());\n rval.putBuffer(b);\n return rval;\n};\n\n/**\n * Creates a HeartbeatMessage (See RFC 6520).\n *\n * struct {\n * HeartbeatMessageType type;\n * uint16 payload_length;\n * opaque payload[HeartbeatMessage.payload_length];\n * opaque padding[padding_length];\n * } HeartbeatMessage;\n *\n * The total length of a HeartbeatMessage MUST NOT exceed 2^14 or\n * max_fragment_length when negotiated as defined in [RFC6066].\n *\n * type: The message type, either heartbeat_request or heartbeat_response.\n *\n * payload_length: The length of the payload.\n *\n * payload: The payload consists of arbitrary content.\n *\n * padding: The padding is random content that MUST be ignored by the\n * receiver. The length of a HeartbeatMessage is TLSPlaintext.length\n * for TLS and DTLSPlaintext.length for DTLS. Furthermore, the\n * length of the type field is 1 byte, and the length of the\n * payload_length is 2. Therefore, the padding_length is\n * TLSPlaintext.length - payload_length - 3 for TLS and\n * DTLSPlaintext.length - payload_length - 3 for DTLS. The\n * padding_length MUST be at least 16.\n *\n * The sender of a HeartbeatMessage MUST use a random padding of at\n * least 16 bytes. The padding of a received HeartbeatMessage message\n * MUST be ignored.\n *\n * If the payload_length of a received HeartbeatMessage is too large,\n * the received HeartbeatMessage MUST be discarded silently.\n *\n * @param c the connection.\n * @param type the tls.HeartbeatMessageType.\n * @param payload the heartbeat data to send as the payload.\n * @param [payloadLength] the payload length to use, defaults to the\n * actual payload length.\n *\n * @return the HeartbeatRequest byte buffer.\n */\ntls.createHeartbeat = function(type, payload, payloadLength) {\n if(typeof payloadLength === 'undefined') {\n payloadLength = payload.length;\n }\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(type); // heartbeat message type\n rval.putInt16(payloadLength); // payload length\n rval.putBytes(payload); // payload\n // padding\n var plaintextLength = rval.length();\n var paddingLength = Math.max(16, plaintextLength - payloadLength - 3);\n rval.putBytes(forge.random.getBytes(paddingLength));\n return rval;\n};\n\n/**\n * Fragments, compresses, encrypts, and queues a record for delivery.\n *\n * @param c the connection.\n * @param record the record to queue.\n */\ntls.queue = function(c, record) {\n // error during record creation\n if(!record) {\n return;\n }\n\n if(record.fragment.length() === 0) {\n if(record.type === tls.ContentType.handshake ||\n record.type === tls.ContentType.alert ||\n record.type === tls.ContentType.change_cipher_spec) {\n // Empty handshake, alert of change cipher spec messages are not allowed per the TLS specification and should not be sent.\n return;\n }\n }\n\n // if the record is a handshake record, update handshake hashes\n if(record.type === tls.ContentType.handshake) {\n var bytes = record.fragment.bytes();\n c.session.md5.update(bytes);\n c.session.sha1.update(bytes);\n bytes = null;\n }\n\n // handle record fragmentation\n var records;\n if(record.fragment.length() <= tls.MaxFragment) {\n records = [record];\n } else {\n // fragment data as long as it is too long\n records = [];\n var data = record.fragment.bytes();\n while(data.length > tls.MaxFragment) {\n records.push(tls.createRecord(c, {\n type: record.type,\n data: forge.util.createBuffer(data.slice(0, tls.MaxFragment))\n }));\n data = data.slice(tls.MaxFragment);\n }\n // add last record\n if(data.length > 0) {\n records.push(tls.createRecord(c, {\n type: record.type,\n data: forge.util.createBuffer(data)\n }));\n }\n }\n\n // compress and encrypt all fragmented records\n for(var i = 0; i < records.length && !c.fail; ++i) {\n // update the record using current write state\n var rec = records[i];\n var s = c.state.current.write;\n if(s.update(c, rec)) {\n // store record\n c.records.push(rec);\n }\n }\n};\n\n/**\n * Flushes all queued records to the output buffer and calls the\n * tlsDataReady() handler on the given connection.\n *\n * @param c the connection.\n *\n * @return true on success, false on failure.\n */\ntls.flush = function(c) {\n for(var i = 0; i < c.records.length; ++i) {\n var record = c.records[i];\n\n // add record header and fragment\n c.tlsData.putByte(record.type);\n c.tlsData.putByte(record.version.major);\n c.tlsData.putByte(record.version.minor);\n c.tlsData.putInt16(record.fragment.length());\n c.tlsData.putBuffer(c.records[i].fragment);\n }\n c.records = [];\n return c.tlsDataReady(c);\n};\n\n/**\n * Maps a pki.certificateError to a tls.Alert.Description.\n *\n * @param error the error to map.\n *\n * @return the alert description.\n */\nvar _certErrorToAlertDesc = function(error) {\n switch(error) {\n case true:\n return true;\n case forge.pki.certificateError.bad_certificate:\n return tls.Alert.Description.bad_certificate;\n case forge.pki.certificateError.unsupported_certificate:\n return tls.Alert.Description.unsupported_certificate;\n case forge.pki.certificateError.certificate_revoked:\n return tls.Alert.Description.certificate_revoked;\n case forge.pki.certificateError.certificate_expired:\n return tls.Alert.Description.certificate_expired;\n case forge.pki.certificateError.certificate_unknown:\n return tls.Alert.Description.certificate_unknown;\n case forge.pki.certificateError.unknown_ca:\n return tls.Alert.Description.unknown_ca;\n default:\n return tls.Alert.Description.bad_certificate;\n }\n};\n\n/**\n * Maps a tls.Alert.Description to a pki.certificateError.\n *\n * @param desc the alert description.\n *\n * @return the certificate error.\n */\nvar _alertDescToCertError = function(desc) {\n switch(desc) {\n case true:\n return true;\n case tls.Alert.Description.bad_certificate:\n return forge.pki.certificateError.bad_certificate;\n case tls.Alert.Description.unsupported_certificate:\n return forge.pki.certificateError.unsupported_certificate;\n case tls.Alert.Description.certificate_revoked:\n return forge.pki.certificateError.certificate_revoked;\n case tls.Alert.Description.certificate_expired:\n return forge.pki.certificateError.certificate_expired;\n case tls.Alert.Description.certificate_unknown:\n return forge.pki.certificateError.certificate_unknown;\n case tls.Alert.Description.unknown_ca:\n return forge.pki.certificateError.unknown_ca;\n default:\n return forge.pki.certificateError.bad_certificate;\n }\n};\n\n/**\n * Verifies a certificate chain against the given connection's\n * Certificate Authority store.\n *\n * @param c the TLS connection.\n * @param chain the certificate chain to verify, with the root or highest\n * authority at the end.\n *\n * @return true if successful, false if not.\n */\ntls.verifyCertificateChain = function(c, chain) {\n try {\n // Make a copy of c.verifyOptions so that we can modify options.verify\n // without modifying c.verifyOptions.\n var options = {};\n for (var key in c.verifyOptions) {\n options[key] = c.verifyOptions[key];\n }\n\n options.verify = function(vfd, depth, chain) {\n // convert pki.certificateError to tls alert description\n var desc = _certErrorToAlertDesc(vfd);\n\n // call application callback\n var ret = c.verify(c, vfd, depth, chain);\n if(ret !== true) {\n if(typeof ret === 'object' && !forge.util.isArray(ret)) {\n // throw custom error\n var error = new Error('The application rejected the certificate.');\n error.send = true;\n error.alert = {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.bad_certificate\n };\n if(ret.message) {\n error.message = ret.message;\n }\n if(ret.alert) {\n error.alert.description = ret.alert;\n }\n throw error;\n }\n\n // convert tls alert description to pki.certificateError\n if(ret !== vfd) {\n ret = _alertDescToCertError(ret);\n }\n }\n\n return ret;\n };\n\n // verify chain\n forge.pki.verifyCertificateChain(c.caStore, chain, options);\n } catch(ex) {\n // build tls error if not already customized\n var err = ex;\n if(typeof err !== 'object' || forge.util.isArray(err)) {\n err = {\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: _certErrorToAlertDesc(ex)\n }\n };\n }\n if(!('send' in err)) {\n err.send = true;\n }\n if(!('alert' in err)) {\n err.alert = {\n level: tls.Alert.Level.fatal,\n description: _certErrorToAlertDesc(err.error)\n };\n }\n\n // send error\n c.error(c, err);\n }\n\n return !c.fail;\n};\n\n/**\n * Creates a new TLS session cache.\n *\n * @param cache optional map of session ID to cached session.\n * @param capacity the maximum size for the cache (default: 100).\n *\n * @return the new TLS session cache.\n */\ntls.createSessionCache = function(cache, capacity) {\n var rval = null;\n\n // assume input is already a session cache object\n if(cache && cache.getSession && cache.setSession && cache.order) {\n rval = cache;\n } else {\n // create cache\n rval = {};\n rval.cache = cache || {};\n rval.capacity = Math.max(capacity || 100, 1);\n rval.order = [];\n\n // store order for sessions, delete session overflow\n for(var key in cache) {\n if(rval.order.length <= capacity) {\n rval.order.push(key);\n } else {\n delete cache[key];\n }\n }\n\n // get a session from a session ID (or get any session)\n rval.getSession = function(sessionId) {\n var session = null;\n var key = null;\n\n // if session ID provided, use it\n if(sessionId) {\n key = forge.util.bytesToHex(sessionId);\n } else if(rval.order.length > 0) {\n // get first session from cache\n key = rval.order[0];\n }\n\n if(key !== null && key in rval.cache) {\n // get cached session and remove from cache\n session = rval.cache[key];\n delete rval.cache[key];\n for(var i in rval.order) {\n if(rval.order[i] === key) {\n rval.order.splice(i, 1);\n break;\n }\n }\n }\n\n return session;\n };\n\n // set a session in the cache\n rval.setSession = function(sessionId, session) {\n // remove session from cache if at capacity\n if(rval.order.length === rval.capacity) {\n var key = rval.order.shift();\n delete rval.cache[key];\n }\n // add session to cache\n var key = forge.util.bytesToHex(sessionId);\n rval.order.push(key);\n rval.cache[key] = session;\n };\n }\n\n return rval;\n};\n\n/**\n * Creates a new TLS connection.\n *\n * See public createConnection() docs for more details.\n *\n * @param options the options for this connection.\n *\n * @return the new TLS connection.\n */\ntls.createConnection = function(options) {\n var caStore = null;\n if(options.caStore) {\n // if CA store is an array, convert it to a CA store object\n if(forge.util.isArray(options.caStore)) {\n caStore = forge.pki.createCaStore(options.caStore);\n } else {\n caStore = options.caStore;\n }\n } else {\n // create empty CA store\n caStore = forge.pki.createCaStore();\n }\n\n // setup default cipher suites\n var cipherSuites = options.cipherSuites || null;\n if(cipherSuites === null) {\n cipherSuites = [];\n for(var key in tls.CipherSuites) {\n cipherSuites.push(tls.CipherSuites[key]);\n }\n }\n\n // set default entity\n var entity = (options.server || false) ?\n tls.ConnectionEnd.server : tls.ConnectionEnd.client;\n\n // create session cache if requested\n var sessionCache = options.sessionCache ?\n tls.createSessionCache(options.sessionCache) : null;\n\n // create TLS connection\n var c = {\n version: {major: tls.Version.major, minor: tls.Version.minor},\n entity: entity,\n sessionId: options.sessionId,\n caStore: caStore,\n sessionCache: sessionCache,\n cipherSuites: cipherSuites,\n connected: options.connected,\n virtualHost: options.virtualHost || null,\n verifyClient: options.verifyClient || false,\n verify: options.verify || function(cn, vfd, dpth, cts) {return vfd;},\n verifyOptions: options.verifyOptions || {},\n getCertificate: options.getCertificate || null,\n getPrivateKey: options.getPrivateKey || null,\n getSignature: options.getSignature || null,\n input: forge.util.createBuffer(),\n tlsData: forge.util.createBuffer(),\n data: forge.util.createBuffer(),\n tlsDataReady: options.tlsDataReady,\n dataReady: options.dataReady,\n heartbeatReceived: options.heartbeatReceived,\n closed: options.closed,\n error: function(c, ex) {\n // set origin if not set\n ex.origin = ex.origin ||\n ((c.entity === tls.ConnectionEnd.client) ? 'client' : 'server');\n\n // send TLS alert\n if(ex.send) {\n tls.queue(c, tls.createAlert(c, ex.alert));\n tls.flush(c);\n }\n\n // error is fatal by default\n var fatal = (ex.fatal !== false);\n if(fatal) {\n // set fail flag\n c.fail = true;\n }\n\n // call error handler first\n options.error(c, ex);\n\n if(fatal) {\n // fatal error, close connection, do not clear fail\n c.close(false);\n }\n },\n deflate: options.deflate || null,\n inflate: options.inflate || null\n };\n\n /**\n * Resets a closed TLS connection for reuse. Called in c.close().\n *\n * @param clearFail true to clear the fail flag (default: true).\n */\n c.reset = function(clearFail) {\n c.version = {major: tls.Version.major, minor: tls.Version.minor};\n c.record = null;\n c.session = null;\n c.peerCertificate = null;\n c.state = {\n pending: null,\n current: null\n };\n c.expect = (c.entity === tls.ConnectionEnd.client) ? SHE : CHE;\n c.fragmented = null;\n c.records = [];\n c.open = false;\n c.handshakes = 0;\n c.handshaking = false;\n c.isConnected = false;\n c.fail = !(clearFail || typeof(clearFail) === 'undefined');\n c.input.clear();\n c.tlsData.clear();\n c.data.clear();\n c.state.current = tls.createConnectionState(c);\n };\n\n // do initial reset of connection\n c.reset();\n\n /**\n * Updates the current TLS engine state based on the given record.\n *\n * @param c the TLS connection.\n * @param record the TLS record to act on.\n */\n var _update = function(c, record) {\n // get record handler (align type in table by subtracting lowest)\n var aligned = record.type - tls.ContentType.change_cipher_spec;\n var handlers = ctTable[c.entity][c.expect];\n if(aligned in handlers) {\n handlers[aligned](c, record);\n } else {\n // unexpected record\n tls.handleUnexpected(c, record);\n }\n };\n\n /**\n * Reads the record header and initializes the next record on the given\n * connection.\n *\n * @param c the TLS connection with the next record.\n *\n * @return 0 if the input data could be processed, otherwise the\n * number of bytes required for data to be processed.\n */\n var _readRecordHeader = function(c) {\n var rval = 0;\n\n // get input buffer and its length\n var b = c.input;\n var len = b.length();\n\n // need at least 5 bytes to initialize a record\n if(len < 5) {\n rval = 5 - len;\n } else {\n // enough bytes for header\n // initialize record\n c.record = {\n type: b.getByte(),\n version: {\n major: b.getByte(),\n minor: b.getByte()\n },\n length: b.getInt16(),\n fragment: forge.util.createBuffer(),\n ready: false\n };\n\n // check record version\n var compatibleVersion = (c.record.version.major === c.version.major);\n if(compatibleVersion && c.session && c.session.version) {\n // session version already set, require same minor version\n compatibleVersion = (c.record.version.minor === c.version.minor);\n }\n if(!compatibleVersion) {\n c.error(c, {\n message: 'Incompatible TLS version.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.protocol_version\n }\n });\n }\n }\n\n return rval;\n };\n\n /**\n * Reads the next record's contents and appends its message to any\n * previously fragmented message.\n *\n * @param c the TLS connection with the next record.\n *\n * @return 0 if the input data could be processed, otherwise the\n * number of bytes required for data to be processed.\n */\n var _readRecord = function(c) {\n var rval = 0;\n\n // ensure there is enough input data to get the entire record\n var b = c.input;\n var len = b.length();\n if(len < c.record.length) {\n // not enough data yet, return how much is required\n rval = c.record.length - len;\n } else {\n // there is enough data to parse the pending record\n // fill record fragment and compact input buffer\n c.record.fragment.putBytes(b.getBytes(c.record.length));\n b.compact();\n\n // update record using current read state\n var s = c.state.current.read;\n if(s.update(c, c.record)) {\n // see if there is a previously fragmented message that the\n // new record's message fragment should be appended to\n if(c.fragmented !== null) {\n // if the record type matches a previously fragmented\n // record, append the record fragment to it\n if(c.fragmented.type === c.record.type) {\n // concatenate record fragments\n c.fragmented.fragment.putBuffer(c.record.fragment);\n c.record = c.fragmented;\n } else {\n // error, invalid fragmented record\n c.error(c, {\n message: 'Invalid fragmented record.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description:\n tls.Alert.Description.unexpected_message\n }\n });\n }\n }\n\n // record is now ready\n c.record.ready = true;\n }\n }\n\n return rval;\n };\n\n /**\n * Performs a handshake using the TLS Handshake Protocol, as a client.\n *\n * This method should only be called if the connection is in client mode.\n *\n * @param sessionId the session ID to use, null to start a new one.\n */\n c.handshake = function(sessionId) {\n // error to call this in non-client mode\n if(c.entity !== tls.ConnectionEnd.client) {\n // not fatal error\n c.error(c, {\n message: 'Cannot initiate handshake as a server.',\n fatal: false\n });\n } else if(c.handshaking) {\n // handshake is already in progress, fail but not fatal error\n c.error(c, {\n message: 'Handshake already in progress.',\n fatal: false\n });\n } else {\n // clear fail flag on reuse\n if(c.fail && !c.open && c.handshakes === 0) {\n c.fail = false;\n }\n\n // now handshaking\n c.handshaking = true;\n\n // default to blank (new session)\n sessionId = sessionId || '';\n\n // if a session ID was specified, try to find it in the cache\n var session = null;\n if(sessionId.length > 0) {\n if(c.sessionCache) {\n session = c.sessionCache.getSession(sessionId);\n }\n\n // matching session not found in cache, clear session ID\n if(session === null) {\n sessionId = '';\n }\n }\n\n // no session given, grab a session from the cache, if available\n if(sessionId.length === 0 && c.sessionCache) {\n session = c.sessionCache.getSession();\n if(session !== null) {\n sessionId = session.id;\n }\n }\n\n // set up session\n c.session = {\n id: sessionId,\n version: null,\n cipherSuite: null,\n compressionMethod: null,\n serverCertificate: null,\n certificateRequest: null,\n clientCertificate: null,\n sp: {},\n md5: forge.md.md5.create(),\n sha1: forge.md.sha1.create()\n };\n\n // use existing session information\n if(session) {\n // only update version on connection, session version not yet set\n c.version = session.version;\n c.session.sp = session.sp;\n }\n\n // generate new client random\n c.session.sp.client_random = tls.createRandom().getBytes();\n\n // connection now open\n c.open = true;\n\n // send hello\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createClientHello(c)\n }));\n tls.flush(c);\n }\n };\n\n /**\n * Called when TLS protocol data has been received from somewhere and should\n * be processed by the TLS engine.\n *\n * @param data the TLS protocol data, as a string, to process.\n *\n * @return 0 if the data could be processed, otherwise the number of bytes\n * required for data to be processed.\n */\n c.process = function(data) {\n var rval = 0;\n\n // buffer input data\n if(data) {\n c.input.putBytes(data);\n }\n\n // process next record if no failure, process will be called after\n // each record is handled (since handling can be asynchronous)\n if(!c.fail) {\n // reset record if ready and now empty\n if(c.record !== null &&\n c.record.ready && c.record.fragment.isEmpty()) {\n c.record = null;\n }\n\n // if there is no pending record, try to read record header\n if(c.record === null) {\n rval = _readRecordHeader(c);\n }\n\n // read the next record (if record not yet ready)\n if(!c.fail && c.record !== null && !c.record.ready) {\n rval = _readRecord(c);\n }\n\n // record ready to be handled, update engine state\n if(!c.fail && c.record !== null && c.record.ready) {\n _update(c, c.record);\n }\n }\n\n return rval;\n };\n\n /**\n * Requests that application data be packaged into a TLS record. The\n * tlsDataReady handler will be called when the TLS record(s) have been\n * prepared.\n *\n * @param data the application data, as a raw 'binary' encoded string, to\n * be sent; to send utf-16/utf-8 string data, use the return value\n * of util.encodeUtf8(str).\n *\n * @return true on success, false on failure.\n */\n c.prepare = function(data) {\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.application_data,\n data: forge.util.createBuffer(data)\n }));\n return tls.flush(c);\n };\n\n /**\n * Requests that a heartbeat request be packaged into a TLS record for\n * transmission. The tlsDataReady handler will be called when TLS record(s)\n * have been prepared.\n *\n * When a heartbeat response has been received, the heartbeatReceived\n * handler will be called with the matching payload. This handler can\n * be used to clear a retransmission timer, etc.\n *\n * @param payload the heartbeat data to send as the payload in the message.\n * @param [payloadLength] the payload length to use, defaults to the\n * actual payload length.\n *\n * @return true on success, false on failure.\n */\n c.prepareHeartbeatRequest = function(payload, payloadLength) {\n if(payload instanceof forge.util.ByteBuffer) {\n payload = payload.bytes();\n }\n if(typeof payloadLength === 'undefined') {\n payloadLength = payload.length;\n }\n c.expectedHeartbeatPayload = payload;\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.heartbeat,\n data: tls.createHeartbeat(\n tls.HeartbeatMessageType.heartbeat_request, payload, payloadLength)\n }));\n return tls.flush(c);\n };\n\n /**\n * Closes the connection (sends a close_notify alert).\n *\n * @param clearFail true to clear the fail flag (default: true).\n */\n c.close = function(clearFail) {\n // save session if connection didn't fail\n if(!c.fail && c.sessionCache && c.session) {\n // only need to preserve session ID, version, and security params\n var session = {\n id: c.session.id,\n version: c.session.version,\n sp: c.session.sp\n };\n session.sp.keys = null;\n c.sessionCache.setSession(session.id, session);\n }\n\n if(c.open) {\n // connection no longer open, clear input\n c.open = false;\n c.input.clear();\n\n // if connected or handshaking, send an alert\n if(c.isConnected || c.handshaking) {\n c.isConnected = c.handshaking = false;\n\n // send close_notify alert\n tls.queue(c, tls.createAlert(c, {\n level: tls.Alert.Level.warning,\n description: tls.Alert.Description.close_notify\n }));\n tls.flush(c);\n }\n\n // call handler\n c.closed(c);\n }\n\n // reset TLS connection, do not clear fail flag\n c.reset(clearFail);\n };\n\n return c;\n};\n\n/* TLS API */\nmodule.exports = forge.tls = forge.tls || {};\n\n// expose non-functions\nfor(var key in tls) {\n if(typeof tls[key] !== 'function') {\n forge.tls[key] = tls[key];\n }\n}\n\n// expose prf_tls1 for testing\nforge.tls.prf_tls1 = prf_TLS1;\n\n// expose sha1 hmac method\nforge.tls.hmac_sha1 = hmac_sha1;\n\n// expose session cache creation\nforge.tls.createSessionCache = tls.createSessionCache;\n\n/**\n * Creates a new TLS connection. This does not make any assumptions about the\n * transport layer that TLS is working on top of, ie: it does not assume there\n * is a TCP/IP connection or establish one. A TLS connection is totally\n * abstracted away from the layer is runs on top of, it merely establishes a\n * secure channel between a client\" and a \"server\".\n *\n * A TLS connection contains 4 connection states: pending read and write, and\n * current read and write.\n *\n * At initialization, the current read and write states will be null. Only once\n * the security parameters have been set and the keys have been generated can\n * the pending states be converted into current states. Current states will be\n * updated for each record processed.\n *\n * A custom certificate verify callback may be provided to check information\n * like the common name on the server's certificate. It will be called for\n * every certificate in the chain. It has the following signature:\n *\n * variable func(c, certs, index, preVerify)\n * Where:\n * c The TLS connection\n * verified Set to true if certificate was verified, otherwise the alert\n * tls.Alert.Description for why the certificate failed.\n * depth The current index in the chain, where 0 is the server's cert.\n * certs The certificate chain, *NOTE* if the server was anonymous then\n * the chain will be empty.\n *\n * The function returns true on success and on failure either the appropriate\n * tls.Alert.Description or an object with 'alert' set to the appropriate\n * tls.Alert.Description and 'message' set to a custom error message. If true\n * is not returned then the connection will abort using, in order of\n * availability, first the returned alert description, second the preVerify\n * alert description, and lastly the default 'bad_certificate'.\n *\n * There are three callbacks that can be used to make use of client-side\n * certificates where each takes the TLS connection as the first parameter:\n *\n * getCertificate(conn, hint)\n * The second parameter is a hint as to which certificate should be\n * returned. If the connection entity is a client, then the hint will be\n * the CertificateRequest message from the server that is part of the\n * TLS protocol. If the connection entity is a server, then it will be\n * the servername list provided via an SNI extension the ClientHello, if\n * one was provided (empty array if not). The hint can be examined to\n * determine which certificate to use (advanced). Most implementations\n * will just return a certificate. The return value must be a\n * PEM-formatted certificate or an array of PEM-formatted certificates\n * that constitute a certificate chain, with the first in the array/chain\n * being the client's certificate.\n * getPrivateKey(conn, certificate)\n * The second parameter is an forge.pki X.509 certificate object that\n * is associated with the requested private key. The return value must\n * be a PEM-formatted private key.\n * getSignature(conn, bytes, callback)\n * This callback can be used instead of getPrivateKey if the private key\n * is not directly accessible in javascript or should not be. For\n * instance, a secure external web service could provide the signature\n * in exchange for appropriate credentials. The second parameter is a\n * string of bytes to be signed that are part of the TLS protocol. These\n * bytes are used to verify that the private key for the previously\n * provided client-side certificate is accessible to the client. The\n * callback is a function that takes 2 parameters, the TLS connection\n * and the RSA encrypted (signed) bytes as a string. This callback must\n * be called once the signature is ready.\n *\n * @param options the options for this connection:\n * server: true if the connection is server-side, false for client.\n * sessionId: a session ID to reuse, null for a new connection.\n * caStore: an array of certificates to trust.\n * sessionCache: a session cache to use.\n * cipherSuites: an optional array of cipher suites to use,\n * see tls.CipherSuites.\n * connected: function(conn) called when the first handshake completes.\n * virtualHost: the virtual server name to use in a TLS SNI extension.\n * verifyClient: true to require a client certificate in server mode,\n * 'optional' to request one, false not to (default: false).\n * verify: a handler used to custom verify certificates in the chain.\n * verifyOptions: an object with options for the certificate chain validation.\n * See documentation of pki.verifyCertificateChain for possible options.\n * verifyOptions.verify is ignored. If you wish to specify a verify handler\n * use the verify key.\n * getCertificate: an optional callback used to get a certificate or\n * a chain of certificates (as an array).\n * getPrivateKey: an optional callback used to get a private key.\n * getSignature: an optional callback used to get a signature.\n * tlsDataReady: function(conn) called when TLS protocol data has been\n * prepared and is ready to be used (typically sent over a socket\n * connection to its destination), read from conn.tlsData buffer.\n * dataReady: function(conn) called when application data has\n * been parsed from a TLS record and should be consumed by the\n * application, read from conn.data buffer.\n * closed: function(conn) called when the connection has been closed.\n * error: function(conn, error) called when there was an error.\n * deflate: function(inBytes) if provided, will deflate TLS records using\n * the deflate algorithm if the server supports it.\n * inflate: function(inBytes) if provided, will inflate TLS records using\n * the deflate algorithm if the server supports it.\n *\n * @return the new TLS connection.\n */\nforge.tls.createConnection = tls.createConnection;\n","/**\n * A Javascript implementation of AES Cipher Suites for TLS.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2009-2015 Digital Bazaar, Inc.\n *\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./tls');\n\nvar tls = module.exports = forge.tls;\n\n/**\n * Supported cipher suites.\n */\ntls.CipherSuites['TLS_RSA_WITH_AES_128_CBC_SHA'] = {\n id: [0x00, 0x2f],\n name: 'TLS_RSA_WITH_AES_128_CBC_SHA',\n initSecurityParameters: function(sp) {\n sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes;\n sp.cipher_type = tls.CipherType.block;\n sp.enc_key_length = 16;\n sp.block_length = 16;\n sp.fixed_iv_length = 16;\n sp.record_iv_length = 16;\n sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1;\n sp.mac_length = 20;\n sp.mac_key_length = 20;\n },\n initConnectionState: initConnectionState\n};\ntls.CipherSuites['TLS_RSA_WITH_AES_256_CBC_SHA'] = {\n id: [0x00, 0x35],\n name: 'TLS_RSA_WITH_AES_256_CBC_SHA',\n initSecurityParameters: function(sp) {\n sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes;\n sp.cipher_type = tls.CipherType.block;\n sp.enc_key_length = 32;\n sp.block_length = 16;\n sp.fixed_iv_length = 16;\n sp.record_iv_length = 16;\n sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1;\n sp.mac_length = 20;\n sp.mac_key_length = 20;\n },\n initConnectionState: initConnectionState\n};\n\nfunction initConnectionState(state, c, sp) {\n var client = (c.entity === forge.tls.ConnectionEnd.client);\n\n // cipher setup\n state.read.cipherState = {\n init: false,\n cipher: forge.cipher.createDecipher('AES-CBC', client ?\n sp.keys.server_write_key : sp.keys.client_write_key),\n iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV\n };\n state.write.cipherState = {\n init: false,\n cipher: forge.cipher.createCipher('AES-CBC', client ?\n sp.keys.client_write_key : sp.keys.server_write_key),\n iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV\n };\n state.read.cipherFunction = decrypt_aes_cbc_sha1;\n state.write.cipherFunction = encrypt_aes_cbc_sha1;\n\n // MAC setup\n state.read.macLength = state.write.macLength = sp.mac_length;\n state.read.macFunction = state.write.macFunction = tls.hmac_sha1;\n}\n\n/**\n * Encrypts the TLSCompressed record into a TLSCipherText record using AES\n * in CBC mode.\n *\n * @param record the TLSCompressed record to encrypt.\n * @param s the ConnectionState to use.\n *\n * @return true on success, false on failure.\n */\nfunction encrypt_aes_cbc_sha1(record, s) {\n var rval = false;\n\n // append MAC to fragment, update sequence number\n var mac = s.macFunction(s.macKey, s.sequenceNumber, record);\n record.fragment.putBytes(mac);\n s.updateSequenceNumber();\n\n // TLS 1.1+ use an explicit IV every time to protect against CBC attacks\n var iv;\n if(record.version.minor === tls.Versions.TLS_1_0.minor) {\n // use the pre-generated IV when initializing for TLS 1.0, otherwise use\n // the residue from the previous encryption\n iv = s.cipherState.init ? null : s.cipherState.iv;\n } else {\n iv = forge.random.getBytesSync(16);\n }\n\n s.cipherState.init = true;\n\n // start cipher\n var cipher = s.cipherState.cipher;\n cipher.start({iv: iv});\n\n // TLS 1.1+ write IV into output\n if(record.version.minor >= tls.Versions.TLS_1_1.minor) {\n cipher.output.putBytes(iv);\n }\n\n // do encryption (default padding is appropriate)\n cipher.update(record.fragment);\n if(cipher.finish(encrypt_aes_cbc_sha1_padding)) {\n // set record fragment to encrypted output\n record.fragment = cipher.output;\n record.length = record.fragment.length();\n rval = true;\n }\n\n return rval;\n}\n\n/**\n * Handles padding for aes_cbc_sha1 in encrypt mode.\n *\n * @param blockSize the block size.\n * @param input the input buffer.\n * @param decrypt true in decrypt mode, false in encrypt mode.\n *\n * @return true on success, false on failure.\n */\nfunction encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) {\n /* The encrypted data length (TLSCiphertext.length) is one more than the sum\n of SecurityParameters.block_length, TLSCompressed.length,\n SecurityParameters.mac_length, and padding_length.\n\n The padding may be any length up to 255 bytes long, as long as it results in\n the TLSCiphertext.length being an integral multiple of the block length.\n Lengths longer than necessary might be desirable to frustrate attacks on a\n protocol based on analysis of the lengths of exchanged messages. Each uint8\n in the padding data vector must be filled with the padding length value.\n\n The padding length should be such that the total size of the\n GenericBlockCipher structure is a multiple of the cipher's block length.\n Legal values range from zero to 255, inclusive. This length specifies the\n length of the padding field exclusive of the padding_length field itself.\n\n This is slightly different from PKCS#7 because the padding value is 1\n less than the actual number of padding bytes if you include the\n padding_length uint8 itself as a padding byte. */\n if(!decrypt) {\n // get the number of padding bytes required to reach the blockSize and\n // subtract 1 for the padding value (to make room for the padding_length\n // uint8)\n var padding = blockSize - (input.length() % blockSize);\n input.fillWithByte(padding - 1, padding);\n }\n return true;\n}\n\n/**\n * Handles padding for aes_cbc_sha1 in decrypt mode.\n *\n * @param blockSize the block size.\n * @param output the output buffer.\n * @param decrypt true in decrypt mode, false in encrypt mode.\n *\n * @return true on success, false on failure.\n */\nfunction decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) {\n var rval = true;\n if(decrypt) {\n /* The last byte in the output specifies the number of padding bytes not\n including itself. Each of the padding bytes has the same value as that\n last byte (known as the padding_length). Here we check all padding\n bytes to ensure they have the value of padding_length even if one of\n them is bad in order to ward-off timing attacks. */\n var len = output.length();\n var paddingLength = output.last();\n for(var i = len - 1 - paddingLength; i < len - 1; ++i) {\n rval = rval && (output.at(i) == paddingLength);\n }\n if(rval) {\n // trim off padding bytes and last padding length byte\n output.truncate(paddingLength + 1);\n }\n }\n return rval;\n}\n\n/**\n * Decrypts a TLSCipherText record into a TLSCompressed record using\n * AES in CBC mode.\n *\n * @param record the TLSCipherText record to decrypt.\n * @param s the ConnectionState to use.\n *\n * @return true on success, false on failure.\n */\nfunction decrypt_aes_cbc_sha1(record, s) {\n var rval = false;\n\n var iv;\n if(record.version.minor === tls.Versions.TLS_1_0.minor) {\n // use pre-generated IV when initializing for TLS 1.0, otherwise use the\n // residue from the previous decryption\n iv = s.cipherState.init ? null : s.cipherState.iv;\n } else {\n // TLS 1.1+ use an explicit IV every time to protect against CBC attacks\n // that is appended to the record fragment\n iv = record.fragment.getBytes(16);\n }\n\n s.cipherState.init = true;\n\n // start cipher\n var cipher = s.cipherState.cipher;\n cipher.start({iv: iv});\n\n // do decryption\n cipher.update(record.fragment);\n rval = cipher.finish(decrypt_aes_cbc_sha1_padding);\n\n // even if decryption fails, keep going to minimize timing attacks\n\n // decrypted data:\n // first (len - 20) bytes = application data\n // last 20 bytes = MAC\n var macLen = s.macLength;\n\n // create a random MAC to check against should the mac length check fail\n // Note: do this regardless of the failure to keep timing consistent\n var mac = forge.random.getBytesSync(macLen);\n\n // get fragment and mac\n var len = cipher.output.length();\n if(len >= macLen) {\n record.fragment = cipher.output.getBytes(len - macLen);\n mac = cipher.output.getBytes(macLen);\n } else {\n // bad data, but get bytes anyway to try to keep timing consistent\n record.fragment = cipher.output.getBytes();\n }\n record.fragment = forge.util.createBuffer(record.fragment);\n record.length = record.fragment.length();\n\n // see if data integrity checks out, update sequence number\n var mac2 = s.macFunction(s.macKey, s.sequenceNumber, record);\n s.updateSequenceNumber();\n rval = compareMacs(s.macKey, mac, mac2) && rval;\n return rval;\n}\n\n/**\n * Safely compare two MACs. This function will compare two MACs in a way\n * that protects against timing attacks.\n *\n * TODO: Expose elsewhere as a utility API.\n *\n * See: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/february/double-hmac-verification/\n *\n * @param key the MAC key to use.\n * @param mac1 as a binary-encoded string of bytes.\n * @param mac2 as a binary-encoded string of bytes.\n *\n * @return true if the MACs are the same, false if not.\n */\nfunction compareMacs(key, mac1, mac2) {\n var hmac = forge.hmac.create();\n\n hmac.start('SHA1', key);\n hmac.update(mac1);\n mac1 = hmac.digest().getBytes();\n\n hmac.start(null, null);\n hmac.update(mac2);\n mac2 = hmac.digest().getBytes();\n\n return mac1 === mac2;\n}\n","/**\n * Secure Hash Algorithm with a 1024-bit block size implementation.\n *\n * This includes: SHA-512, SHA-384, SHA-512/224, and SHA-512/256. For\n * SHA-256 (block size 512 bits), see sha256.js.\n *\n * See FIPS 180-4 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2014-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha512 = module.exports = forge.sha512 = forge.sha512 || {};\n\n// SHA-512\nforge.md.sha512 = forge.md.algorithms.sha512 = sha512;\n\n// SHA-384\nvar sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {};\nsha384.create = function() {\n return sha512.create('SHA-384');\n};\nforge.md.sha384 = forge.md.algorithms.sha384 = sha384;\n\n// SHA-512/256\nforge.sha512.sha256 = forge.sha512.sha256 || {\n create: function() {\n return sha512.create('SHA-512/256');\n }\n};\nforge.md['sha512/256'] = forge.md.algorithms['sha512/256'] =\n forge.sha512.sha256;\n\n// SHA-512/224\nforge.sha512.sha224 = forge.sha512.sha224 || {\n create: function() {\n return sha512.create('SHA-512/224');\n }\n};\nforge.md['sha512/224'] = forge.md.algorithms['sha512/224'] =\n forge.sha512.sha224;\n\n/**\n * Creates a SHA-2 message digest object.\n *\n * @param algorithm the algorithm to use (SHA-512, SHA-384, SHA-512/224,\n * SHA-512/256).\n *\n * @return a message digest object.\n */\nsha512.create = function(algorithm) {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n if(typeof algorithm === 'undefined') {\n algorithm = 'SHA-512';\n }\n\n if(!(algorithm in _states)) {\n throw new Error('Invalid SHA-512 algorithm: ' + algorithm);\n }\n\n // SHA-512 state contains eight 64-bit integers (each as two 32-bit ints)\n var _state = _states[algorithm];\n var _h = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for 64-bit word storage\n var _w = new Array(80);\n for(var wi = 0; wi < 80; ++wi) {\n _w[wi] = new Array(2);\n }\n\n // determine digest length by algorithm name (default)\n var digestLength = 64;\n switch(algorithm) {\n case 'SHA-384':\n digestLength = 48;\n break;\n case 'SHA-512/256':\n digestLength = 32;\n break;\n case 'SHA-512/224':\n digestLength = 28;\n break;\n }\n\n // message digest object\n var md = {\n // SHA-512 => sha512\n algorithm: algorithm.replace('-', '').toLowerCase(),\n blockLength: 128,\n digestLength: digestLength,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 16\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength128 for backwards-compatibility)\n md.fullMessageLength = md.messageLength128 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _h = new Array(_state.length);\n for(var i = 0; i < _state.length; ++i) {\n _h[i] = _state[i].slice(0);\n }\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_h, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-512 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 896 mod 1024. In other words,\n the data to be digested must be a multiple of 1024 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 16 bytes (128\n bits), that means that the last segment of the data must have 112 bytes\n (896 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 896 mod 1024 because\n 1024 - 128 = 896.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 896 mod 1024, then 1024 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var h = new Array(_h.length);\n for(var i = 0; i < _h.length; ++i) {\n h[i] = _h[i].slice(0);\n }\n _update(h, _w, finalBlock);\n var rval = forge.util.createBuffer();\n var hlen;\n if(algorithm === 'SHA-512') {\n hlen = h.length;\n } else if(algorithm === 'SHA-384') {\n hlen = h.length - 2;\n } else {\n hlen = h.length - 4;\n }\n for(var i = 0; i < hlen; ++i) {\n rval.putInt32(h[i][0]);\n if(i !== hlen - 1 || algorithm !== 'SHA-512/224') {\n rval.putInt32(h[i][1]);\n }\n }\n return rval;\n };\n\n return md;\n};\n\n// sha-512 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n// table of constants\nvar _k = null;\n\n// initial hash states\nvar _states = null;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 128);\n\n // create K table for SHA-512\n _k = [\n [0x428a2f98, 0xd728ae22], [0x71374491, 0x23ef65cd],\n [0xb5c0fbcf, 0xec4d3b2f], [0xe9b5dba5, 0x8189dbbc],\n [0x3956c25b, 0xf348b538], [0x59f111f1, 0xb605d019],\n [0x923f82a4, 0xaf194f9b], [0xab1c5ed5, 0xda6d8118],\n [0xd807aa98, 0xa3030242], [0x12835b01, 0x45706fbe],\n [0x243185be, 0x4ee4b28c], [0x550c7dc3, 0xd5ffb4e2],\n [0x72be5d74, 0xf27b896f], [0x80deb1fe, 0x3b1696b1],\n [0x9bdc06a7, 0x25c71235], [0xc19bf174, 0xcf692694],\n [0xe49b69c1, 0x9ef14ad2], [0xefbe4786, 0x384f25e3],\n [0x0fc19dc6, 0x8b8cd5b5], [0x240ca1cc, 0x77ac9c65],\n [0x2de92c6f, 0x592b0275], [0x4a7484aa, 0x6ea6e483],\n [0x5cb0a9dc, 0xbd41fbd4], [0x76f988da, 0x831153b5],\n [0x983e5152, 0xee66dfab], [0xa831c66d, 0x2db43210],\n [0xb00327c8, 0x98fb213f], [0xbf597fc7, 0xbeef0ee4],\n [0xc6e00bf3, 0x3da88fc2], [0xd5a79147, 0x930aa725],\n [0x06ca6351, 0xe003826f], [0x14292967, 0x0a0e6e70],\n [0x27b70a85, 0x46d22ffc], [0x2e1b2138, 0x5c26c926],\n [0x4d2c6dfc, 0x5ac42aed], [0x53380d13, 0x9d95b3df],\n [0x650a7354, 0x8baf63de], [0x766a0abb, 0x3c77b2a8],\n [0x81c2c92e, 0x47edaee6], [0x92722c85, 0x1482353b],\n [0xa2bfe8a1, 0x4cf10364], [0xa81a664b, 0xbc423001],\n [0xc24b8b70, 0xd0f89791], [0xc76c51a3, 0x0654be30],\n [0xd192e819, 0xd6ef5218], [0xd6990624, 0x5565a910],\n [0xf40e3585, 0x5771202a], [0x106aa070, 0x32bbd1b8],\n [0x19a4c116, 0xb8d2d0c8], [0x1e376c08, 0x5141ab53],\n [0x2748774c, 0xdf8eeb99], [0x34b0bcb5, 0xe19b48a8],\n [0x391c0cb3, 0xc5c95a63], [0x4ed8aa4a, 0xe3418acb],\n [0x5b9cca4f, 0x7763e373], [0x682e6ff3, 0xd6b2b8a3],\n [0x748f82ee, 0x5defb2fc], [0x78a5636f, 0x43172f60],\n [0x84c87814, 0xa1f0ab72], [0x8cc70208, 0x1a6439ec],\n [0x90befffa, 0x23631e28], [0xa4506ceb, 0xde82bde9],\n [0xbef9a3f7, 0xb2c67915], [0xc67178f2, 0xe372532b],\n [0xca273ece, 0xea26619c], [0xd186b8c7, 0x21c0c207],\n [0xeada7dd6, 0xcde0eb1e], [0xf57d4f7f, 0xee6ed178],\n [0x06f067aa, 0x72176fba], [0x0a637dc5, 0xa2c898a6],\n [0x113f9804, 0xbef90dae], [0x1b710b35, 0x131c471b],\n [0x28db77f5, 0x23047d84], [0x32caab7b, 0x40c72493],\n [0x3c9ebe0a, 0x15c9bebc], [0x431d67c4, 0x9c100d4c],\n [0x4cc5d4be, 0xcb3e42b6], [0x597f299c, 0xfc657e2a],\n [0x5fcb6fab, 0x3ad6faec], [0x6c44198c, 0x4a475817]\n ];\n\n // initial hash states\n _states = {};\n _states['SHA-512'] = [\n [0x6a09e667, 0xf3bcc908],\n [0xbb67ae85, 0x84caa73b],\n [0x3c6ef372, 0xfe94f82b],\n [0xa54ff53a, 0x5f1d36f1],\n [0x510e527f, 0xade682d1],\n [0x9b05688c, 0x2b3e6c1f],\n [0x1f83d9ab, 0xfb41bd6b],\n [0x5be0cd19, 0x137e2179]\n ];\n _states['SHA-384'] = [\n [0xcbbb9d5d, 0xc1059ed8],\n [0x629a292a, 0x367cd507],\n [0x9159015a, 0x3070dd17],\n [0x152fecd8, 0xf70e5939],\n [0x67332667, 0xffc00b31],\n [0x8eb44a87, 0x68581511],\n [0xdb0c2e0d, 0x64f98fa7],\n [0x47b5481d, 0xbefa4fa4]\n ];\n _states['SHA-512/256'] = [\n [0x22312194, 0xFC2BF72C],\n [0x9F555FA3, 0xC84C64C2],\n [0x2393B86B, 0x6F53B151],\n [0x96387719, 0x5940EABD],\n [0x96283EE2, 0xA88EFFE3],\n [0xBE5E1E25, 0x53863992],\n [0x2B0199FC, 0x2C85B8AA],\n [0x0EB72DDC, 0x81C52CA2]\n ];\n _states['SHA-512/224'] = [\n [0x8C3D37C8, 0x19544DA2],\n [0x73E19966, 0x89DCD4D6],\n [0x1DFAB7AE, 0x32FF9C82],\n [0x679DD514, 0x582F9FCF],\n [0x0F6D2B69, 0x7BD44DA8],\n [0x77E36F73, 0x04C48942],\n [0x3F9D85A8, 0x6A1D36C8],\n [0x1112E6AD, 0x91D692A1]\n ];\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-512 state with the given byte buffer.\n *\n * @param s the SHA-512 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (128 byte) chunks\n var t1_hi, t1_lo;\n var t2_hi, t2_lo;\n var s0_hi, s0_lo;\n var s1_hi, s1_lo;\n var ch_hi, ch_lo;\n var maj_hi, maj_lo;\n var a_hi, a_lo;\n var b_hi, b_lo;\n var c_hi, c_lo;\n var d_hi, d_lo;\n var e_hi, e_lo;\n var f_hi, f_lo;\n var g_hi, g_lo;\n var h_hi, h_lo;\n var i, hi, lo, w2, w7, w15, w16;\n var len = bytes.length();\n while(len >= 128) {\n // the w array will be populated with sixteen 64-bit big-endian words\n // and then extended into 64 64-bit words according to SHA-512\n for(i = 0; i < 16; ++i) {\n w[i][0] = bytes.getInt32() >>> 0;\n w[i][1] = bytes.getInt32() >>> 0;\n }\n for(; i < 80; ++i) {\n // for word 2 words ago: ROTR 19(x) ^ ROTR 61(x) ^ SHR 6(x)\n w2 = w[i - 2];\n hi = w2[0];\n lo = w2[1];\n\n // high bits\n t1_hi = (\n ((hi >>> 19) | (lo << 13)) ^ // ROTR 19\n ((lo >>> 29) | (hi << 3)) ^ // ROTR 61/(swap + ROTR 29)\n (hi >>> 6)) >>> 0; // SHR 6\n // low bits\n t1_lo = (\n ((hi << 13) | (lo >>> 19)) ^ // ROTR 19\n ((lo << 3) | (hi >>> 29)) ^ // ROTR 61/(swap + ROTR 29)\n ((hi << 26) | (lo >>> 6))) >>> 0; // SHR 6\n\n // for word 15 words ago: ROTR 1(x) ^ ROTR 8(x) ^ SHR 7(x)\n w15 = w[i - 15];\n hi = w15[0];\n lo = w15[1];\n\n // high bits\n t2_hi = (\n ((hi >>> 1) | (lo << 31)) ^ // ROTR 1\n ((hi >>> 8) | (lo << 24)) ^ // ROTR 8\n (hi >>> 7)) >>> 0; // SHR 7\n // low bits\n t2_lo = (\n ((hi << 31) | (lo >>> 1)) ^ // ROTR 1\n ((hi << 24) | (lo >>> 8)) ^ // ROTR 8\n ((hi << 25) | (lo >>> 7))) >>> 0; // SHR 7\n\n // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^64 (carry lo overflow)\n w7 = w[i - 7];\n w16 = w[i - 16];\n lo = (t1_lo + w7[1] + t2_lo + w16[1]);\n w[i][0] = (t1_hi + w7[0] + t2_hi + w16[0] +\n ((lo / 0x100000000) >>> 0)) >>> 0;\n w[i][1] = lo >>> 0;\n }\n\n // initialize hash value for this chunk\n a_hi = s[0][0];\n a_lo = s[0][1];\n b_hi = s[1][0];\n b_lo = s[1][1];\n c_hi = s[2][0];\n c_lo = s[2][1];\n d_hi = s[3][0];\n d_lo = s[3][1];\n e_hi = s[4][0];\n e_lo = s[4][1];\n f_hi = s[5][0];\n f_lo = s[5][1];\n g_hi = s[6][0];\n g_lo = s[6][1];\n h_hi = s[7][0];\n h_lo = s[7][1];\n\n // round function\n for(i = 0; i < 80; ++i) {\n // Sum1(e) = ROTR 14(e) ^ ROTR 18(e) ^ ROTR 41(e)\n s1_hi = (\n ((e_hi >>> 14) | (e_lo << 18)) ^ // ROTR 14\n ((e_hi >>> 18) | (e_lo << 14)) ^ // ROTR 18\n ((e_lo >>> 9) | (e_hi << 23))) >>> 0; // ROTR 41/(swap + ROTR 9)\n s1_lo = (\n ((e_hi << 18) | (e_lo >>> 14)) ^ // ROTR 14\n ((e_hi << 14) | (e_lo >>> 18)) ^ // ROTR 18\n ((e_lo << 23) | (e_hi >>> 9))) >>> 0; // ROTR 41/(swap + ROTR 9)\n\n // Ch(e, f, g) (optimized the same way as SHA-1)\n ch_hi = (g_hi ^ (e_hi & (f_hi ^ g_hi))) >>> 0;\n ch_lo = (g_lo ^ (e_lo & (f_lo ^ g_lo))) >>> 0;\n\n // Sum0(a) = ROTR 28(a) ^ ROTR 34(a) ^ ROTR 39(a)\n s0_hi = (\n ((a_hi >>> 28) | (a_lo << 4)) ^ // ROTR 28\n ((a_lo >>> 2) | (a_hi << 30)) ^ // ROTR 34/(swap + ROTR 2)\n ((a_lo >>> 7) | (a_hi << 25))) >>> 0; // ROTR 39/(swap + ROTR 7)\n s0_lo = (\n ((a_hi << 4) | (a_lo >>> 28)) ^ // ROTR 28\n ((a_lo << 30) | (a_hi >>> 2)) ^ // ROTR 34/(swap + ROTR 2)\n ((a_lo << 25) | (a_hi >>> 7))) >>> 0; // ROTR 39/(swap + ROTR 7)\n\n // Maj(a, b, c) (optimized the same way as SHA-1)\n maj_hi = ((a_hi & b_hi) | (c_hi & (a_hi ^ b_hi))) >>> 0;\n maj_lo = ((a_lo & b_lo) | (c_lo & (a_lo ^ b_lo))) >>> 0;\n\n // main algorithm\n // t1 = (h + s1 + ch + _k[i] + _w[i]) modulo 2^64 (carry lo overflow)\n lo = (h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]);\n t1_hi = (h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] +\n ((lo / 0x100000000) >>> 0)) >>> 0;\n t1_lo = lo >>> 0;\n\n // t2 = s0 + maj modulo 2^64 (carry lo overflow)\n lo = s0_lo + maj_lo;\n t2_hi = (s0_hi + maj_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n t2_lo = lo >>> 0;\n\n h_hi = g_hi;\n h_lo = g_lo;\n\n g_hi = f_hi;\n g_lo = f_lo;\n\n f_hi = e_hi;\n f_lo = e_lo;\n\n // e = (d + t1) modulo 2^64 (carry lo overflow)\n lo = d_lo + t1_lo;\n e_hi = (d_hi + t1_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n e_lo = lo >>> 0;\n\n d_hi = c_hi;\n d_lo = c_lo;\n\n c_hi = b_hi;\n c_lo = b_lo;\n\n b_hi = a_hi;\n b_lo = a_lo;\n\n // a = (t1 + t2) modulo 2^64 (carry lo overflow)\n lo = t1_lo + t2_lo;\n a_hi = (t1_hi + t2_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n a_lo = lo >>> 0;\n }\n\n // update hash state (additional modulo 2^64)\n lo = s[0][1] + a_lo;\n s[0][0] = (s[0][0] + a_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[0][1] = lo >>> 0;\n\n lo = s[1][1] + b_lo;\n s[1][0] = (s[1][0] + b_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[1][1] = lo >>> 0;\n\n lo = s[2][1] + c_lo;\n s[2][0] = (s[2][0] + c_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[2][1] = lo >>> 0;\n\n lo = s[3][1] + d_lo;\n s[3][0] = (s[3][0] + d_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[3][1] = lo >>> 0;\n\n lo = s[4][1] + e_lo;\n s[4][0] = (s[4][0] + e_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[4][1] = lo >>> 0;\n\n lo = s[5][1] + f_lo;\n s[5][0] = (s[5][0] + f_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[5][1] = lo >>> 0;\n\n lo = s[6][1] + g_lo;\n s[6][0] = (s[6][0] + g_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[6][1] = lo >>> 0;\n\n lo = s[7][1] + h_lo;\n s[7][0] = (s[7][0] + h_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[7][1] = lo >>> 0;\n\n len -= 128;\n }\n}\n","/**\n * Copyright (c) 2019 Digital Bazaar, Inc.\n */\n\nvar forge = require('./forge');\nrequire('./asn1');\nvar asn1 = forge.asn1;\n\nexports.privateKeyValidator = {\n // PrivateKeyInfo\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // Version (INTEGER)\n name: 'PrivateKeyInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyVersion'\n }, {\n // privateKeyAlgorithm\n name: 'PrivateKeyInfo.privateKeyAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'privateKeyOid'\n }]\n }, {\n // PrivateKey\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'privateKey'\n }]\n};\n\nexports.publicKeyValidator = {\n name: 'SubjectPublicKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'subjectPublicKeyInfo',\n value: [{\n name: 'SubjectPublicKeyInfo.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'publicKeyOid'\n }]\n },\n // capture group for ed25519PublicKey\n {\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n composed: true,\n captureBitStringValue: 'ed25519PublicKey'\n }\n // FIXME: this is capture group for rsaPublicKey, use it in this API or\n // discard?\n /* {\n // subjectPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n value: [{\n // RSAPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n captureAsn1: 'rsaPublicKey'\n }]\n } */\n ]\n};\n","/**\n * JavaScript implementation of Ed25519.\n *\n * Copyright (c) 2017-2019 Digital Bazaar, Inc.\n *\n * This implementation is based on the most excellent TweetNaCl which is\n * in the public domain. Many thanks to its contributors:\n *\n * https://github.com/dchest/tweetnacl-js\n */\nvar forge = require('./forge');\nrequire('./jsbn');\nrequire('./random');\nrequire('./sha512');\nrequire('./util');\nvar asn1Validator = require('./asn1-validator');\nvar publicKeyValidator = asn1Validator.publicKeyValidator;\nvar privateKeyValidator = asn1Validator.privateKeyValidator;\n\nif(typeof BigInteger === 'undefined') {\n var BigInteger = forge.jsbn.BigInteger;\n}\n\nvar ByteBuffer = forge.util.ByteBuffer;\nvar NativeBuffer = typeof Buffer === 'undefined' ? Uint8Array : Buffer;\n\n/*\n * Ed25519 algorithms, see RFC 8032:\n * https://tools.ietf.org/html/rfc8032\n */\nforge.pki = forge.pki || {};\nmodule.exports = forge.pki.ed25519 = forge.ed25519 = forge.ed25519 || {};\nvar ed25519 = forge.ed25519;\n\ned25519.constants = {};\ned25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32;\ned25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64;\ned25519.constants.SEED_BYTE_LENGTH = 32;\ned25519.constants.SIGN_BYTE_LENGTH = 64;\ned25519.constants.HASH_BYTE_LENGTH = 64;\n\ned25519.generateKeyPair = function(options) {\n options = options || {};\n var seed = options.seed;\n if(seed === undefined) {\n // generate seed\n seed = forge.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH);\n } else if(typeof seed === 'string') {\n if(seed.length !== ed25519.constants.SEED_BYTE_LENGTH) {\n throw new TypeError(\n '\"seed\" must be ' + ed25519.constants.SEED_BYTE_LENGTH +\n ' bytes in length.');\n }\n } else if(!(seed instanceof Uint8Array)) {\n throw new TypeError(\n '\"seed\" must be a node.js Buffer, Uint8Array, or a binary string.');\n }\n\n seed = messageToNativeBuffer({message: seed, encoding: 'binary'});\n\n var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);\n var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);\n for(var i = 0; i < 32; ++i) {\n sk[i] = seed[i];\n }\n crypto_sign_keypair(pk, sk);\n return {publicKey: pk, privateKey: sk};\n};\n\n/**\n * Converts a private key from a RFC8410 ASN.1 encoding.\n *\n * @param obj - The asn1 representation of a private key.\n *\n * @returns {Object} keyInfo - The key information.\n * @returns {Buffer|Uint8Array} keyInfo.privateKeyBytes - 32 private key bytes.\n */\ned25519.privateKeyFromAsn1 = function(obj) {\n var capture = {};\n var errors = [];\n var valid = forge.asn1.validate(obj, privateKeyValidator, capture, errors);\n if(!valid) {\n var error = new Error('Invalid Key.');\n error.errors = errors;\n throw error;\n }\n var oid = forge.asn1.derToOid(capture.privateKeyOid);\n var ed25519Oid = forge.oids.EdDSA25519;\n if(oid !== ed25519Oid) {\n throw new Error('Invalid OID \"' + oid + '\"; OID must be \"' +\n ed25519Oid + '\".');\n }\n var privateKey = capture.privateKey;\n // manually extract the private key bytes from nested octet string, see FIXME:\n // https://github.com/digitalbazaar/forge/blob/master/lib/asn1.js#L542\n var privateKeyBytes = messageToNativeBuffer({\n message: forge.asn1.fromDer(privateKey).value,\n encoding: 'binary'\n });\n // TODO: RFC8410 specifies a format for encoding the public key bytes along\n // with the private key bytes. `publicKeyBytes` can be returned in the\n // future. https://tools.ietf.org/html/rfc8410#section-10.3\n return {privateKeyBytes: privateKeyBytes};\n};\n\n/**\n * Converts a public key from a RFC8410 ASN.1 encoding.\n *\n * @param obj - The asn1 representation of a public key.\n *\n * @return {Buffer|Uint8Array} - 32 public key bytes.\n */\ned25519.publicKeyFromAsn1 = function(obj) {\n // get SubjectPublicKeyInfo\n var capture = {};\n var errors = [];\n var valid = forge.asn1.validate(obj, publicKeyValidator, capture, errors);\n if(!valid) {\n var error = new Error('Invalid Key.');\n error.errors = errors;\n throw error;\n }\n var oid = forge.asn1.derToOid(capture.publicKeyOid);\n var ed25519Oid = forge.oids.EdDSA25519;\n if(oid !== ed25519Oid) {\n throw new Error('Invalid OID \"' + oid + '\"; OID must be \"' +\n ed25519Oid + '\".');\n }\n var publicKeyBytes = capture.ed25519PublicKey;\n if(publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) {\n throw new Error('Key length is invalid.');\n }\n return messageToNativeBuffer({\n message: publicKeyBytes,\n encoding: 'binary'\n });\n};\n\ned25519.publicKeyFromPrivateKey = function(options) {\n options = options || {};\n var privateKey = messageToNativeBuffer({\n message: options.privateKey, encoding: 'binary'\n });\n if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) {\n throw new TypeError(\n '\"options.privateKey\" must have a byte length of ' +\n ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);\n }\n\n var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);\n for(var i = 0; i < pk.length; ++i) {\n pk[i] = privateKey[32 + i];\n }\n return pk;\n};\n\ned25519.sign = function(options) {\n options = options || {};\n var msg = messageToNativeBuffer(options);\n var privateKey = messageToNativeBuffer({\n message: options.privateKey,\n encoding: 'binary'\n });\n if(privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) {\n var keyPair = ed25519.generateKeyPair({seed: privateKey});\n privateKey = keyPair.privateKey;\n } else if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) {\n throw new TypeError(\n '\"options.privateKey\" must have a byte length of ' +\n ed25519.constants.SEED_BYTE_LENGTH + ' or ' +\n ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);\n }\n\n var signedMsg = new NativeBuffer(\n ed25519.constants.SIGN_BYTE_LENGTH + msg.length);\n crypto_sign(signedMsg, msg, msg.length, privateKey);\n\n var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH);\n for(var i = 0; i < sig.length; ++i) {\n sig[i] = signedMsg[i];\n }\n return sig;\n};\n\ned25519.verify = function(options) {\n options = options || {};\n var msg = messageToNativeBuffer(options);\n if(options.signature === undefined) {\n throw new TypeError(\n '\"options.signature\" must be a node.js Buffer, a Uint8Array, a forge ' +\n 'ByteBuffer, or a binary string.');\n }\n var sig = messageToNativeBuffer({\n message: options.signature,\n encoding: 'binary'\n });\n if(sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) {\n throw new TypeError(\n '\"options.signature\" must have a byte length of ' +\n ed25519.constants.SIGN_BYTE_LENGTH);\n }\n var publicKey = messageToNativeBuffer({\n message: options.publicKey,\n encoding: 'binary'\n });\n if(publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) {\n throw new TypeError(\n '\"options.publicKey\" must have a byte length of ' +\n ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);\n }\n\n var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length);\n var m = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length);\n var i;\n for(i = 0; i < ed25519.constants.SIGN_BYTE_LENGTH; ++i) {\n sm[i] = sig[i];\n }\n for(i = 0; i < msg.length; ++i) {\n sm[i + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i];\n }\n return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);\n};\n\nfunction messageToNativeBuffer(options) {\n var message = options.message;\n if(message instanceof Uint8Array || message instanceof NativeBuffer) {\n return message;\n }\n\n var encoding = options.encoding;\n if(message === undefined) {\n if(options.md) {\n // TODO: more rigorous validation that `md` is a MessageDigest\n message = options.md.digest().getBytes();\n encoding = 'binary';\n } else {\n throw new TypeError('\"options.message\" or \"options.md\" not specified.');\n }\n }\n\n if(typeof message === 'string' && !encoding) {\n throw new TypeError('\"options.encoding\" must be \"binary\" or \"utf8\".');\n }\n\n if(typeof message === 'string') {\n if(typeof Buffer !== 'undefined') {\n return Buffer.from(message, encoding);\n }\n message = new ByteBuffer(message, encoding);\n } else if(!(message instanceof ByteBuffer)) {\n throw new TypeError(\n '\"options.message\" must be a node.js Buffer, a Uint8Array, a forge ' +\n 'ByteBuffer, or a string with \"options.encoding\" specifying its ' +\n 'encoding.');\n }\n\n // convert to native buffer\n var buffer = new NativeBuffer(message.length());\n for(var i = 0; i < buffer.length; ++i) {\n buffer[i] = message.at(i);\n }\n return buffer;\n}\n\nvar gf0 = gf();\nvar gf1 = gf([1]);\nvar D = gf([\n 0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070,\n 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]);\nvar D2 = gf([\n 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0,\n 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]);\nvar X = gf([\n 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c,\n 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]);\nvar Y = gf([\n 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,\n 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]);\nvar L = new Float64Array([\n 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58,\n 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);\nvar I = gf([\n 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43,\n 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);\n\n// TODO: update forge buffer implementation to use `Buffer` or `Uint8Array`,\n// whichever is available, to improve performance\nfunction sha512(msg, msgLen) {\n // Note: `out` and `msg` are NativeBuffer\n var md = forge.md.sha512.create();\n var buffer = new ByteBuffer(msg);\n md.update(buffer.getBytes(msgLen), 'binary');\n var hash = md.digest().getBytes();\n if(typeof Buffer !== 'undefined') {\n return Buffer.from(hash, 'binary');\n }\n var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH);\n for(var i = 0; i < 64; ++i) {\n out[i] = hash.charCodeAt(i);\n }\n return out;\n}\n\nfunction crypto_sign_keypair(pk, sk) {\n var p = [gf(), gf(), gf(), gf()];\n var i;\n\n var d = sha512(sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n scalarbase(p, d);\n pack(pk, p);\n\n for(i = 0; i < 32; ++i) {\n sk[i + 32] = pk[i];\n }\n return 0;\n}\n\n// Note: difference from C - smlen returned, not passed as argument.\nfunction crypto_sign(sm, m, n, sk) {\n var i, j, x = new Float64Array(64);\n var p = [gf(), gf(), gf(), gf()];\n\n var d = sha512(sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n var smlen = n + 64;\n for(i = 0; i < n; ++i) {\n sm[64 + i] = m[i];\n }\n for(i = 0; i < 32; ++i) {\n sm[32 + i] = d[32 + i];\n }\n\n var r = sha512(sm.subarray(32), n + 32);\n reduce(r);\n scalarbase(p, r);\n pack(sm, p);\n\n for(i = 32; i < 64; ++i) {\n sm[i] = sk[i];\n }\n var h = sha512(sm, n + 64);\n reduce(h);\n\n for(i = 32; i < 64; ++i) {\n x[i] = 0;\n }\n for(i = 0; i < 32; ++i) {\n x[i] = r[i];\n }\n for(i = 0; i < 32; ++i) {\n for(j = 0; j < 32; j++) {\n x[i + j] += h[i] * d[j];\n }\n }\n\n modL(sm.subarray(32), x);\n return smlen;\n}\n\nfunction crypto_sign_open(m, sm, n, pk) {\n var i, mlen;\n var t = new NativeBuffer(32);\n var p = [gf(), gf(), gf(), gf()],\n q = [gf(), gf(), gf(), gf()];\n\n mlen = -1;\n if(n < 64) {\n return -1;\n }\n\n if(unpackneg(q, pk)) {\n return -1;\n }\n\n for(i = 0; i < n; ++i) {\n m[i] = sm[i];\n }\n for(i = 0; i < 32; ++i) {\n m[i + 32] = pk[i];\n }\n var h = sha512(m, n);\n reduce(h);\n scalarmult(p, q, h);\n\n scalarbase(q, sm.subarray(32));\n add(p, q);\n pack(t, p);\n\n n -= 64;\n if(crypto_verify_32(sm, 0, t, 0)) {\n for(i = 0; i < n; ++i) {\n m[i] = 0;\n }\n return -1;\n }\n\n for(i = 0; i < n; ++i) {\n m[i] = sm[i + 64];\n }\n mlen = n;\n return mlen;\n}\n\nfunction modL(r, x) {\n var carry, i, j, k;\n for(i = 63; i >= 32; --i) {\n carry = 0;\n for(j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * L[j - (i - 32)];\n carry = (x[j] + 128) >> 8;\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for(j = 0; j < 32; ++j) {\n x[j] += carry - (x[31] >> 4) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for(j = 0; j < 32; ++j) {\n x[j] -= carry * L[j];\n }\n for(i = 0; i < 32; ++i) {\n x[i + 1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\n\nfunction reduce(r) {\n var x = new Float64Array(64);\n for(var i = 0; i < 64; ++i) {\n x[i] = r[i];\n r[i] = 0;\n }\n modL(r, x);\n}\n\nfunction add(p, q) {\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf(),\n g = gf(), h = gf(), t = gf();\n\n Z(a, p[1], p[0]);\n Z(t, q[1], q[0]);\n M(a, a, t);\n A(b, p[0], p[1]);\n A(t, q[0], q[1]);\n M(b, b, t);\n M(c, p[3], q[3]);\n M(c, c, D2);\n M(d, p[2], q[2]);\n A(d, d, d);\n Z(e, b, a);\n Z(f, d, c);\n A(g, d, c);\n A(h, b, a);\n\n M(p[0], e, f);\n M(p[1], h, g);\n M(p[2], g, f);\n M(p[3], e, h);\n}\n\nfunction cswap(p, q, b) {\n for(var i = 0; i < 4; ++i) {\n sel25519(p[i], q[i], b);\n }\n}\n\nfunction pack(r, p) {\n var tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n M(tx, p[0], zi);\n M(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\n\nfunction pack25519(o, n) {\n var i, j, b;\n var m = gf(), t = gf();\n for(i = 0; i < 16; ++i) {\n t[i] = n[i];\n }\n car25519(t);\n car25519(t);\n car25519(t);\n for(j = 0; j < 2; ++j) {\n m[0] = t[0] - 0xffed;\n for(i = 1; i < 15; ++i) {\n m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);\n m[i-1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);\n b = (m[15] >> 16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1 - b);\n }\n for (i = 0; i < 16; i++) {\n o[2 * i] = t[i] & 0xff;\n o[2 * i + 1] = t[i] >> 8;\n }\n}\n\nfunction unpackneg(r, p) {\n var t = gf(), chk = gf(), num = gf(),\n den = gf(), den2 = gf(), den4 = gf(),\n den6 = gf();\n\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n S(num, r[1]);\n M(den, num, D);\n Z(num, num, r[2]);\n A(den, r[2], den);\n\n S(den2, den);\n S(den4, den2);\n M(den6, den4, den2);\n M(t, den6, num);\n M(t, t, den);\n\n pow2523(t, t);\n M(t, t, num);\n M(t, t, den);\n M(t, t, den);\n M(r[0], t, den);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if(neq25519(chk, num)) {\n M(r[0], r[0], I);\n }\n\n S(chk, r[0]);\n M(chk, chk, den);\n if(neq25519(chk, num)) {\n return -1;\n }\n\n if(par25519(r[0]) === (p[31] >> 7)) {\n Z(r[0], gf0, r[0]);\n }\n\n M(r[3], r[0], r[1]);\n return 0;\n}\n\nfunction unpack25519(o, n) {\n var i;\n for(i = 0; i < 16; ++i) {\n o[i] = n[2 * i] + (n[2 * i + 1] << 8);\n }\n o[15] &= 0x7fff;\n}\n\nfunction pow2523(o, i) {\n var c = gf();\n var a;\n for(a = 0; a < 16; ++a) {\n c[a] = i[a];\n }\n for(a = 250; a >= 0; --a) {\n S(c, c);\n if(a !== 1) {\n M(c, c, i);\n }\n }\n for(a = 0; a < 16; ++a) {\n o[a] = c[a];\n }\n}\n\nfunction neq25519(a, b) {\n var c = new NativeBuffer(32);\n var d = new NativeBuffer(32);\n pack25519(c, a);\n pack25519(d, b);\n return crypto_verify_32(c, 0, d, 0);\n}\n\nfunction crypto_verify_32(x, xi, y, yi) {\n return vn(x, xi, y, yi, 32);\n}\n\nfunction vn(x, xi, y, yi, n) {\n var i, d = 0;\n for(i = 0; i < n; ++i) {\n d |= x[xi + i] ^ y[yi + i];\n }\n return (1 & ((d - 1) >>> 8)) - 1;\n}\n\nfunction par25519(a) {\n var d = new NativeBuffer(32);\n pack25519(d, a);\n return d[0] & 1;\n}\n\nfunction scalarmult(p, q, s) {\n var b, i;\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for(i = 255; i >= 0; --i) {\n b = (s[(i / 8)|0] >> (i & 7)) & 1;\n cswap(p, q, b);\n add(q, p);\n add(p, p);\n cswap(p, q, b);\n }\n}\n\nfunction scalarbase(p, s) {\n var q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n M(q[3], X, Y);\n scalarmult(p, q, s);\n}\n\nfunction set25519(r, a) {\n var i;\n for(i = 0; i < 16; i++) {\n r[i] = a[i] | 0;\n }\n}\n\nfunction inv25519(o, i) {\n var c = gf();\n var a;\n for(a = 0; a < 16; ++a) {\n c[a] = i[a];\n }\n for(a = 253; a >= 0; --a) {\n S(c, c);\n if(a !== 2 && a !== 4) {\n M(c, c, i);\n }\n }\n for(a = 0; a < 16; ++a) {\n o[a] = c[a];\n }\n}\n\nfunction car25519(o) {\n var i, v, c = 1;\n for(i = 0; i < 16; ++i) {\n v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c - 1 + 37 * (c - 1);\n}\n\nfunction sel25519(p, q, b) {\n var t, c = ~(b - 1);\n for(var i = 0; i < 16; ++i) {\n t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction gf(init) {\n var i, r = new Float64Array(16);\n if(init) {\n for(i = 0; i < init.length; ++i) {\n r[i] = init[i];\n }\n }\n return r;\n}\n\nfunction A(o, a, b) {\n for(var i = 0; i < 16; ++i) {\n o[i] = a[i] + b[i];\n }\n}\n\nfunction Z(o, a, b) {\n for(var i = 0; i < 16; ++i) {\n o[i] = a[i] - b[i];\n }\n}\n\nfunction S(o, a) {\n M(o, a, a);\n}\n\nfunction M(o, a, b) {\n var v, c,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n o[ 0] = t0;\n o[ 1] = t1;\n o[ 2] = t2;\n o[ 3] = t3;\n o[ 4] = t4;\n o[ 5] = t5;\n o[ 6] = t6;\n o[ 7] = t7;\n o[ 8] = t8;\n o[ 9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n","/**\n * Javascript implementation of RSA-KEM.\n *\n * @author Lautaro Cozzani Rodriguez\n * @author Dave Longley\n *\n * Copyright (c) 2014 Lautaro Cozzani <lautaro.cozzani@scytl.com>\n * Copyright (c) 2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./random');\nrequire('./jsbn');\n\nmodule.exports = forge.kem = forge.kem || {};\n\nvar BigInteger = forge.jsbn.BigInteger;\n\n/**\n * The API for the RSA Key Encapsulation Mechanism (RSA-KEM) from ISO 18033-2.\n */\nforge.kem.rsa = {};\n\n/**\n * Creates an RSA KEM API object for generating a secret asymmetric key.\n *\n * The symmetric key may be generated via a call to 'encrypt', which will\n * produce a ciphertext to be transmitted to the recipient and a key to be\n * kept secret. The ciphertext is a parameter to be passed to 'decrypt' which\n * will produce the same secret key for the recipient to use to decrypt a\n * message that was encrypted with the secret key.\n *\n * @param kdf the KDF API to use (eg: new forge.kem.kdf1()).\n * @param options the options to use.\n * [prng] a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\".\n */\nforge.kem.rsa.create = function(kdf, options) {\n options = options || {};\n var prng = options.prng || forge.random;\n\n var kem = {};\n\n /**\n * Generates a secret key and its encapsulation.\n *\n * @param publicKey the RSA public key to encrypt with.\n * @param keyLength the length, in bytes, of the secret key to generate.\n *\n * @return an object with:\n * encapsulation: the ciphertext for generating the secret key, as a\n * binary-encoded string of bytes.\n * key: the secret key to use for encrypting a message.\n */\n kem.encrypt = function(publicKey, keyLength) {\n // generate a random r where 1 < r < n\n var byteLength = Math.ceil(publicKey.n.bitLength() / 8);\n var r;\n do {\n r = new BigInteger(\n forge.util.bytesToHex(prng.getBytesSync(byteLength)),\n 16).mod(publicKey.n);\n } while(r.compareTo(BigInteger.ONE) <= 0);\n\n // prepend r with zeros\n r = forge.util.hexToBytes(r.toString(16));\n var zeros = byteLength - r.length;\n if(zeros > 0) {\n r = forge.util.fillString(String.fromCharCode(0), zeros) + r;\n }\n\n // encrypt the random\n var encapsulation = publicKey.encrypt(r, 'NONE');\n\n // generate the secret key\n var key = kdf.generate(r, keyLength);\n\n return {encapsulation: encapsulation, key: key};\n };\n\n /**\n * Decrypts an encapsulated secret key.\n *\n * @param privateKey the RSA private key to decrypt with.\n * @param encapsulation the ciphertext for generating the secret key, as\n * a binary-encoded string of bytes.\n * @param keyLength the length, in bytes, of the secret key to generate.\n *\n * @return the secret key as a binary-encoded string of bytes.\n */\n kem.decrypt = function(privateKey, encapsulation, keyLength) {\n // decrypt the encapsulation and generate the secret key\n var r = privateKey.decrypt(encapsulation, 'NONE');\n return kdf.generate(r, keyLength);\n };\n\n return kem;\n};\n\n// TODO: add forge.kem.kdf.create('KDF1', {md: ..., ...}) API?\n\n/**\n * Creates a key derivation API object that implements KDF1 per ISO 18033-2.\n *\n * @param md the hash API to use.\n * @param [digestLength] an optional digest length that must be positive and\n * less than or equal to md.digestLength.\n *\n * @return a KDF1 API object.\n */\nforge.kem.kdf1 = function(md, digestLength) {\n _createKDF(this, md, 0, digestLength || md.digestLength);\n};\n\n/**\n * Creates a key derivation API object that implements KDF2 per ISO 18033-2.\n *\n * @param md the hash API to use.\n * @param [digestLength] an optional digest length that must be positive and\n * less than or equal to md.digestLength.\n *\n * @return a KDF2 API object.\n */\nforge.kem.kdf2 = function(md, digestLength) {\n _createKDF(this, md, 1, digestLength || md.digestLength);\n};\n\n/**\n * Creates a KDF1 or KDF2 API object.\n *\n * @param md the hash API to use.\n * @param counterStart the starting index for the counter.\n * @param digestLength the digest length to use.\n *\n * @return the KDF API object.\n */\nfunction _createKDF(kdf, md, counterStart, digestLength) {\n /**\n * Generate a key of the specified length.\n *\n * @param x the binary-encoded byte string to generate a key from.\n * @param length the number of bytes to generate (the size of the key).\n *\n * @return the key as a binary-encoded string.\n */\n kdf.generate = function(x, length) {\n var key = new forge.util.ByteBuffer();\n\n // run counter from counterStart to ceil(length / Hash.len)\n var k = Math.ceil(length / digestLength) + counterStart;\n\n var c = new forge.util.ByteBuffer();\n for(var i = counterStart; i < k; ++i) {\n // I2OSP(i, 4): convert counter to an octet string of 4 octets\n c.putInt32(i);\n\n // digest 'x' and the counter and add the result to the key\n md.start();\n md.update(x + c.getBytes());\n var hash = md.digest();\n key.putBytes(hash.getBytes(digestLength));\n }\n\n // truncate to the correct key length\n key.truncate(key.length() - length);\n return key.getBytes();\n };\n}\n","/**\n * Cross-browser support for logging in a web application.\n *\n * @author David I. Lehn <dlehn@digitalbazaar.com>\n *\n * Copyright (c) 2008-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\n/* LOG API */\nmodule.exports = forge.log = forge.log || {};\n\n/**\n * Application logging system.\n *\n * Each logger level available as it's own function of the form:\n * forge.log.level(category, args...)\n * The category is an arbitrary string, and the args are the same as\n * Firebug's console.log API. By default the call will be output as:\n * 'LEVEL [category] <args[0]>, args[1], ...'\n * This enables proper % formatting via the first argument.\n * Each category is enabled by default but can be enabled or disabled with\n * the setCategoryEnabled() function.\n */\n// list of known levels\nforge.log.levels = [\n 'none', 'error', 'warning', 'info', 'debug', 'verbose', 'max'];\n// info on the levels indexed by name:\n// index: level index\n// name: uppercased display name\nvar sLevelInfo = {};\n// list of loggers\nvar sLoggers = [];\n/**\n * Standard console logger. If no console support is enabled this will\n * remain null. Check before using.\n */\nvar sConsoleLogger = null;\n\n// logger flags\n/**\n * Lock the level at the current value. Used in cases where user config may\n * set the level such that only critical messages are seen but more verbose\n * messages are needed for debugging or other purposes.\n */\nforge.log.LEVEL_LOCKED = (1 << 1);\n/**\n * Always call log function. By default, the logging system will check the\n * message level against logger.level before calling the log function. This\n * flag allows the function to do its own check.\n */\nforge.log.NO_LEVEL_CHECK = (1 << 2);\n/**\n * Perform message interpolation with the passed arguments. \"%\" style\n * fields in log messages will be replaced by arguments as needed. Some\n * loggers, such as Firebug, may do this automatically. The original log\n * message will be available as 'message' and the interpolated version will\n * be available as 'fullMessage'.\n */\nforge.log.INTERPOLATE = (1 << 3);\n\n// setup each log level\nfor(var i = 0; i < forge.log.levels.length; ++i) {\n var level = forge.log.levels[i];\n sLevelInfo[level] = {\n index: i,\n name: level.toUpperCase()\n };\n}\n\n/**\n * Message logger. Will dispatch a message to registered loggers as needed.\n *\n * @param message message object\n */\nforge.log.logMessage = function(message) {\n var messageLevelIndex = sLevelInfo[message.level].index;\n for(var i = 0; i < sLoggers.length; ++i) {\n var logger = sLoggers[i];\n if(logger.flags & forge.log.NO_LEVEL_CHECK) {\n logger.f(message);\n } else {\n // get logger level\n var loggerLevelIndex = sLevelInfo[logger.level].index;\n // check level\n if(messageLevelIndex <= loggerLevelIndex) {\n // message critical enough, call logger\n logger.f(logger, message);\n }\n }\n }\n};\n\n/**\n * Sets the 'standard' key on a message object to:\n * \"LEVEL [category] \" + message\n *\n * @param message a message log object\n */\nforge.log.prepareStandard = function(message) {\n if(!('standard' in message)) {\n message.standard =\n sLevelInfo[message.level].name +\n //' ' + +message.timestamp +\n ' [' + message.category + '] ' +\n message.message;\n }\n};\n\n/**\n * Sets the 'full' key on a message object to the original message\n * interpolated via % formatting with the message arguments.\n *\n * @param message a message log object.\n */\nforge.log.prepareFull = function(message) {\n if(!('full' in message)) {\n // copy args and insert message at the front\n var args = [message.message];\n args = args.concat([] || message['arguments']);\n // format the message\n message.full = forge.util.format.apply(this, args);\n }\n};\n\n/**\n * Applies both preparseStandard() and prepareFull() to a message object and\n * store result in 'standardFull'.\n *\n * @param message a message log object.\n */\nforge.log.prepareStandardFull = function(message) {\n if(!('standardFull' in message)) {\n // FIXME implement 'standardFull' logging\n forge.log.prepareStandard(message);\n message.standardFull = message.standard;\n }\n};\n\n// create log level functions\nif(true) {\n // levels for which we want functions\n var levels = ['error', 'warning', 'info', 'debug', 'verbose'];\n for(var i = 0; i < levels.length; ++i) {\n // wrap in a function to ensure proper level var is passed\n (function(level) {\n // create function for this level\n forge.log[level] = function(category, message/*, args...*/) {\n // convert arguments to real array, remove category and message\n var args = Array.prototype.slice.call(arguments).slice(2);\n // create message object\n // Note: interpolation and standard formatting is done lazily\n var msg = {\n timestamp: new Date(),\n level: level,\n category: category,\n message: message,\n 'arguments': args\n /*standard*/\n /*full*/\n /*fullMessage*/\n };\n // process this message\n forge.log.logMessage(msg);\n };\n })(levels[i]);\n }\n}\n\n/**\n * Creates a new logger with specified custom logging function.\n *\n * The logging function has a signature of:\n * function(logger, message)\n * logger: current logger\n * message: object:\n * level: level id\n * category: category\n * message: string message\n * arguments: Array of extra arguments\n * fullMessage: interpolated message and arguments if INTERPOLATE flag set\n *\n * @param logFunction a logging function which takes a log message object\n * as a parameter.\n *\n * @return a logger object.\n */\nforge.log.makeLogger = function(logFunction) {\n var logger = {\n flags: 0,\n f: logFunction\n };\n forge.log.setLevel(logger, 'none');\n return logger;\n};\n\n/**\n * Sets the current log level on a logger.\n *\n * @param logger the target logger.\n * @param level the new maximum log level as a string.\n *\n * @return true if set, false if not.\n */\nforge.log.setLevel = function(logger, level) {\n var rval = false;\n if(logger && !(logger.flags & forge.log.LEVEL_LOCKED)) {\n for(var i = 0; i < forge.log.levels.length; ++i) {\n var aValidLevel = forge.log.levels[i];\n if(level == aValidLevel) {\n // set level\n logger.level = level;\n rval = true;\n break;\n }\n }\n }\n\n return rval;\n};\n\n/**\n * Locks the log level at its current value.\n *\n * @param logger the target logger.\n * @param lock boolean lock value, default to true.\n */\nforge.log.lock = function(logger, lock) {\n if(typeof lock === 'undefined' || lock) {\n logger.flags |= forge.log.LEVEL_LOCKED;\n } else {\n logger.flags &= ~forge.log.LEVEL_LOCKED;\n }\n};\n\n/**\n * Adds a logger.\n *\n * @param logger the logger object.\n */\nforge.log.addLogger = function(logger) {\n sLoggers.push(logger);\n};\n\n// setup the console logger if possible, else create fake console.log\nif(typeof(console) !== 'undefined' && 'log' in console) {\n var logger;\n if(console.error && console.warn && console.info && console.debug) {\n // looks like Firebug-style logging is available\n // level handlers map\n var levelHandlers = {\n error: console.error,\n warning: console.warn,\n info: console.info,\n debug: console.debug,\n verbose: console.debug\n };\n var f = function(logger, message) {\n forge.log.prepareStandard(message);\n var handler = levelHandlers[message.level];\n // prepend standard message and concat args\n var args = [message.standard];\n args = args.concat(message['arguments'].slice());\n // apply to low-level console function\n handler.apply(console, args);\n };\n logger = forge.log.makeLogger(f);\n } else {\n // only appear to have basic console.log\n var f = function(logger, message) {\n forge.log.prepareStandardFull(message);\n console.log(message.standardFull);\n };\n logger = forge.log.makeLogger(f);\n }\n forge.log.setLevel(logger, 'debug');\n forge.log.addLogger(logger);\n sConsoleLogger = logger;\n} else {\n // define fake console.log to avoid potential script errors on\n // browsers that do not have console logging\n console = {\n log: function() {}\n };\n}\n\n/*\n * Check for logging control query vars in current URL.\n *\n * console.level=<level-name>\n * Set's the console log level by name. Useful to override defaults and\n * allow more verbose logging before a user config is loaded.\n *\n * console.lock=<true|false>\n * Lock the console log level at whatever level it is set at. This is run\n * after console.level is processed. Useful to force a level of verbosity\n * that could otherwise be limited by a user config.\n */\nif(sConsoleLogger !== null &&\n typeof window !== 'undefined' && window.location\n) {\n var query = new URL(window.location.href).searchParams;\n if(query.has('console.level')) {\n // set with last value\n forge.log.setLevel(\n sConsoleLogger, query.get('console.level').slice(-1)[0]);\n }\n if(query.has('console.lock')) {\n // set with last value\n var lock = query.get('console.lock').slice(-1)[0];\n if(lock == 'true') {\n forge.log.lock(sConsoleLogger);\n }\n }\n}\n\n// provide public access to console logger\nforge.log.consoleLogger = sConsoleLogger;\n","/**\n * Node.js module for all known Forge message digests.\n *\n * @author Dave Longley\n *\n * Copyright 2011-2017 Digital Bazaar, Inc.\n */\nmodule.exports = require('./md');\n\nrequire('./md5');\nrequire('./sha1');\nrequire('./sha256');\nrequire('./sha512');\n","/**\n * Javascript implementation of PKCS#7 v1.5.\n *\n * @author Stefan Siegl\n * @author Dave Longley\n *\n * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>\n * Copyright (c) 2012-2015 Digital Bazaar, Inc.\n *\n * Currently this implementation only supports ContentType of EnvelopedData,\n * EncryptedData, or SignedData at the root level. The top level elements may\n * contain only a ContentInfo of ContentType Data, i.e. plain data. Further\n * nesting is not (yet) supported.\n *\n * The Forge validators for PKCS #7's ASN.1 structures are available from\n * a separate file pkcs7asn1.js, since those are referenced from other\n * PKCS standards like PKCS #12.\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./asn1');\nrequire('./des');\nrequire('./oids');\nrequire('./pem');\nrequire('./pkcs7asn1');\nrequire('./random');\nrequire('./util');\nrequire('./x509');\n\n// shortcut for ASN.1 API\nvar asn1 = forge.asn1;\n\n// shortcut for PKCS#7 API\nvar p7 = module.exports = forge.pkcs7 = forge.pkcs7 || {};\n\n/**\n * Converts a PKCS#7 message from PEM format.\n *\n * @param pem the PEM-formatted PKCS#7 message.\n *\n * @return the PKCS#7 message.\n */\np7.messageFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'PKCS7') {\n var error = new Error('Could not convert PKCS#7 message from PEM; PEM ' +\n 'header type is not \"PKCS#7\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert PKCS#7 message from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body);\n\n return p7.messageFromAsn1(obj);\n};\n\n/**\n * Converts a PKCS#7 message to PEM format.\n *\n * @param msg The PKCS#7 message object\n * @param maxline The maximum characters per line, defaults to 64.\n *\n * @return The PEM-formatted PKCS#7 message.\n */\np7.messageToPem = function(msg, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var pemObj = {\n type: 'PKCS7',\n body: asn1.toDer(msg.toAsn1()).getBytes()\n };\n return forge.pem.encode(pemObj, {maxline: maxline});\n};\n\n/**\n * Converts a PKCS#7 message from an ASN.1 object.\n *\n * @param obj the ASN.1 representation of a ContentInfo.\n *\n * @return the PKCS#7 message.\n */\np7.messageFromAsn1 = function(obj) {\n // validate root level ContentInfo and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 message. ' +\n 'ASN.1 object is not an PKCS#7 ContentInfo.');\n error.errors = errors;\n throw error;\n }\n\n var contentType = asn1.derToOid(capture.contentType);\n var msg;\n\n switch(contentType) {\n case forge.pki.oids.envelopedData:\n msg = p7.createEnvelopedData();\n break;\n\n case forge.pki.oids.encryptedData:\n msg = p7.createEncryptedData();\n break;\n\n case forge.pki.oids.signedData:\n msg = p7.createSignedData();\n break;\n\n default:\n throw new Error('Cannot read PKCS#7 message. ContentType with OID ' +\n contentType + ' is not (yet) supported.');\n }\n\n msg.fromAsn1(capture.content.value[0]);\n return msg;\n};\n\np7.createSignedData = function() {\n var msg = null;\n msg = {\n type: forge.pki.oids.signedData,\n version: 1,\n certificates: [],\n crls: [],\n // TODO: add json-formatted signer stuff here?\n signers: [],\n // populated during sign()\n digestAlgorithmIdentifiers: [],\n contentInfo: null,\n signerInfos: [],\n\n fromAsn1: function(obj) {\n // validate SignedData content block and capture data.\n _fromAsn1(msg, obj, p7.asn1.signedDataValidator);\n msg.certificates = [];\n msg.crls = [];\n msg.digestAlgorithmIdentifiers = [];\n msg.contentInfo = null;\n msg.signerInfos = [];\n\n if(msg.rawCapture.certificates) {\n var certs = msg.rawCapture.certificates.value;\n for(var i = 0; i < certs.length; ++i) {\n msg.certificates.push(forge.pki.certificateFromAsn1(certs[i]));\n }\n }\n\n // TODO: parse crls\n },\n\n toAsn1: function() {\n // degenerate case with no content\n if(!msg.contentInfo) {\n msg.sign();\n }\n\n var certs = [];\n for(var i = 0; i < msg.certificates.length; ++i) {\n certs.push(forge.pki.certificateToAsn1(msg.certificates[i]));\n }\n\n var crls = [];\n // TODO: implement CRLs\n\n // [0] SignedData\n var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(msg.version).getBytes()),\n // DigestAlgorithmIdentifiers\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SET, true,\n msg.digestAlgorithmIdentifiers),\n // ContentInfo\n msg.contentInfo\n ])\n ]);\n if(certs.length > 0) {\n // [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL\n signedData.value[0].value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs));\n }\n if(crls.length > 0) {\n // [1] IMPLICIT CertificateRevocationLists OPTIONAL\n signedData.value[0].value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls));\n }\n // SignerInfos\n signedData.value[0].value.push(\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,\n msg.signerInfos));\n\n // ContentInfo\n return asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // ContentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(msg.type).getBytes()),\n // [0] SignedData\n signedData\n ]);\n },\n\n /**\n * Add (another) entity to list of signers.\n *\n * Note: If authenticatedAttributes are provided, then, per RFC 2315,\n * they must include at least two attributes: content type and\n * message digest. The message digest attribute value will be\n * auto-calculated during signing and will be ignored if provided.\n *\n * Here's an example of providing these two attributes:\n *\n * forge.pkcs7.createSignedData();\n * p7.addSigner({\n * issuer: cert.issuer.attributes,\n * serialNumber: cert.serialNumber,\n * key: privateKey,\n * digestAlgorithm: forge.pki.oids.sha1,\n * authenticatedAttributes: [{\n * type: forge.pki.oids.contentType,\n * value: forge.pki.oids.data\n * }, {\n * type: forge.pki.oids.messageDigest\n * }]\n * });\n *\n * TODO: Support [subjectKeyIdentifier] as signer's ID.\n *\n * @param signer the signer information:\n * key the signer's private key.\n * [certificate] a certificate containing the public key\n * associated with the signer's private key; use this option as\n * an alternative to specifying signer.issuer and\n * signer.serialNumber.\n * [issuer] the issuer attributes (eg: cert.issuer.attributes).\n * [serialNumber] the signer's certificate's serial number in\n * hexadecimal (eg: cert.serialNumber).\n * [digestAlgorithm] the message digest OID, as a string, to use\n * (eg: forge.pki.oids.sha1).\n * [authenticatedAttributes] an optional array of attributes\n * to also sign along with the content.\n */\n addSigner: function(signer) {\n var issuer = signer.issuer;\n var serialNumber = signer.serialNumber;\n if(signer.certificate) {\n var cert = signer.certificate;\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n issuer = cert.issuer.attributes;\n serialNumber = cert.serialNumber;\n }\n var key = signer.key;\n if(!key) {\n throw new Error(\n 'Could not add PKCS#7 signer; no private key specified.');\n }\n if(typeof key === 'string') {\n key = forge.pki.privateKeyFromPem(key);\n }\n\n // ensure OID known for digest algorithm\n var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1;\n switch(digestAlgorithm) {\n case forge.pki.oids.sha1:\n case forge.pki.oids.sha256:\n case forge.pki.oids.sha384:\n case forge.pki.oids.sha512:\n case forge.pki.oids.md5:\n break;\n default:\n throw new Error(\n 'Could not add PKCS#7 signer; unknown message digest algorithm: ' +\n digestAlgorithm);\n }\n\n // if authenticatedAttributes is present, then the attributes\n // must contain at least PKCS #9 content-type and message-digest\n var authenticatedAttributes = signer.authenticatedAttributes || [];\n if(authenticatedAttributes.length > 0) {\n var contentType = false;\n var messageDigest = false;\n for(var i = 0; i < authenticatedAttributes.length; ++i) {\n var attr = authenticatedAttributes[i];\n if(!contentType && attr.type === forge.pki.oids.contentType) {\n contentType = true;\n if(messageDigest) {\n break;\n }\n continue;\n }\n if(!messageDigest && attr.type === forge.pki.oids.messageDigest) {\n messageDigest = true;\n if(contentType) {\n break;\n }\n continue;\n }\n }\n\n if(!contentType || !messageDigest) {\n throw new Error('Invalid signer.authenticatedAttributes. If ' +\n 'signer.authenticatedAttributes is specified, then it must ' +\n 'contain at least two attributes, PKCS #9 content-type and ' +\n 'PKCS #9 message-digest.');\n }\n }\n\n msg.signers.push({\n key: key,\n version: 1,\n issuer: issuer,\n serialNumber: serialNumber,\n digestAlgorithm: digestAlgorithm,\n signatureAlgorithm: forge.pki.oids.rsaEncryption,\n signature: null,\n authenticatedAttributes: authenticatedAttributes,\n unauthenticatedAttributes: []\n });\n },\n\n /**\n * Signs the content.\n * @param options Options to apply when signing:\n * [detached] boolean. If signing should be done in detached mode. Defaults to false.\n */\n sign: function(options) {\n options = options || {};\n // auto-generate content info\n if(typeof msg.content !== 'object' || msg.contentInfo === null) {\n // use Data ContentInfo\n msg.contentInfo = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // ContentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(forge.pki.oids.data).getBytes())\n ]);\n\n // add actual content, if present\n if('content' in msg) {\n var content;\n if(msg.content instanceof forge.util.ByteBuffer) {\n content = msg.content.bytes();\n } else if(typeof msg.content === 'string') {\n content = forge.util.encodeUtf8(msg.content);\n }\n\n if (options.detached) {\n msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content);\n } else {\n msg.contentInfo.value.push(\n // [0] EXPLICIT content\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n content)\n ]));\n }\n }\n }\n\n // no signers, return early (degenerate case for certificate container)\n if(msg.signers.length === 0) {\n return;\n }\n\n // generate digest algorithm identifiers\n var mds = addDigestAlgorithmIds();\n\n // generate signerInfos\n addSignerInfos(mds);\n },\n\n verify: function() {\n throw new Error('PKCS#7 signature verification not yet implemented.');\n },\n\n /**\n * Add a certificate.\n *\n * @param cert the certificate to add.\n */\n addCertificate: function(cert) {\n // convert from PEM\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n msg.certificates.push(cert);\n },\n\n /**\n * Add a certificate revokation list.\n *\n * @param crl the certificate revokation list to add.\n */\n addCertificateRevokationList: function(crl) {\n throw new Error('PKCS#7 CRL support not yet implemented.');\n }\n };\n return msg;\n\n function addDigestAlgorithmIds() {\n var mds = {};\n\n for(var i = 0; i < msg.signers.length; ++i) {\n var signer = msg.signers[i];\n var oid = signer.digestAlgorithm;\n if(!(oid in mds)) {\n // content digest\n mds[oid] = forge.md[forge.pki.oids[oid]].create();\n }\n if(signer.authenticatedAttributes.length === 0) {\n // no custom attributes to digest; use content message digest\n signer.md = mds[oid];\n } else {\n // custom attributes to be digested; use own message digest\n // TODO: optimize to just copy message digest state if that\n // feature is ever supported with message digests\n signer.md = forge.md[forge.pki.oids[oid]].create();\n }\n }\n\n // add unique digest algorithm identifiers\n msg.digestAlgorithmIdentifiers = [];\n for(var oid in mds) {\n msg.digestAlgorithmIdentifiers.push(\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oid).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]));\n }\n\n return mds;\n }\n\n function addSignerInfos(mds) {\n var content;\n\n if (msg.detachedContent) {\n // Signature has been made in detached mode.\n content = msg.detachedContent;\n } else {\n // Note: ContentInfo is a SEQUENCE with 2 values, second value is\n // the content field and is optional for a ContentInfo but required here\n // since signers are present\n // get ContentInfo content\n content = msg.contentInfo.value[1];\n // skip [0] EXPLICIT content wrapper\n content = content.value[0];\n }\n\n if(!content) {\n throw new Error(\n 'Could not sign PKCS#7 message; there is no content to sign.');\n }\n\n // get ContentInfo content type\n var contentType = asn1.derToOid(msg.contentInfo.value[0].value);\n\n // serialize content\n var bytes = asn1.toDer(content);\n\n // skip identifier and length per RFC 2315 9.3\n // skip identifier (1 byte)\n bytes.getByte();\n // read and discard length bytes\n asn1.getBerValueLength(bytes);\n bytes = bytes.getBytes();\n\n // digest content DER value bytes\n for(var oid in mds) {\n mds[oid].start().update(bytes);\n }\n\n // sign content\n var signingTime = new Date();\n for(var i = 0; i < msg.signers.length; ++i) {\n var signer = msg.signers[i];\n\n if(signer.authenticatedAttributes.length === 0) {\n // if ContentInfo content type is not \"Data\", then\n // authenticatedAttributes must be present per RFC 2315\n if(contentType !== forge.pki.oids.data) {\n throw new Error(\n 'Invalid signer; authenticatedAttributes must be present ' +\n 'when the ContentInfo content type is not PKCS#7 Data.');\n }\n } else {\n // process authenticated attributes\n // [0] IMPLICIT\n signer.authenticatedAttributesAsn1 = asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n\n // per RFC 2315, attributes are to be digested using a SET container\n // not the above [0] IMPLICIT container\n var attrsAsn1 = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SET, true, []);\n\n for(var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) {\n var attr = signer.authenticatedAttributes[ai];\n if(attr.type === forge.pki.oids.messageDigest) {\n // use content message digest as value\n attr.value = mds[signer.digestAlgorithm].digest();\n } else if(attr.type === forge.pki.oids.signingTime) {\n // auto-populate signing time if not already set\n if(!attr.value) {\n attr.value = signingTime;\n }\n }\n\n // convert to ASN.1 and push onto Attributes SET (for signing) and\n // onto authenticatedAttributesAsn1 to complete SignedData ASN.1\n // TODO: optimize away duplication\n attrsAsn1.value.push(_attributeToAsn1(attr));\n signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr));\n }\n\n // DER-serialize and digest SET OF attributes only\n bytes = asn1.toDer(attrsAsn1).getBytes();\n signer.md.start().update(bytes);\n }\n\n // sign digest\n signer.signature = signer.key.sign(signer.md, 'RSASSA-PKCS1-V1_5');\n }\n\n // add signer info\n msg.signerInfos = _signersToAsn1(msg.signers);\n }\n};\n\n/**\n * Creates an empty PKCS#7 message of type EncryptedData.\n *\n * @return the message.\n */\np7.createEncryptedData = function() {\n var msg = null;\n msg = {\n type: forge.pki.oids.encryptedData,\n version: 0,\n encryptedContent: {\n algorithm: forge.pki.oids['aes256-CBC']\n },\n\n /**\n * Reads an EncryptedData content block (in ASN.1 format)\n *\n * @param obj The ASN.1 representation of the EncryptedData content block\n */\n fromAsn1: function(obj) {\n // Validate EncryptedData content block and capture data.\n _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator);\n },\n\n /**\n * Decrypt encrypted content\n *\n * @param key The (symmetric) key as a byte buffer\n */\n decrypt: function(key) {\n if(key !== undefined) {\n msg.encryptedContent.key = key;\n }\n _decryptContent(msg);\n }\n };\n return msg;\n};\n\n/**\n * Creates an empty PKCS#7 message of type EnvelopedData.\n *\n * @return the message.\n */\np7.createEnvelopedData = function() {\n var msg = null;\n msg = {\n type: forge.pki.oids.envelopedData,\n version: 0,\n recipients: [],\n encryptedContent: {\n algorithm: forge.pki.oids['aes256-CBC']\n },\n\n /**\n * Reads an EnvelopedData content block (in ASN.1 format)\n *\n * @param obj the ASN.1 representation of the EnvelopedData content block.\n */\n fromAsn1: function(obj) {\n // validate EnvelopedData content block and capture data\n var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator);\n msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value);\n },\n\n toAsn1: function() {\n // ContentInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // ContentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(msg.type).getBytes()),\n // [0] EnvelopedData\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(msg.version).getBytes()),\n // RecipientInfos\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,\n _recipientsToAsn1(msg.recipients)),\n // EncryptedContentInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true,\n _encryptedContentToAsn1(msg.encryptedContent))\n ])\n ])\n ]);\n },\n\n /**\n * Find recipient by X.509 certificate's issuer.\n *\n * @param cert the certificate with the issuer to look for.\n *\n * @return the recipient object.\n */\n findRecipient: function(cert) {\n var sAttr = cert.issuer.attributes;\n\n for(var i = 0; i < msg.recipients.length; ++i) {\n var r = msg.recipients[i];\n var rAttr = r.issuer;\n\n if(r.serialNumber !== cert.serialNumber) {\n continue;\n }\n\n if(rAttr.length !== sAttr.length) {\n continue;\n }\n\n var match = true;\n for(var j = 0; j < sAttr.length; ++j) {\n if(rAttr[j].type !== sAttr[j].type ||\n rAttr[j].value !== sAttr[j].value) {\n match = false;\n break;\n }\n }\n\n if(match) {\n return r;\n }\n }\n\n return null;\n },\n\n /**\n * Decrypt enveloped content\n *\n * @param recipient The recipient object related to the private key\n * @param privKey The (RSA) private key object\n */\n decrypt: function(recipient, privKey) {\n if(msg.encryptedContent.key === undefined && recipient !== undefined &&\n privKey !== undefined) {\n switch(recipient.encryptedContent.algorithm) {\n case forge.pki.oids.rsaEncryption:\n case forge.pki.oids.desCBC:\n var key = privKey.decrypt(recipient.encryptedContent.content);\n msg.encryptedContent.key = forge.util.createBuffer(key);\n break;\n\n default:\n throw new Error('Unsupported asymmetric cipher, ' +\n 'OID ' + recipient.encryptedContent.algorithm);\n }\n }\n\n _decryptContent(msg);\n },\n\n /**\n * Add (another) entity to list of recipients.\n *\n * @param cert The certificate of the entity to add.\n */\n addRecipient: function(cert) {\n msg.recipients.push({\n version: 0,\n issuer: cert.issuer.attributes,\n serialNumber: cert.serialNumber,\n encryptedContent: {\n // We simply assume rsaEncryption here, since forge.pki only\n // supports RSA so far. If the PKI module supports other\n // ciphers one day, we need to modify this one as well.\n algorithm: forge.pki.oids.rsaEncryption,\n key: cert.publicKey\n }\n });\n },\n\n /**\n * Encrypt enveloped content.\n *\n * This function supports two optional arguments, cipher and key, which\n * can be used to influence symmetric encryption. Unless cipher is\n * provided, the cipher specified in encryptedContent.algorithm is used\n * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key\n * is (re-)used. If that one's not set, a random key will be generated\n * automatically.\n *\n * @param [key] The key to be used for symmetric encryption.\n * @param [cipher] The OID of the symmetric cipher to use.\n */\n encrypt: function(key, cipher) {\n // Part 1: Symmetric encryption\n if(msg.encryptedContent.content === undefined) {\n cipher = cipher || msg.encryptedContent.algorithm;\n key = key || msg.encryptedContent.key;\n\n var keyLen, ivLen, ciphFn;\n switch(cipher) {\n case forge.pki.oids['aes128-CBC']:\n keyLen = 16;\n ivLen = 16;\n ciphFn = forge.aes.createEncryptionCipher;\n break;\n\n case forge.pki.oids['aes192-CBC']:\n keyLen = 24;\n ivLen = 16;\n ciphFn = forge.aes.createEncryptionCipher;\n break;\n\n case forge.pki.oids['aes256-CBC']:\n keyLen = 32;\n ivLen = 16;\n ciphFn = forge.aes.createEncryptionCipher;\n break;\n\n case forge.pki.oids['des-EDE3-CBC']:\n keyLen = 24;\n ivLen = 8;\n ciphFn = forge.des.createEncryptionCipher;\n break;\n\n default:\n throw new Error('Unsupported symmetric cipher, OID ' + cipher);\n }\n\n if(key === undefined) {\n key = forge.util.createBuffer(forge.random.getBytes(keyLen));\n } else if(key.length() != keyLen) {\n throw new Error('Symmetric key has wrong length; ' +\n 'got ' + key.length() + ' bytes, expected ' + keyLen + '.');\n }\n\n // Keep a copy of the key & IV in the object, so the caller can\n // use it for whatever reason.\n msg.encryptedContent.algorithm = cipher;\n msg.encryptedContent.key = key;\n msg.encryptedContent.parameter = forge.util.createBuffer(\n forge.random.getBytes(ivLen));\n\n var ciph = ciphFn(key);\n ciph.start(msg.encryptedContent.parameter.copy());\n ciph.update(msg.content);\n\n // The finish function does PKCS#7 padding by default, therefore\n // no action required by us.\n if(!ciph.finish()) {\n throw new Error('Symmetric encryption failed.');\n }\n\n msg.encryptedContent.content = ciph.output;\n }\n\n // Part 2: asymmetric encryption for each recipient\n for(var i = 0; i < msg.recipients.length; ++i) {\n var recipient = msg.recipients[i];\n\n // Nothing to do, encryption already done.\n if(recipient.encryptedContent.content !== undefined) {\n continue;\n }\n\n switch(recipient.encryptedContent.algorithm) {\n case forge.pki.oids.rsaEncryption:\n recipient.encryptedContent.content =\n recipient.encryptedContent.key.encrypt(\n msg.encryptedContent.key.data);\n break;\n\n default:\n throw new Error('Unsupported asymmetric cipher, OID ' +\n recipient.encryptedContent.algorithm);\n }\n }\n }\n };\n return msg;\n};\n\n/**\n * Converts a single recipient from an ASN.1 object.\n *\n * @param obj the ASN.1 RecipientInfo.\n *\n * @return the recipient object.\n */\nfunction _recipientFromAsn1(obj) {\n // validate EnvelopedData content block and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 RecipientInfo. ' +\n 'ASN.1 object is not an PKCS#7 RecipientInfo.');\n error.errors = errors;\n throw error;\n }\n\n return {\n version: capture.version.charCodeAt(0),\n issuer: forge.pki.RDNAttributesAsArray(capture.issuer),\n serialNumber: forge.util.createBuffer(capture.serial).toHex(),\n encryptedContent: {\n algorithm: asn1.derToOid(capture.encAlgorithm),\n parameter: capture.encParameter ? capture.encParameter.value : undefined,\n content: capture.encKey\n }\n };\n}\n\n/**\n * Converts a single recipient object to an ASN.1 object.\n *\n * @param obj the recipient object.\n *\n * @return the ASN.1 RecipientInfo.\n */\nfunction _recipientToAsn1(obj) {\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(obj.version).getBytes()),\n // IssuerAndSerialNumber\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Name\n forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),\n // Serial\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(obj.serialNumber))\n ]),\n // KeyEncryptionAlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()),\n // Parameter, force NULL, only RSA supported for now.\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // EncryptedKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n obj.encryptedContent.content)\n ]);\n}\n\n/**\n * Map a set of RecipientInfo ASN.1 objects to recipient objects.\n *\n * @param infos an array of ASN.1 representations RecipientInfo (i.e. SET OF).\n *\n * @return an array of recipient objects.\n */\nfunction _recipientsFromAsn1(infos) {\n var ret = [];\n for(var i = 0; i < infos.length; ++i) {\n ret.push(_recipientFromAsn1(infos[i]));\n }\n return ret;\n}\n\n/**\n * Map an array of recipient objects to ASN.1 RecipientInfo objects.\n *\n * @param recipients an array of recipientInfo objects.\n *\n * @return an array of ASN.1 RecipientInfos.\n */\nfunction _recipientsToAsn1(recipients) {\n var ret = [];\n for(var i = 0; i < recipients.length; ++i) {\n ret.push(_recipientToAsn1(recipients[i]));\n }\n return ret;\n}\n\n/**\n * Converts a single signer from an ASN.1 object.\n *\n * @param obj the ASN.1 representation of a SignerInfo.\n *\n * @return the signer object.\n */\nfunction _signerFromAsn1(obj) {\n // validate EnvelopedData content block and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, p7.asn1.signerInfoValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 SignerInfo. ' +\n 'ASN.1 object is not an PKCS#7 SignerInfo.');\n error.errors = errors;\n throw error;\n }\n\n var rval = {\n version: capture.version.charCodeAt(0),\n issuer: forge.pki.RDNAttributesAsArray(capture.issuer),\n serialNumber: forge.util.createBuffer(capture.serial).toHex(),\n digestAlgorithm: asn1.derToOid(capture.digestAlgorithm),\n signatureAlgorithm: asn1.derToOid(capture.signatureAlgorithm),\n signature: capture.signature,\n authenticatedAttributes: [],\n unauthenticatedAttributes: []\n };\n\n // TODO: convert attributes\n var authenticatedAttributes = capture.authenticatedAttributes || [];\n var unauthenticatedAttributes = capture.unauthenticatedAttributes || [];\n\n return rval;\n}\n\n/**\n * Converts a single signerInfo object to an ASN.1 object.\n *\n * @param obj the signerInfo object.\n *\n * @return the ASN.1 representation of a SignerInfo.\n */\nfunction _signerToAsn1(obj) {\n // SignerInfo\n var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(obj.version).getBytes()),\n // issuerAndSerialNumber\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // name\n forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),\n // serial\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(obj.serialNumber))\n ]),\n // digestAlgorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(obj.digestAlgorithm).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ])\n ]);\n\n // authenticatedAttributes (OPTIONAL)\n if(obj.authenticatedAttributesAsn1) {\n // add ASN.1 previously generated during signing\n rval.value.push(obj.authenticatedAttributesAsn1);\n }\n\n // digestEncryptionAlgorithm\n rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(obj.signatureAlgorithm).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]));\n\n // encryptedDigest\n rval.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.signature));\n\n // unauthenticatedAttributes (OPTIONAL)\n if(obj.unauthenticatedAttributes.length > 0) {\n // [1] IMPLICIT\n var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []);\n for(var i = 0; i < obj.unauthenticatedAttributes.length; ++i) {\n var attr = obj.unauthenticatedAttributes[i];\n attrsAsn1.values.push(_attributeToAsn1(attr));\n }\n rval.value.push(attrsAsn1);\n }\n\n return rval;\n}\n\n/**\n * Map a set of SignerInfo ASN.1 objects to an array of signer objects.\n *\n * @param signerInfoAsn1s an array of ASN.1 SignerInfos (i.e. SET OF).\n *\n * @return an array of signers objects.\n */\nfunction _signersFromAsn1(signerInfoAsn1s) {\n var ret = [];\n for(var i = 0; i < signerInfoAsn1s.length; ++i) {\n ret.push(_signerFromAsn1(signerInfoAsn1s[i]));\n }\n return ret;\n}\n\n/**\n * Map an array of signer objects to ASN.1 objects.\n *\n * @param signers an array of signer objects.\n *\n * @return an array of ASN.1 SignerInfos.\n */\nfunction _signersToAsn1(signers) {\n var ret = [];\n for(var i = 0; i < signers.length; ++i) {\n ret.push(_signerToAsn1(signers[i]));\n }\n return ret;\n}\n\n/**\n * Convert an attribute object to an ASN.1 Attribute.\n *\n * @param attr the attribute object.\n *\n * @return the ASN.1 Attribute.\n */\nfunction _attributeToAsn1(attr) {\n var value;\n\n // TODO: generalize to support more attributes\n if(attr.type === forge.pki.oids.contentType) {\n value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.value).getBytes());\n } else if(attr.type === forge.pki.oids.messageDigest) {\n value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n attr.value.bytes());\n } else if(attr.type === forge.pki.oids.signingTime) {\n /* Note per RFC 2985: Dates between 1 January 1950 and 31 December 2049\n (inclusive) MUST be encoded as UTCTime. Any dates with year values\n before 1950 or after 2049 MUST be encoded as GeneralizedTime. [Further,]\n UTCTime values MUST be expressed in Greenwich Mean Time (Zulu) and MUST\n include seconds (i.e., times are YYMMDDHHMMSSZ), even where the\n number of seconds is zero. Midnight (GMT) must be represented as\n \"YYMMDD000000Z\". */\n // TODO: make these module-level constants\n var jan_1_1950 = new Date('1950-01-01T00:00:00Z');\n var jan_1_2050 = new Date('2050-01-01T00:00:00Z');\n var date = attr.value;\n if(typeof date === 'string') {\n // try to parse date\n var timestamp = Date.parse(date);\n if(!isNaN(timestamp)) {\n date = new Date(timestamp);\n } else if(date.length === 13) {\n // YYMMDDHHMMSSZ (13 chars for UTCTime)\n date = asn1.utcTimeToDate(date);\n } else {\n // assume generalized time\n date = asn1.generalizedTimeToDate(date);\n }\n }\n\n if(date >= jan_1_1950 && date < jan_1_2050) {\n value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false,\n asn1.dateToUtcTime(date));\n } else {\n value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false,\n asn1.dateToGeneralizedTime(date));\n }\n }\n\n // TODO: expose as common API call\n // create a RelativeDistinguishedName set\n // each value in the set is an AttributeTypeAndValue first\n // containing the type (an OID) and second the value\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AttributeType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.type).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n // AttributeValue\n value\n ])\n ]);\n}\n\n/**\n * Map messages encrypted content to ASN.1 objects.\n *\n * @param ec The encryptedContent object of the message.\n *\n * @return ASN.1 representation of the encryptedContent object (SEQUENCE).\n */\nfunction _encryptedContentToAsn1(ec) {\n return [\n // ContentType, always Data for the moment\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(forge.pki.oids.data).getBytes()),\n // ContentEncryptionAlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(ec.algorithm).getBytes()),\n // Parameters (IV)\n !ec.parameter ?\n undefined :\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n ec.parameter.getBytes())\n ]),\n // [0] EncryptedContent\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n ec.content.getBytes())\n ])\n ];\n}\n\n/**\n * Reads the \"common part\" of an PKCS#7 content block (in ASN.1 format)\n *\n * This function reads the \"common part\" of the PKCS#7 content blocks\n * EncryptedData and EnvelopedData, i.e. version number and symmetrically\n * encrypted content block.\n *\n * The result of the ASN.1 validate and capture process is returned\n * to allow the caller to extract further data, e.g. the list of recipients\n * in case of a EnvelopedData object.\n *\n * @param msg the PKCS#7 object to read the data to.\n * @param obj the ASN.1 representation of the content block.\n * @param validator the ASN.1 structure validator object to use.\n *\n * @return the value map captured by validator object.\n */\nfunction _fromAsn1(msg, obj, validator) {\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, validator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 message. ' +\n 'ASN.1 object is not a supported PKCS#7 message.');\n error.errors = error;\n throw error;\n }\n\n // Check contentType, so far we only support (raw) Data.\n var contentType = asn1.derToOid(capture.contentType);\n if(contentType !== forge.pki.oids.data) {\n throw new Error('Unsupported PKCS#7 message. ' +\n 'Only wrapped ContentType Data supported.');\n }\n\n if(capture.encryptedContent) {\n var content = '';\n if(forge.util.isArray(capture.encryptedContent)) {\n for(var i = 0; i < capture.encryptedContent.length; ++i) {\n if(capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) {\n throw new Error('Malformed PKCS#7 message, expecting encrypted ' +\n 'content constructed of only OCTET STRING objects.');\n }\n content += capture.encryptedContent[i].value;\n }\n } else {\n content = capture.encryptedContent;\n }\n msg.encryptedContent = {\n algorithm: asn1.derToOid(capture.encAlgorithm),\n parameter: forge.util.createBuffer(capture.encParameter.value),\n content: forge.util.createBuffer(content)\n };\n }\n\n if(capture.content) {\n var content = '';\n if(forge.util.isArray(capture.content)) {\n for(var i = 0; i < capture.content.length; ++i) {\n if(capture.content[i].type !== asn1.Type.OCTETSTRING) {\n throw new Error('Malformed PKCS#7 message, expecting ' +\n 'content constructed of only OCTET STRING objects.');\n }\n content += capture.content[i].value;\n }\n } else {\n content = capture.content;\n }\n msg.content = forge.util.createBuffer(content);\n }\n\n msg.version = capture.version.charCodeAt(0);\n msg.rawCapture = capture;\n\n return capture;\n}\n\n/**\n * Decrypt the symmetrically encrypted content block of the PKCS#7 message.\n *\n * Decryption is skipped in case the PKCS#7 message object already has a\n * (decrypted) content attribute. The algorithm, key and cipher parameters\n * (probably the iv) are taken from the encryptedContent attribute of the\n * message object.\n *\n * @param The PKCS#7 message object.\n */\nfunction _decryptContent(msg) {\n if(msg.encryptedContent.key === undefined) {\n throw new Error('Symmetric key not available.');\n }\n\n if(msg.content === undefined) {\n var ciph;\n\n switch(msg.encryptedContent.algorithm) {\n case forge.pki.oids['aes128-CBC']:\n case forge.pki.oids['aes192-CBC']:\n case forge.pki.oids['aes256-CBC']:\n ciph = forge.aes.createDecryptionCipher(msg.encryptedContent.key);\n break;\n\n case forge.pki.oids['desCBC']:\n case forge.pki.oids['des-EDE3-CBC']:\n ciph = forge.des.createDecryptionCipher(msg.encryptedContent.key);\n break;\n\n default:\n throw new Error('Unsupported symmetric cipher, OID ' +\n msg.encryptedContent.algorithm);\n }\n ciph.start(msg.encryptedContent.parameter);\n ciph.update(msg.encryptedContent.content);\n\n if(!ciph.finish()) {\n throw new Error('Symmetric decryption failed.');\n }\n\n msg.content = ciph.output;\n }\n}\n","/**\n * Functions to output keys in SSH-friendly formats.\n *\n * This is part of the Forge project which may be used under the terms of\n * either the BSD License or the GNU General Public License (GPL) Version 2.\n *\n * See: https://github.com/digitalbazaar/forge/blob/cbebca3780658703d925b61b2caffb1d263a6c1d/LICENSE\n *\n * @author https://github.com/shellac\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./hmac');\nrequire('./md5');\nrequire('./sha1');\nrequire('./util');\n\nvar ssh = module.exports = forge.ssh = forge.ssh || {};\n\n/**\n * Encodes (and optionally encrypts) a private RSA key as a Putty PPK file.\n *\n * @param privateKey the key.\n * @param passphrase a passphrase to protect the key (falsy for no encryption).\n * @param comment a comment to include in the key file.\n *\n * @return the PPK file as a string.\n */\nssh.privateKeyToPutty = function(privateKey, passphrase, comment) {\n comment = comment || '';\n passphrase = passphrase || '';\n var algorithm = 'ssh-rsa';\n var encryptionAlgorithm = (passphrase === '') ? 'none' : 'aes256-cbc';\n\n var ppk = 'PuTTY-User-Key-File-2: ' + algorithm + '\\r\\n';\n ppk += 'Encryption: ' + encryptionAlgorithm + '\\r\\n';\n ppk += 'Comment: ' + comment + '\\r\\n';\n\n // public key into buffer for ppk\n var pubbuffer = forge.util.createBuffer();\n _addStringToBuffer(pubbuffer, algorithm);\n _addBigIntegerToBuffer(pubbuffer, privateKey.e);\n _addBigIntegerToBuffer(pubbuffer, privateKey.n);\n\n // write public key\n var pub = forge.util.encode64(pubbuffer.bytes(), 64);\n var length = Math.floor(pub.length / 66) + 1; // 66 = 64 + \\r\\n\n ppk += 'Public-Lines: ' + length + '\\r\\n';\n ppk += pub;\n\n // private key into a buffer\n var privbuffer = forge.util.createBuffer();\n _addBigIntegerToBuffer(privbuffer, privateKey.d);\n _addBigIntegerToBuffer(privbuffer, privateKey.p);\n _addBigIntegerToBuffer(privbuffer, privateKey.q);\n _addBigIntegerToBuffer(privbuffer, privateKey.qInv);\n\n // optionally encrypt the private key\n var priv;\n if(!passphrase) {\n // use the unencrypted buffer\n priv = forge.util.encode64(privbuffer.bytes(), 64);\n } else {\n // encrypt RSA key using passphrase\n var encLen = privbuffer.length() + 16 - 1;\n encLen -= encLen % 16;\n\n // pad private key with sha1-d data -- needs to be a multiple of 16\n var padding = _sha1(privbuffer.bytes());\n\n padding.truncate(padding.length() - encLen + privbuffer.length());\n privbuffer.putBuffer(padding);\n\n var aeskey = forge.util.createBuffer();\n aeskey.putBuffer(_sha1('\\x00\\x00\\x00\\x00', passphrase));\n aeskey.putBuffer(_sha1('\\x00\\x00\\x00\\x01', passphrase));\n\n // encrypt some bytes using CBC mode\n // key is 40 bytes, so truncate *by* 8 bytes\n var cipher = forge.aes.createEncryptionCipher(aeskey.truncate(8), 'CBC');\n cipher.start(forge.util.createBuffer().fillWithByte(0, 16));\n cipher.update(privbuffer.copy());\n cipher.finish();\n var encrypted = cipher.output;\n\n // Note: this appears to differ from Putty -- is forge wrong, or putty?\n // due to padding we finish as an exact multiple of 16\n encrypted.truncate(16); // all padding\n\n priv = forge.util.encode64(encrypted.bytes(), 64);\n }\n\n // output private key\n length = Math.floor(priv.length / 66) + 1; // 64 + \\r\\n\n ppk += '\\r\\nPrivate-Lines: ' + length + '\\r\\n';\n ppk += priv;\n\n // MAC\n var mackey = _sha1('putty-private-key-file-mac-key', passphrase);\n\n var macbuffer = forge.util.createBuffer();\n _addStringToBuffer(macbuffer, algorithm);\n _addStringToBuffer(macbuffer, encryptionAlgorithm);\n _addStringToBuffer(macbuffer, comment);\n macbuffer.putInt32(pubbuffer.length());\n macbuffer.putBuffer(pubbuffer);\n macbuffer.putInt32(privbuffer.length());\n macbuffer.putBuffer(privbuffer);\n\n var hmac = forge.hmac.create();\n hmac.start('sha1', mackey);\n hmac.update(macbuffer.bytes());\n\n ppk += '\\r\\nPrivate-MAC: ' + hmac.digest().toHex() + '\\r\\n';\n\n return ppk;\n};\n\n/**\n * Encodes a public RSA key as an OpenSSH file.\n *\n * @param key the key.\n * @param comment a comment.\n *\n * @return the public key in OpenSSH format.\n */\nssh.publicKeyToOpenSSH = function(key, comment) {\n var type = 'ssh-rsa';\n comment = comment || '';\n\n var buffer = forge.util.createBuffer();\n _addStringToBuffer(buffer, type);\n _addBigIntegerToBuffer(buffer, key.e);\n _addBigIntegerToBuffer(buffer, key.n);\n\n return type + ' ' + forge.util.encode64(buffer.bytes()) + ' ' + comment;\n};\n\n/**\n * Encodes a private RSA key as an OpenSSH file.\n *\n * @param key the key.\n * @param passphrase a passphrase to protect the key (falsy for no encryption).\n *\n * @return the public key in OpenSSH format.\n */\nssh.privateKeyToOpenSSH = function(privateKey, passphrase) {\n if(!passphrase) {\n return forge.pki.privateKeyToPem(privateKey);\n }\n // OpenSSH private key is just a legacy format, it seems\n return forge.pki.encryptRsaPrivateKey(privateKey, passphrase,\n {legacy: true, algorithm: 'aes128'});\n};\n\n/**\n * Gets the SSH fingerprint for the given public key.\n *\n * @param options the options to use.\n * [md] the message digest object to use (defaults to forge.md.md5).\n * [encoding] an alternative output encoding, such as 'hex'\n * (defaults to none, outputs a byte buffer).\n * [delimiter] the delimiter to use between bytes for 'hex' encoded\n * output, eg: ':' (defaults to none).\n *\n * @return the fingerprint as a byte buffer or other encoding based on options.\n */\nssh.getPublicKeyFingerprint = function(key, options) {\n options = options || {};\n var md = options.md || forge.md.md5.create();\n\n var type = 'ssh-rsa';\n var buffer = forge.util.createBuffer();\n _addStringToBuffer(buffer, type);\n _addBigIntegerToBuffer(buffer, key.e);\n _addBigIntegerToBuffer(buffer, key.n);\n\n // hash public key bytes\n md.start();\n md.update(buffer.getBytes());\n var digest = md.digest();\n if(options.encoding === 'hex') {\n var hex = digest.toHex();\n if(options.delimiter) {\n return hex.match(/.{2}/g).join(options.delimiter);\n }\n return hex;\n } else if(options.encoding === 'binary') {\n return digest.getBytes();\n } else if(options.encoding) {\n throw new Error('Unknown encoding \"' + options.encoding + '\".');\n }\n return digest;\n};\n\n/**\n * Adds len(val) then val to a buffer.\n *\n * @param buffer the buffer to add to.\n * @param val a big integer.\n */\nfunction _addBigIntegerToBuffer(buffer, val) {\n var hexVal = val.toString(16);\n // ensure 2s complement +ve\n if(hexVal[0] >= '8') {\n hexVal = '00' + hexVal;\n }\n var bytes = forge.util.hexToBytes(hexVal);\n buffer.putInt32(bytes.length);\n buffer.putBytes(bytes);\n}\n\n/**\n * Adds len(val) then val to a buffer.\n *\n * @param buffer the buffer to add to.\n * @param val a string.\n */\nfunction _addStringToBuffer(buffer, val) {\n buffer.putInt32(val.length);\n buffer.putString(val);\n}\n\n/**\n * Hashes the arguments into one value using SHA-1.\n *\n * @return the sha1 hash of the provided arguments.\n */\nfunction _sha1() {\n var sha = forge.md.sha1.create();\n var num = arguments.length;\n for (var i = 0; i < num; ++i) {\n sha.update(arguments[i]);\n }\n return sha.digest();\n}\n","/**\n * Node.js module for Forge.\n *\n * @author Dave Longley\n *\n * Copyright 2011-2016 Digital Bazaar, Inc.\n */\nmodule.exports = require('./forge');\nrequire('./aes');\nrequire('./aesCipherSuites');\nrequire('./asn1');\nrequire('./cipher');\nrequire('./des');\nrequire('./ed25519');\nrequire('./hmac');\nrequire('./kem');\nrequire('./log');\nrequire('./md.all');\nrequire('./mgf1');\nrequire('./pbkdf2');\nrequire('./pem');\nrequire('./pkcs1');\nrequire('./pkcs12');\nrequire('./pkcs7');\nrequire('./pki');\nrequire('./prime');\nrequire('./prng');\nrequire('./pss');\nrequire('./random');\nrequire('./rc2');\nrequire('./ssh');\nrequire('./tls');\nrequire('./util');\n","var forge = require('node-forge');\n\n// a hexString is considered negative if it's most significant bit is 1\n// because serial numbers use ones' complement notation\n// this RFC in section 4.1.2.2 requires serial numbers to be positive\n// http://www.ietf.org/rfc/rfc5280.txt\nfunction toPositiveHex(hexString){\n var mostSiginficativeHexAsInt = parseInt(hexString[0], 16);\n if (mostSiginficativeHexAsInt < 8){\n return hexString;\n }\n\n mostSiginficativeHexAsInt -= 8;\n return mostSiginficativeHexAsInt.toString() + hexString.substring(1);\n}\n\nfunction getAlgorithm(key) {\n switch (key) {\n case 'sha256':\n return forge.md.sha256.create();\n default:\n return forge.md.sha1.create();\n }\n}\n\n/**\n *\n * @param {forge.pki.CertificateField[]} attrs Attributes used for subject and issuer.\n * @param {object} options\n * @param {number} [options.days=365] the number of days before expiration\n * @param {number} [options.keySize=1024] the size for the private key in bits\n * @param {object} [options.extensions] additional extensions for the certificate\n * @param {string} [options.algorithm=\"sha1\"] The signature algorithm sha256 or sha1\n * @param {boolean} [options.pkcs7=false] include PKCS#7 as part of the output\n * @param {boolean} [options.clientCertificate=false] generate client cert signed by the original key\n * @param {string} [options.clientCertificateCN=\"John Doe jdoe123\"] client certificate's common name\n * @param {function} [done] Optional callback, if not provided the generation is synchronous\n * @returns\n */\nexports.generate = function generate(attrs, options, done) {\n if (typeof attrs === 'function') {\n done = attrs;\n attrs = undefined;\n } else if (typeof options === 'function') {\n done = options;\n options = {};\n }\n\n options = options || {};\n\n var generatePem = function (keyPair) {\n var cert = forge.pki.createCertificate();\n\n cert.serialNumber = toPositiveHex(forge.util.bytesToHex(forge.random.getBytesSync(9))); // the serial number can be decimal or hex (if preceded by 0x)\n\n cert.validity.notBefore = options.notBeforeDate || new Date();\n\n var notAfter = new Date();\n cert.validity.notAfter = notAfter;\n cert.validity.notAfter.setDate(notAfter.getDate() + (options.days || 365));\n\n attrs = attrs || [{\n name: 'commonName',\n value: 'example.org'\n }, {\n name: 'countryName',\n value: 'US'\n }, {\n shortName: 'ST',\n value: 'Virginia'\n }, {\n name: 'localityName',\n value: 'Blacksburg'\n }, {\n name: 'organizationName',\n value: 'Test'\n }, {\n shortName: 'OU',\n value: 'Test'\n }];\n\n cert.setSubject(attrs);\n cert.setIssuer(attrs);\n\n cert.publicKey = keyPair.publicKey;\n\n cert.setExtensions(options.extensions || [{\n name: 'basicConstraints',\n cA: true\n }, {\n name: 'keyUsage',\n keyCertSign: true,\n digitalSignature: true,\n nonRepudiation: true,\n keyEncipherment: true,\n dataEncipherment: true\n }, {\n name: 'subjectAltName',\n altNames: [{\n type: 6, // URI\n value: 'http://example.org/webid#me'\n }]\n }]);\n\n cert.sign(keyPair.privateKey, getAlgorithm(options && options.algorithm));\n\n const fingerprint = forge.md.sha1\n .create()\n .update(forge.asn1.toDer(forge.pki.certificateToAsn1(cert)).getBytes())\n .digest()\n .toHex()\n .match(/.{2}/g)\n .join(':');\n\n var pem = {\n private: forge.pki.privateKeyToPem(keyPair.privateKey),\n public: forge.pki.publicKeyToPem(keyPair.publicKey),\n cert: forge.pki.certificateToPem(cert),\n fingerprint: fingerprint,\n };\n\n if (options && options.pkcs7) {\n var p7 = forge.pkcs7.createSignedData();\n p7.addCertificate(cert);\n pem.pkcs7 = forge.pkcs7.messageToPem(p7);\n }\n\n if (options && options.clientCertificate) {\n var clientkeys = forge.pki.rsa.generateKeyPair(options.clientCertificateKeySize || 1024);\n var clientcert = forge.pki.createCertificate();\n clientcert.serialNumber = toPositiveHex(forge.util.bytesToHex(forge.random.getBytesSync(9)));\n clientcert.validity.notBefore = new Date();\n clientcert.validity.notAfter = new Date();\n clientcert.validity.notAfter.setFullYear(clientcert.validity.notBefore.getFullYear() + 1);\n\n var clientAttrs = JSON.parse(JSON.stringify(attrs));\n\n for(var i = 0; i < clientAttrs.length; i++) {\n if(clientAttrs[i].name === 'commonName') {\n if( options.clientCertificateCN )\n clientAttrs[i] = { name: 'commonName', value: options.clientCertificateCN };\n else\n clientAttrs[i] = { name: 'commonName', value: 'John Doe jdoe123' };\n }\n }\n\n clientcert.setSubject(clientAttrs);\n\n // Set the issuer to the parent key\n clientcert.setIssuer(attrs);\n\n clientcert.publicKey = clientkeys.publicKey;\n\n // Sign client cert with root cert\n clientcert.sign(keyPair.privateKey);\n\n pem.clientprivate = forge.pki.privateKeyToPem(clientkeys.privateKey);\n pem.clientpublic = forge.pki.publicKeyToPem(clientkeys.publicKey);\n pem.clientcert = forge.pki.certificateToPem(clientcert);\n\n if (options.pkcs7) {\n var clientp7 = forge.pkcs7.createSignedData();\n clientp7.addCertificate(clientcert);\n pem.clientpkcs7 = forge.pkcs7.messageToPem(clientp7);\n }\n }\n\n var caStore = forge.pki.createCaStore();\n caStore.addCertificate(cert);\n\n try {\n forge.pki.verifyCertificateChain(caStore, [cert],\n function (vfd, depth, chain) {\n if (vfd !== true) {\n throw new Error('Certificate could not be verified.');\n }\n return true;\n });\n }\n catch(ex) {\n throw new Error(ex);\n }\n\n return pem;\n };\n\n var keySize = options.keySize || 1024;\n\n if (done) { // async scenario\n return forge.pki.rsa.generateKeyPair({ bits: keySize }, function (err, keyPair) {\n if (err) { return done(err); }\n\n try {\n return done(null, generatePem(keyPair));\n } catch (ex) {\n return done(ex);\n }\n });\n }\n\n var keyPair = options.keyPair ? {\n privateKey: forge.pki.privateKeyFromPem(options.keyPair.privateKey),\n publicKey: forge.pki.publicKeyFromPem(options.keyPair.publicKey)\n } : forge.pki.rsa.generateKeyPair(keySize);\n\n return generatePem(keyPair);\n};\n","/**\n * Error type definitions and interfaces for the BlaizeJS framework\n *\n * This module contains all the type definitions used for error handling\n * across the BlaizeJS framework, including server-side errors, client-side\n * errors, and HTTP response formats.\n */\n\n/**\n * Structure of error responses sent over HTTP\n *\n * This interface defines the JSON format used for all error responses\n * from BlaizeJS servers. It matches the structure returned by BlaizeError.toJSON()\n *\n * @example\n * ```json\n * {\n * \"type\": \"VALIDATION_ERROR\",\n * \"title\": \"Request validation failed\",\n * \"status\": 400,\n * \"correlationId\": \"req_abc123\",\n * \"timestamp\": \"2024-01-15T10:30:00.000Z\",\n * \"details\": {\n * \"fields\": [\"email\", \"password\"]\n * }\n * }\n * ```\n */\nexport interface BlaizeErrorResponse {\n /** Error type from the ErrorType enum */\n type: ErrorType;\n\n /** Human-readable error message */\n title: string;\n\n /** HTTP status code */\n status: number;\n\n /** Correlation ID for request tracing */\n correlationId: string;\n\n /** ISO timestamp when error occurred */\n timestamp: string;\n\n /** Optional error-specific details */\n details?: unknown;\n}\n\n/**\n * Context information for network-related errors\n *\n * Used by client-side error classes to provide additional context\n * about network failures, timeouts, and connection issues.\n */\nexport interface NetworkErrorContext {\n /** The URL that failed */\n url: string;\n\n /** HTTP method being attempted */\n method: string;\n\n /** Correlation ID for tracing */\n correlationId: string;\n\n /** Timeout value if applicable */\n timeout?: number;\n\n /** The original error that caused the network failure */\n originalError: Error;\n\n /** Additional network-specific details */\n networkDetails?: {\n /** Whether this was a connection timeout */\n isTimeout?: boolean;\n\n /** Whether this was a DNS resolution failure */\n isDnsFailure?: boolean;\n\n /** Whether this was a connection refused error */\n isConnectionRefused?: boolean;\n\n /** HTTP status code if received before failure */\n statusCode?: number;\n };\n}\n\n/**\n * Context information for request timeout errors\n *\n * Specialized context for timeout-specific errors with timing information.\n */\nexport interface TimeoutErrorContext {\n /** The URL that timed out */\n url: string;\n\n /** HTTP method being attempted */\n method: string;\n\n /** Correlation ID for tracing */\n correlationId: string;\n\n /** Configured timeout value in milliseconds */\n timeoutMs: number;\n\n /** Actual duration before timeout in milliseconds */\n elapsedMs: number;\n\n /** Type of timeout (request, connection, etc.) */\n timeoutType: 'request' | 'connection' | 'response' | 'idle';\n}\n\n/**\n * Context information for response parsing errors\n *\n * Used when the client receives a response but cannot parse it properly.\n */\nexport interface ParseErrorContext {\n /** The URL that returned unparseable content */\n url: string;\n\n /** HTTP method used */\n method: string;\n\n /** Correlation ID for tracing */\n correlationId: string;\n\n /** HTTP status code received */\n statusCode: number;\n\n /** Content-Type header if available */\n contentType?: string;\n\n /** Expected response format */\n expectedFormat: 'json' | 'text' | 'binary';\n\n /** Sample of the actual response content (truncated for safety) */\n responseSample?: string;\n\n /** The original parsing error */\n originalError: Error;\n}\n\n/**\n * Validation error field details\n *\n * Structure for field-level validation errors with multiple error messages\n * per field.\n */\nexport interface ValidationFieldError {\n /** Field name or path (e.g., \"email\", \"user.profile.name\") */\n field: string;\n\n /** Array of error messages for this field */\n messages: string[];\n\n /** The invalid value that caused the error */\n rejectedValue?: unknown;\n\n /** Expected type or format */\n expectedType?: string;\n}\n\n/**\n * Validation error details structure\n *\n * Used by ValidationError to provide structured information about\n * what fields failed validation and why.\n */\nexport interface ValidationErrorDetails {\n /** Array of field-level errors */\n fields: ValidationFieldError[];\n\n /** Total number of validation errors */\n errorCount: number;\n\n /** The section that failed validation */\n section: 'params' | 'query' | 'body' | 'response';\n\n /** Schema name if available */\n schemaName?: string;\n}\n\n/**\n * All available error types in the BlaizeJS framework\n *\n * This enum provides both compile-time type safety and runtime values\n * for error type identification across server and client packages.\n *\n * @example Type-safe error handling:\n * ```typescript\n * function handleError(errorType: ErrorType) {\n * switch (errorType) {\n * case ErrorType.VALIDATION_ERROR:\n * // Handle validation error\n * break;\n * case ErrorType.NOT_FOUND:\n * // Handle not found error\n * break;\n * // TypeScript ensures all cases are covered\n * }\n * }\n * ```\n */\nexport enum ErrorType {\n // Server-side business logic errors\n /** Request validation failed (400) */\n VALIDATION_ERROR = 'VALIDATION_ERROR',\n\n /** Resource not found (404) */\n NOT_FOUND = 'NOT_FOUND',\n\n /** Authentication required (401) */\n UNAUTHORIZED = 'UNAUTHORIZED',\n\n /** Access forbidden (403) */\n FORBIDDEN = 'FORBIDDEN',\n\n /** Resource conflict (409) */\n CONFLICT = 'CONFLICT',\n\n /** Rate limit exceeded (429) */\n RATE_LIMITED = 'RATE_LIMITED',\n\n /** Internal server error (500) */\n INTERNAL_SERVER_ERROR = 'INTERNAL_SERVER_ERROR',\n\n /** File/Request Too Large (413) */\n PAYLOAD_TOO_LARGE = 'PAYLOAD_TOO_LARGE',\n\n /** Wrong Content Type (415) */\n UNSUPPORTED_MEDIA_TYPE = 'UNSUPPORTED_MEDIA_TYPE',\n\n /** Upload Timeout (408) */\n UPLOAD_TIMEOUT = 'UPLOAD_TIMEOUT',\n\n /** Valid Format Invalid Semantics (422) */\n UNPROCESSABLE_ENTITY = 'UNPROCESSABLE_ENTITY',\n\n // Client-side errors\n /** Network connectivity failure (0) */\n NETWORK_ERROR = 'NETWORK_ERROR',\n\n /** Request or response timeout (0) */\n TIMEOUT_ERROR = 'TIMEOUT_ERROR',\n\n /** Response parsing failure (0) */\n PARSE_ERROR = 'PARSE_ERROR',\n\n /** Generic HTTP error (varies) */\n HTTP_ERROR = 'HTTP_ERROR',\n}\n\n/**\n * Error severity levels for logging and monitoring\n *\n * Provides a way to categorize errors by their impact and urgency.\n */\nexport enum ErrorSeverity {\n /** Low impact, often user errors */\n LOW = 'low',\n\n /** Medium impact, application errors */\n MEDIUM = 'medium',\n\n /** High impact, system errors */\n HIGH = 'high',\n\n /** Critical impact, service disruption */\n CRITICAL = 'critical',\n}\n\n/**\n * Abstract base class for all BlaizeJS errors\n *\n * This class provides the foundation for all error types in the BlaizeJS framework.\n * It extends JavaScript's built-in Error class and adds framework-specific properties\n * for consistent error handling across server and client.\n *\n * @example\n * ```typescript\n * import { ErrorType } from './types';\n *\n * class NotFoundError extends BlaizeError<{ resourceId: string }> {\n * constructor(message = 'Resource not found', details?: { resourceId: string }) {\n * super(ErrorType.NOT_FOUND, message, 404, getCurrentCorrelationId(), details);\n * }\n * }\n * ```\n *\n * @template TDetails - Type for error-specific details object\n */\nexport abstract class BlaizeError<TDetails = unknown> extends Error {\n /**\n * Error type identifier from the ErrorType enum\n * Used for programmatic error handling and client-side error routing\n */\n readonly type: ErrorType;\n\n /**\n * Human-readable error title/message\n * Should be descriptive enough for debugging but safe for end users\n */\n readonly title: string;\n\n /**\n * HTTP status code associated with this error\n * Used by the error boundary to set appropriate response status\n */\n readonly status: number;\n\n /**\n * Correlation ID for request tracing\n * Links this error to the specific request that generated it\n */\n readonly correlationId: string;\n\n /**\n * Timestamp when the error occurred\n * Useful for debugging and log correlation\n */\n readonly timestamp: Date;\n\n /**\n * Additional error-specific details\n * Type-safe error context that varies by error type\n */\n readonly details?: TDetails | undefined;\n\n /**\n * Creates a new BlaizeError instance\n *\n * @param type - Error type from the ErrorType enum\n * @param title - Human-readable error message\n * @param status - HTTP status code\n * @param correlationId - Request correlation ID for tracing\n * @param details - Optional error-specific details\n */\n protected constructor(\n type: ErrorType,\n title: string,\n status: number,\n correlationId: string,\n details?: TDetails | undefined\n ) {\n super(title);\n\n // Set the error name to the class name for better stack traces\n this.name = this.constructor.name;\n\n // Framework-specific properties\n this.type = type;\n this.title = title;\n this.status = status;\n this.correlationId = correlationId;\n this.timestamp = new Date();\n this.details = details;\n\n // Maintain proper prototype chain for instanceof checks\n Object.setPrototypeOf(this, new.target.prototype);\n\n // Capture stack trace if available (V8 feature)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /**\n * Serializes the error to a plain object suitable for HTTP responses\n *\n * @returns Object representation of the error\n */\n toJSON() {\n const base = {\n type: this.type,\n title: this.title,\n status: this.status,\n correlationId: this.correlationId,\n timestamp: this.timestamp.toISOString(),\n };\n\n // Only include details if they are not undefined\n if (this.details !== undefined) {\n return { ...base, details: this.details };\n }\n\n return base;\n }\n\n /**\n * Returns a string representation of the error\n * Includes correlation ID for easier debugging\n */\n toString(): string {\n return `${this.name}: ${this.title} [${this.correlationId}]`;\n }\n}\n\n/**\n * Interface for payload too large error details\n */\nexport interface PayloadTooLargeErrorDetails {\n fileCount?: number;\n maxFiles?: number;\n filename?: string;\n field?: string;\n contentType?: string;\n currentSize?: number;\n maxSize?: number;\n}\n\n/**\n * Interface for unsupported media type error details\n */\nexport interface UnsupportedMediaTypeErrorDetails {\n receivedMimeType?: string;\n allowedMimeTypes?: string[];\n filename?: string;\n}\n\n/**\n * Interface for authentication error details\n */\nexport interface UnauthorizedErrorDetails {\n /** Reason for authentication failure */\n reason?:\n | 'missing_token'\n | 'invalid_token'\n | 'expired_token'\n | 'malformed_token'\n | 'insufficient_scope'\n | string;\n\n /** Authentication scheme (Bearer, Basic, etc.) */\n authScheme?: string;\n\n /** Authentication realm */\n realm?: string;\n\n /** Detailed error description */\n error_description?: string;\n\n /** Required scopes or permissions */\n requiredScopes?: string[];\n\n /** Login URL for interactive authentication */\n loginUrl?: string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for authorization/permission error details\n */\nexport interface ForbiddenErrorDetails {\n /** Required permission or role */\n requiredPermission?: string;\n\n /** User's current permissions */\n userPermissions?: string[];\n\n /** Resource being accessed */\n resource?: string;\n\n /** Action being attempted */\n action?: string;\n\n /** Reason for access denial */\n reason?: 'insufficient_permissions' | 'account_suspended' | 'resource_locked' | string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for resource conflict error details\n */\nexport interface ConflictErrorDetails {\n /** Type of conflict */\n conflictType?:\n | 'duplicate_key'\n | 'version_mismatch'\n | 'concurrent_modification'\n | 'business_rule'\n | string;\n\n /** Field that caused the conflict */\n field?: string;\n\n /** Existing value that conflicts */\n existingValue?: unknown;\n\n /** Provided value that conflicts */\n providedValue?: unknown;\n\n /** Resource that has the conflicting value */\n conflictingResource?: string;\n\n /** Current version/etag of the resource */\n currentVersion?: string;\n\n /** Expected version/etag */\n expectedVersion?: string;\n\n /** Suggested resolution */\n resolution?: string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for rate limiting error details\n */\nexport interface RateLimitErrorDetails {\n /** Maximum requests allowed in the time window */\n limit?: number;\n\n /** Remaining requests in current window */\n remaining?: number;\n\n /** When the rate limit resets */\n resetTime?: Date;\n\n /** Seconds until the rate limit resets */\n retryAfter?: number;\n\n /** Time window for the rate limit */\n window?: string;\n\n /** Identifier used for rate limiting (IP, user ID, etc.) */\n identifier?: string;\n\n /** Type of rate limit hit */\n limitType?: 'global' | 'per_user' | 'per_ip' | 'per_endpoint' | string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for internal server error details\n */\nexport interface InternalServerErrorDetails {\n /** Original error message (for debugging) */\n originalError?: string;\n\n /** Stack trace (for debugging) */\n stackTrace?: string;\n\n /** Component where the error occurred */\n component?: string;\n\n /** Operation being performed */\n operation?: string;\n\n /** Internal error code */\n internalErrorCode?: string;\n\n /** When the error occurred */\n timestamp?: Date;\n\n /** Whether this error should be retryable */\n retryable?: boolean;\n\n /** Additional debugging context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for NotFound error details\n * Provides context about the missing resource\n */\nexport interface NotFoundErrorDetails {\n /** Type of resource that was not found */\n resourceType?: string;\n\n /** ID or identifier of the resource */\n resourceId?: string;\n\n /** Collection or table where the resource was searched */\n collection?: string;\n\n /** Search criteria that was used */\n query?: Record<string, unknown>;\n\n /** Search criteria that was used (for backward compatibility) */\n searchCriteria?: Record<string, unknown>;\n\n /** The path that was attempted */\n path?: string;\n\n /** HTTP method used (for API endpoints) */\n method?: string;\n\n /** The path that was attempted (for backward compatibility) */\n attemptedPath?: string;\n\n /** Parent resource information for nested resources */\n parentResource?: {\n type: string;\n id: string;\n };\n\n /** Helpful suggestion for the user */\n suggestion?: string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n// TODO: This can potentiall be removed\n/**\n * Interface for body parsing errors stored in context state\n */\nexport interface BodyParseError {\n /**\n * Type of parsing error that occurred\n */\n readonly type:\n | 'json_parse_error'\n | 'form_parse_error'\n | 'multipart_parse_error'\n | 'body_read_error';\n\n /**\n * Human-readable error message\n */\n readonly message: string;\n\n /**\n * Original error object or details\n */\n readonly error: unknown;\n}\n\n/**\n * Type guard to check if an object is a BodyParseError\n */\nexport function isBodyParseError(error: unknown): error is BodyParseError {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'type' in error &&\n 'message' in error &&\n 'error' in error &&\n typeof (error as any).type === 'string' &&\n typeof (error as any).message === 'string'\n );\n}\n\n/**\n * Context information for error transformation\n */\nexport interface ErrorTransformContext {\n url: string;\n method: string;\n correlationId: string;\n timeoutMs?: number;\n elapsedMs?: number;\n statusCode?: number;\n contentType?: string;\n responseSample?: string;\n [key: string]: unknown;\n}\n","/**\n * Correlation ID system for request tracing across async operations\n *\n * This module provides utilities for generating, storing, and accessing\n * correlation IDs that follow requests through the entire application stack.\n * Uses AsyncLocalStorage for automatic context propagation.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\n/**\n * AsyncLocalStorage instance for storing correlation IDs\n * Separate from the main context storage to allow independent lifecycle management\n */\nconst correlationStorage = new AsyncLocalStorage<string>();\n\n/**\n * Generates a new unique correlation ID\n *\n * Format: req_[timestamp_base36]_[random_base36]\n * Example: req_k3x2m1_9z8y7w6v\n *\n * @returns A unique correlation ID string\n */\nexport function generateCorrelationId(): string {\n const timestamp = Date.now().toString(36); // Base36 encoded timestamp\n const random = Math.random().toString(36).substr(2, 9); // Base36 random string\n return `req_${timestamp}_${random}`;\n}\n\n/**\n * Gets the current correlation ID from AsyncLocalStorage\n *\n * @returns The current correlation ID, or 'unknown' if none is set\n */\nexport function getCurrentCorrelationId(): string {\n const stored = correlationStorage.getStore();\n return stored && stored.trim() ? stored : 'unknown';\n}\n\n/**\n * Sets the correlation ID in the current AsyncLocalStorage context\n *\n * This will affect the current execution context and any subsequent\n * async operations that inherit from it.\n *\n * @param correlationId - The correlation ID to set\n */\nexport function setCorrelationId(correlationId: string): void {\n correlationStorage.enterWith(correlationId);\n}\n\n/**\n * Runs a function with a specific correlation ID\n *\n * Creates a new AsyncLocalStorage context with the provided correlation ID.\n * The correlation ID will be available to the function and any async operations\n * it spawns, but will not affect the parent context.\n *\n * @param correlationId - The correlation ID to use for this context\n * @param fn - The function to run with the correlation ID\n * @returns The result of the function\n *\n * @example\n * ```typescript\n * const result = await withCorrelationId('req_123', async () => {\n * console.log(getCurrentCorrelationId()); // 'req_123'\n * return await processRequest();\n * });\n * ```\n */\nexport function withCorrelationId<T>(\n correlationId: string,\n fn: () => T | Promise<T>\n): T | Promise<T> {\n return correlationStorage.run(correlationId, fn);\n}\n\n/**\n * Extracts correlation ID from headers or generates a new one\n *\n * Looks for the 'x-correlation-id' header and uses it if present.\n * If not found, empty, or undefined, generates a new correlation ID.\n *\n * @param headers - HTTP headers object\n * @returns A correlation ID (either from headers or newly generated)\n *\n * @example\n * ```typescript\n * // From incoming request headers\n * const correlationId = getOrGenerateCorrelationId(request.headers);\n *\n * // Use in request processing\n * await withCorrelationId(correlationId, async () => {\n * // Process request with correlation tracking\n * });\n * ```\n */\nexport function getOrGenerateCorrelationId(headers: Record<string, string | undefined>): string {\n const headerCorrelationId = headers['x-correlation-id'];\n\n // Use header value if it exists and is not empty\n if (headerCorrelationId && headerCorrelationId.trim()) {\n return headerCorrelationId;\n }\n\n // Generate new correlation ID if header is missing or empty\n return generateCorrelationId();\n}\n\n/**\n * Creates a middleware function for setting correlation ID from request headers\n *\n * This is a utility for integrating correlation ID handling into the middleware stack.\n * It extracts or generates a correlation ID and sets it for the request processing.\n *\n * @returns Middleware function that sets correlation ID\n *\n * @example\n * ```typescript\n * import { createServer } from 'blaizejs';\n * import { createCorrelationMiddleware } from './correlation';\n *\n * const server = createServer({\n * middleware: [\n * createCorrelationMiddleware(),\n * // ... other middleware\n * ]\n * });\n * ```\n */\nexport function createCorrelationMiddleware() {\n return {\n name: 'correlation',\n execute: async (context: any, next: () => Promise<void>) => {\n // Extract headers from context (adapting to BlaizeJS context structure)\n const headers = context.request.headers();\n const correlationId = getOrGenerateCorrelationId(headers);\n\n // Set correlation ID and process request\n await withCorrelationId(correlationId, next);\n },\n debug: () => ({ stage: 'correlation-id-setup' }),\n };\n}\n\n/**\n * Type-safe wrapper for functions that need correlation ID context\n *\n * Ensures that a function always has access to a correlation ID,\n * either from the current context or by generating a new one.\n *\n * @param fn - Function that requires correlation ID context\n * @returns Wrapped function that guarantees correlation ID availability\n */\nexport function withEnsuredCorrelation<T extends any[], R>(\n fn: (...args: T) => R | Promise<R>\n): (...args: T) => R | Promise<R> {\n return (...args: T): R | Promise<R> => {\n const currentCorrelationId = getCurrentCorrelationId();\n\n // If we already have a correlation ID, just run the function\n if (currentCorrelationId !== 'unknown') {\n return fn(...args);\n }\n\n // Generate new correlation ID and run function in that context\n const newCorrelationId = generateCorrelationId();\n return withCorrelationId(newCorrelationId, () => fn(...args));\n };\n}\n\n/**\n * Debugging utility to get correlation storage information\n *\n * @internal This is for debugging purposes only\n */\nexport function _getCorrelationStorageInfo() {\n return {\n hasActiveStore: correlationStorage.getStore() !== undefined,\n currentCorrelationId: correlationStorage.getStore() ?? null,\n };\n}\n","/**\n * InternalServerError class for server-side errors\n *\n * This error is thrown for unexpected server-side errors that are not\n * the client's fault. It provides debugging context while protecting\n * sensitive information in production.\n */\n\nimport { BlaizeError, ErrorType } from '@blaize-types/errors';\n\nimport { getCurrentCorrelationId } from './correlation';\n\nimport type { InternalServerErrorDetails } from '@blaize-types/errors';\n/**\n * Error thrown for internal server errors\n *\n * Automatically sets HTTP status to 500 and provides debugging context.\n * Note: In production, sensitive details should be filtered by error boundary.\n *\n * @example Basic usage:\n * ```typescript\n * throw new InternalServerError('Something went wrong');\n * ```\n *\n * @example With debugging details:\n * ```typescript\n * throw new InternalServerError('Database error', {\n * originalError: error.message,\n * component: 'user-service',\n * operation: 'createUser',\n * retryable: true\n * });\n * ```\n *\n * @example Wrapping an existing error:\n * ```typescript\n * try {\n * await database.connect();\n * } catch (error) {\n * throw new InternalServerError('Database connection failed', {\n * originalError: error.message,\n * stackTrace: error.stack,\n * component: 'database',\n * retryable: true\n * });\n * }\n * ```\n */\nexport class InternalServerError extends BlaizeError<InternalServerErrorDetails> {\n /**\n * Creates a new InternalServerError instance\n *\n * @param title - Human-readable error message\n * @param details - Optional debugging context\n * @param correlationId - Optional correlation ID (uses current context if not provided)\n */\n constructor(\n title: string,\n details: InternalServerErrorDetails | undefined = undefined,\n correlationId: string | undefined = undefined\n ) {\n super(\n ErrorType.INTERNAL_SERVER_ERROR,\n title,\n 500, // HTTP 500 Internal Server Error\n correlationId ?? getCurrentCorrelationId(),\n details\n );\n }\n}\n","/**\n * ValidationError class for request validation failures\n *\n * This error is thrown when request validation fails (params, query, body, or response).\n * It provides structured information about which fields failed validation and why.\n */\n\nimport { BlaizeError, ErrorType } from '@blaize-types/errors';\n\nimport { getCurrentCorrelationId } from './correlation';\n\nimport type { ValidationErrorDetails } from '@blaize-types/errors';\n\n/**\n * Error thrown when request validation fails\n *\n * Automatically sets HTTP status to 400 and provides structured\n * validation error information for better client debugging.\n *\n * @example Basic usage:\n * ```typescript\n * throw new ValidationError('Email is required');\n * ```\n *\n * @example With detailed field information:\n * ```typescript\n * throw new ValidationError('Validation failed', {\n * fields: [\n * {\n * field: 'email',\n * messages: ['Email is required', 'Email must be valid'],\n * rejectedValue: '',\n * expectedType: 'string'\n * }\n * ],\n * errorCount: 1,\n * section: 'body'\n * });\n * ```\n */\nexport class ValidationError extends BlaizeError<ValidationErrorDetails> {\n /**\n * Creates a new ValidationError instance\n *\n * @param title - Human-readable error message\n * @param details - Optional structured validation details\n * @param correlationId - Optional correlation ID (uses current context if not provided)\n */\n constructor(\n title: string,\n details: ValidationErrorDetails | undefined = undefined,\n correlationId: string | undefined = undefined\n ) {\n super(\n ErrorType.VALIDATION_ERROR,\n title,\n 400, // HTTP 400 Bad Request\n correlationId ?? getCurrentCorrelationId(),\n details\n );\n }\n}\n","import { getCurrentCorrelationId } from './correlation';\nimport { BlaizeError, ErrorType } from '../../../blaize-types/src/errors';\n\nimport type { PayloadTooLargeErrorDetails } from '@blaize-types/errors';\n\nexport class PayloadTooLargeError extends BlaizeError<PayloadTooLargeErrorDetails> {\n constructor(\n title: string,\n details?: PayloadTooLargeErrorDetails | undefined,\n correlationId?: string\n ) {\n super(\n ErrorType.PAYLOAD_TOO_LARGE,\n title,\n 413,\n correlationId ?? getCurrentCorrelationId(),\n details\n );\n }\n}\n","import { getCurrentCorrelationId } from './correlation';\nimport { BlaizeError, ErrorType } from '../../../blaize-types/src/errors';\n\nexport class UnsupportedMediaTypeError extends BlaizeError {\n constructor(title: string, details?: unknown, correlationId?: string) {\n super(\n ErrorType.UNSUPPORTED_MEDIA_TYPE,\n title,\n 415,\n correlationId ?? getCurrentCorrelationId(),\n details\n );\n }\n}\n","/**\n * BlaizeJS Core\n *\n * A blazing-fast, type-safe Node.js framework with file-based routing,\n * powerful middleware, and end-to-end type safety.\n *\n * @package blaizejs\n */\n\nimport { compose } from './middleware/compose';\nimport { create as createMiddleware } from './middleware/create';\nimport { create as createPlugin } from './plugins/create';\nimport {\n createDeleteRoute,\n createGetRoute,\n createHeadRoute,\n createOptionsRoute,\n createPatchRoute,\n createPostRoute,\n createPutRoute,\n} from './router/create';\nimport { create as createServer } from './server/create';\n\n// TODO: ideally this could be import as an npm package, but for now we use a relative path\n// Explicit imports to avoid using values without importing\nexport * from '../../blaize-types/src/index';\n\n// Re-export everything\n// Server module exports\nexport { createServer };\n\n// Router module exports\nexport {\n createDeleteRoute,\n createGetRoute,\n createHeadRoute,\n createOptionsRoute,\n createPatchRoute,\n createPostRoute,\n createPutRoute,\n};\n\n// Middleware module exports\nexport { createMiddleware, compose };\n\n// Plugins module exports\nexport { createPlugin };\n\n// Version information\nexport const VERSION = '0.1.0';\n\n// Namespaced exports with different names to avoid conflicts\nexport const ServerAPI = { createServer };\nexport const RouterAPI = {\n createDeleteRoute,\n createGetRoute,\n createHeadRoute,\n createOptionsRoute,\n createPatchRoute,\n createPostRoute,\n createPutRoute,\n};\nexport const MiddlewareAPI = { createMiddleware, compose };\nexport const PluginsAPI = { createPlugin };\n\n// Server-side error classes\nexport { ValidationError } from './errors/validation-error';\nexport { NotFoundError } from './errors/not-found-error';\nexport { UnauthorizedError } from './errors/unauthorized-error';\nexport { ForbiddenError } from './errors/forbidden-error';\nexport { ConflictError } from './errors/conflict-error';\nexport { RateLimitError } from './errors/rate-limit-error';\nexport { InternalServerError } from './errors/internal-server-error';\nexport { PayloadTooLargeError } from './errors/payload-too-large-error';\nexport { RequestTimeoutError } from './errors/request-timeout-error';\nexport { UnsupportedMediaTypeError } from './errors/unsupported-media-type-error';\nexport { UnprocessableEntityError } from './errors/unprocessable-entity-error';\n\n// Default export\nconst Blaize = {\n // Core functions\n createServer,\n createMiddleware,\n createPlugin,\n\n // Namespaces (using the non-conflicting names)\n Server: ServerAPI,\n Router: RouterAPI,\n Middleware: MiddlewareAPI,\n Plugins: PluginsAPI,\n\n // Constants\n VERSION,\n};\n\nexport { Blaize };\n","import type { Context } from '@blaize-types/context';\nimport type { Middleware, NextFunction } from '@blaize-types/middleware';\n\n/**\n * Execute a single middleware, handling both function and object forms\n */\nexport function execute(\n middleware: Middleware | undefined,\n ctx: Context,\n next: NextFunction\n): Promise<void> {\n // Handle undefined middleware (safety check)\n if (!middleware) {\n return Promise.resolve(next());\n }\n\n // Handle middleware with skip function\n if (middleware.skip && middleware.skip(ctx)) {\n return Promise.resolve(next());\n }\n\n try {\n // Execute middleware\n const result = middleware.execute(ctx, next);\n\n // Handle both Promise and non-Promise returns\n if (result instanceof Promise) {\n // Return the promise directly to allow errors to propagate\n return result;\n } else {\n // Only wrap non-Promise returns\n return Promise.resolve(result);\n }\n } catch (error) {\n // Handle synchronous errors\n return Promise.reject(error);\n }\n}\n","import { execute } from './execute';\n\nimport type { Context } from '@blaize-types/context';\nimport type { Middleware, NextFunction, MiddlewareFunction } from '@blaize-types/middleware';\n\n/**\n * Compose multiple middleware functions into a single middleware function\n */\nexport function compose(middlewareStack: Middleware[]): MiddlewareFunction {\n // No middleware? Return a pass-through function\n if (middlewareStack.length === 0) {\n return async (_, next) => {\n await Promise.resolve(next());\n };\n }\n\n // Return a function that executes the middleware stack\n return async function (ctx: Context, finalHandler: NextFunction): Promise<void> {\n // Keep track of which \"next\" functions have been called\n const called = new Set<number>();\n\n // Create dispatch function to process middleware stack\n const dispatch = async (i: number): Promise<void> => {\n // If we've reached the end of the stack, execute the final handler\n if (i >= middlewareStack.length) {\n // Ensure we're returning a Promise regardless of what finalHandler returns\n return Promise.resolve(finalHandler());\n }\n\n // Get current middleware\n const middleware = middlewareStack[i];\n\n // Create a next function that can only be called once\n const nextDispatch = () => {\n if (called.has(i)) {\n throw new Error('next() called multiple times');\n }\n\n // Mark this middleware's next as called\n called.add(i);\n\n // Move to the next middleware\n return dispatch(i + 1);\n };\n\n // Use the executeMiddleware function we defined\n return execute(middleware, ctx, nextDispatch);\n };\n\n // Start middleware chain execution\n return dispatch(0);\n };\n}\n","import type { Middleware, MiddlewareOptions, MiddlewareFunction } from '@blaize-types/middleware';\n\n/**\n * Create a middleware\n */\nexport function create(handlerOrOptions: MiddlewareFunction | MiddlewareOptions): Middleware {\n // If handlerOrOptions is a function, convert it to our middleware object format\n if (typeof handlerOrOptions === 'function') {\n return {\n name: 'anonymous', // Default name for function middleware\n execute: handlerOrOptions,\n debug: false,\n };\n }\n\n // Otherwise, handle it as middleware options\n const { name = 'anonymous', handler, skip, debug = false } = handlerOrOptions;\n\n // Create base middleware object with required properties\n const middleware: Middleware = {\n name,\n execute: handler,\n debug,\n };\n\n if (skip !== undefined) {\n return {\n ...middleware,\n skip,\n };\n }\n\n return middleware;\n}\n","import type { Plugin, PluginFactory, PluginHooks } from '@blaize-types/plugins';\nimport type { Server } from '@blaize-types/server';\n\n/**\n * Create a plugin with the given name, version, and setup function\n */\nexport function create<T = any>(\n name: string,\n version: string,\n setup: (\n app: Server,\n options: T\n ) => void | Partial<PluginHooks> | Promise<void> | Promise<Partial<PluginHooks>>,\n defaultOptions: Partial<T> = {}\n): PluginFactory<T> {\n // Input validation\n if (!name || typeof name !== 'string') {\n throw new Error('Plugin name must be a non-empty string');\n }\n\n if (!version || typeof version !== 'string') {\n throw new Error('Plugin version must be a non-empty string');\n }\n\n if (typeof setup !== 'function') {\n throw new Error('Plugin setup must be a function');\n }\n\n // Return the factory function\n return function pluginFactory(userOptions?: Partial<T>) {\n // Merge default options with user options\n const mergedOptions = { ...defaultOptions, ...userOptions } as T;\n\n // Create the base plugin object\n const plugin: Plugin = {\n name,\n version,\n\n // The register hook calls the user's setup function\n register: async (app: Server) => {\n const result = await setup(app, mergedOptions);\n\n // If setup returns hooks, merge them into this plugin\n if (result && typeof result === 'object') {\n // Now we explicitly assign to our plugin object\n Object.assign(plugin, result);\n }\n },\n };\n\n return plugin;\n };\n}\n","import { fileURLToPath } from 'node:url';\n\nimport { getRoutesDir } from '../config';\nimport { parseRoutePath } from './discovery/parser';\n\nimport type {\n CreateGetRoute,\n CreatePostRoute,\n CreatePutRoute,\n CreateDeleteRoute,\n CreatePatchRoute,\n CreateHeadRoute,\n CreateOptionsRoute,\n} from '@blaize-types/router';\n\n/**\n * Get the file path of the function that called createXRoute\n */\nfunction getCallerFilePath(): string {\n const originalPrepareStackTrace = Error.prepareStackTrace;\n\n try {\n Error.prepareStackTrace = (_, stack) => stack;\n const stack = new Error().stack as unknown as NodeJS.CallSite[];\n\n // Stack: getCallerFilePath -> createXRoute -> route file\n const callerFrame = stack[3];\n if (!callerFrame || typeof callerFrame.getFileName !== 'function') {\n throw new Error('Unable to determine caller file frame');\n }\n const fileName = callerFrame.getFileName();\n\n if (!fileName) {\n throw new Error('Unable to determine caller file name');\n }\n\n if (fileName.startsWith('file://')) {\n return fileURLToPath(fileName);\n }\n\n return fileName;\n } finally {\n Error.prepareStackTrace = originalPrepareStackTrace;\n }\n}\n\n/**\n * Convert caller file path to route path using existing parsing logic\n */\nfunction getRoutePath(): string {\n const callerPath = getCallerFilePath();\n const routesDir = getRoutesDir();\n\n const parsedRoute = parseRoutePath(callerPath, routesDir);\n console.log(`🔎 Parsed route path: ${parsedRoute.routePath} from file: ${callerPath}`);\n\n return parsedRoute.routePath;\n}\n\n/**\n * Create a GET route\n * SIMPLER FIX: Just pass the config through, TypeScript will handle the types\n */\nexport const createGetRoute: CreateGetRoute = config => {\n validateMethodConfig('GET', config);\n\n const path = getRoutePath();\n\n return {\n GET: config as any, // Let TypeScript infer the proper types\n path,\n };\n};\n\n/**\n * Create a POST route\n */\nexport const createPostRoute: CreatePostRoute = config => {\n validateMethodConfig('POST', config);\n\n const path = getRoutePath();\n\n return {\n POST: config as any, // Let TypeScript infer the proper types\n path,\n };\n};\n\n/**\n * Create a PUT route\n */\nexport const createPutRoute: CreatePutRoute = config => {\n validateMethodConfig('PUT', config);\n\n const path = getRoutePath();\n\n return {\n PUT: config as any, // Let TypeScript infer the proper types\n path,\n };\n};\n\n/**\n * Create a DELETE route\n */\nexport const createDeleteRoute: CreateDeleteRoute = config => {\n validateMethodConfig('DELETE', config);\n\n const path = getRoutePath();\n\n return {\n DELETE: config as any, // Let TypeScript infer the proper types\n path,\n };\n};\n\n/**\n * Create a PATCH route\n */\nexport const createPatchRoute: CreatePatchRoute = config => {\n validateMethodConfig('PATCH', config);\n\n const path = getRoutePath();\n\n return {\n PATCH: config as any, // Let TypeScript infer the proper types\n path,\n };\n};\n\n/**\n * Create a HEAD route (same signature as GET - no body)\n */\nexport const createHeadRoute: CreateHeadRoute = config => {\n validateMethodConfig('HEAD', config);\n\n const path = getRoutePath();\n\n return {\n HEAD: config as any, // Let TypeScript infer the proper types\n path,\n };\n};\n\n/**\n * Create an OPTIONS route (same signature as GET - no body)\n */\nexport const createOptionsRoute: CreateOptionsRoute = config => {\n validateMethodConfig('OPTIONS', config);\n\n const path = getRoutePath();\n\n return {\n OPTIONS: config as any, // Let TypeScript infer the proper types\n path,\n };\n};\n\n/**\n * Validate a method configuration\n */\nfunction validateMethodConfig(method: string, config: any): void {\n if (!config.handler || typeof config.handler !== 'function') {\n throw new Error(`Handler for method ${method} must be a function`);\n }\n\n if (config.middleware && !Array.isArray(config.middleware)) {\n throw new Error(`Middleware for method ${method} must be an array`);\n }\n\n // Validate schema if provided\n if (config.schema) {\n validateSchema(method, config.schema);\n }\n\n // Method-specific warnings\n switch (method) {\n case 'GET':\n case 'HEAD':\n case 'DELETE':\n if (config.schema?.body) {\n console.warn(`Warning: ${method} requests typically don't have request bodies`);\n }\n break;\n }\n}\n\n/**\n * Validate schema structure\n */\nfunction validateSchema(method: string, schema: any): void {\n const { params, query, body, response } = schema;\n\n // Basic validation - ensure they look like Zod schemas if provided\n if (params && (!params._def || typeof params.parse !== 'function')) {\n throw new Error(`Params schema for ${method} must be a valid Zod schema`);\n }\n\n if (query && (!query._def || typeof query.parse !== 'function')) {\n throw new Error(`Query schema for ${method} must be a valid Zod schema`);\n }\n\n if (body && (!body._def || typeof body.parse !== 'function')) {\n throw new Error(`Body schema for ${method} must be a valid Zod schema`);\n }\n\n if (response && (!response._def || typeof response.parse !== 'function')) {\n throw new Error(`Response schema for ${method} must be a valid Zod schema`);\n }\n}\n","// config/runtime-config.ts\ninterface RuntimeConfig {\n routesDir?: string;\n basePath?: string;\n // Add other runtime configuration as needed\n}\n\n// Internal state - not exported\nlet config: RuntimeConfig = {};\n\n/**\n * Set runtime configuration\n */\nexport function setRuntimeConfig(newConfig: Partial<RuntimeConfig>): void {\n config = { ...config, ...newConfig };\n}\n\n/**\n * Get full runtime configuration\n */\nexport function getRuntimeConfig(): RuntimeConfig {\n return { ...config };\n}\n\n/**\n * Get the configured routes directory\n */\nexport function getRoutesDir(): string {\n if (!config.routesDir) {\n throw new Error('Routes directory not configured. Make sure server is properly initialized.');\n }\n return config.routesDir;\n}\n\n/**\n * Get the configured base path\n */\nexport function getBasePath(): string {\n return config.basePath || '';\n}\n\n/**\n * Clear configuration (useful for testing)\n */\nexport function clearRuntimeConfig(): void {\n config = {};\n}\n","import * as path from 'node:path';\n\nimport type { ParsedRoute } from '@blaize-types/router';\n\n/**\n * Parse a file path into a route path\n * Works consistently across Windows and Unix-like file systems\n */\nexport function parseRoutePath(filePath: string, basePath: string): ParsedRoute {\n // Clean file:// URLs if present\n if (filePath.startsWith('file://')) {\n filePath = filePath.replace('file://', '');\n }\n if (basePath.startsWith('file://')) {\n basePath = basePath.replace('file://', '');\n }\n\n // Convert all backslashes to forward slashes for consistent handling\n const forwardSlashFilePath = filePath.replace(/\\\\/g, '/');\n const forwardSlashBasePath = basePath.replace(/\\\\/g, '/');\n\n // Ensure the base path ends with a slash for proper prefix removal\n const normalizedBasePath = forwardSlashBasePath.endsWith('/')\n ? forwardSlashBasePath\n : `${forwardSlashBasePath}/`;\n\n // Remove the base path to get the relative path\n let relativePath = forwardSlashFilePath;\n if (forwardSlashFilePath.startsWith(normalizedBasePath)) {\n relativePath = forwardSlashFilePath.substring(normalizedBasePath.length);\n } else if (forwardSlashFilePath.startsWith(forwardSlashBasePath)) {\n relativePath = forwardSlashFilePath.substring(forwardSlashBasePath.length);\n // If base path didn't end with a slash but we still matched, ensure relative path doesn't start with a slash\n if (relativePath.startsWith('/')) {\n relativePath = relativePath.substring(1);\n }\n } else {\n // If base path isn't a prefix of file path, use path.relative as a fallback\n // But convert to forward slashes for consistency\n relativePath = path.relative(forwardSlashBasePath, forwardSlashFilePath).replace(/\\\\/g, '/');\n }\n\n // Remove file extension (anything after the last dot)\n relativePath = relativePath.replace(/\\.[^.]+$/, '');\n\n // Split the path into segments\n const segments = relativePath.split('/').filter(Boolean);\n const params: string[] = [];\n\n // Transform file path segments to route path segments\n const routeSegments = segments.map(segment => {\n // Handle dynamic parameters ([param])\n if (segment.startsWith('[') && segment.endsWith(']')) {\n const paramName = segment.slice(1, -1);\n params.push(paramName);\n return `:${paramName}`;\n }\n return segment;\n });\n\n // Create the final route path\n let routePath = routeSegments.length > 0 ? `/${routeSegments.join('/')}` : '/';\n\n // Handle index routes\n if (routePath.endsWith('/index')) {\n routePath = routePath.slice(0, -6) || '/';\n }\n\n return {\n filePath,\n routePath,\n params,\n };\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport EventEmitter from 'node:events';\n\nimport { setRuntimeConfig } from '../config';\nimport { startServer } from './start';\nimport { registerSignalHandlers, stopServer } from './stop';\nimport { validateServerOptions } from './validation';\nimport { createPluginLifecycleManager } from '../plugins/lifecycle';\nimport { validatePlugin } from '../plugins/validation';\nimport { createRouter } from '../router/router';\n\nimport type { Context } from '@blaize-types/context';\nimport type { Middleware } from '@blaize-types/middleware';\nimport type { Plugin } from '@blaize-types/plugins';\nimport type { Server, ServerOptions, ServerOptionsInput, StopOptions } from '@blaize-types/server';\n\nexport const DEFAULT_OPTIONS: ServerOptions = {\n port: 3000,\n host: 'localhost',\n routesDir: './routes',\n http2: {\n enabled: true,\n },\n middleware: [],\n plugins: [],\n};\n\n/**\n * Creates the configuration options by merging defaults with user-provided options\n */\nfunction createServerOptions(options: ServerOptionsInput = {}): ServerOptions {\n const baseOptions: ServerOptions = { ...DEFAULT_OPTIONS };\n setRuntimeConfig({ routesDir: options.routesDir || baseOptions.routesDir });\n\n return {\n port: options.port ?? baseOptions.port,\n host: options.host ?? baseOptions.host,\n routesDir: options.routesDir ?? baseOptions.routesDir,\n http2: {\n enabled: options.http2?.enabled ?? baseOptions.http2?.enabled,\n keyFile: options.http2?.keyFile ?? baseOptions.http2?.keyFile,\n certFile: options.http2?.certFile ?? baseOptions.http2?.certFile,\n },\n middleware: [...(baseOptions.middleware || []), ...(options.middleware || [])],\n plugins: [...(baseOptions.plugins || []), ...(options.plugins || [])],\n };\n}\n\n/**\n * Creates the server listen method\n */\nfunction createListenMethod(\n serverInstance: Server,\n validatedOptions: ServerOptions,\n initialMiddleware: Middleware[],\n initialPlugins: Plugin[]\n): Server['listen'] {\n return async () => {\n // Initialize middleware and plugins\n await initializeComponents(serverInstance, initialMiddleware, initialPlugins);\n\n // Use the functional manager\n await serverInstance.pluginManager.initializePlugins(serverInstance);\n\n // Start the server\n await startServer(serverInstance, validatedOptions);\n\n await serverInstance.pluginManager.onServerStart(serverInstance, serverInstance.server);\n\n // Setup signal handlers and emit events\n setupServerLifecycle(serverInstance);\n\n return serverInstance;\n };\n}\n\n/**\n * Initializes middleware and plugins\n */\nasync function initializeComponents(\n serverInstance: Server,\n initialMiddleware: Middleware[],\n initialPlugins: Plugin[]\n): Promise<void> {\n // Initialize middleware from options\n for (const mw of initialMiddleware) {\n serverInstance.use(mw);\n }\n\n // Register plugins from options\n for (const p of initialPlugins) {\n await serverInstance.register(p);\n }\n}\n\n/**\n * Sets up server lifecycle (signal handlers, events)\n */\nfunction setupServerLifecycle(serverInstance: Server): void {\n // Register signal handlers for graceful shutdown\n const signalHandlers = registerSignalHandlers(() => serverInstance.close());\n\n // Store handlers to unregister when server closes\n serverInstance._signalHandlers = signalHandlers;\n\n // Emit started event\n serverInstance.events.emit('started');\n}\n\n/**\n * Creates the server close method\n */\nfunction createCloseMethod(serverInstance: Server): Server['close'] {\n return async (stopOptions?: StopOptions) => {\n if (!serverInstance.server) {\n return;\n }\n\n // Prepare options\n const options: StopOptions = { ...stopOptions };\n\n // Unregister signal handlers if they exist\n if (serverInstance._signalHandlers) {\n serverInstance._signalHandlers.unregister();\n delete serverInstance._signalHandlers;\n }\n\n // Call stopServer with the server instance\n await stopServer(serverInstance, options);\n };\n}\n\n/**\n * Creates the server use method for adding middleware\n */\nfunction createUseMethod(serverInstance: Server): Server['use'] {\n return middleware => {\n const middlewareArray = Array.isArray(middleware) ? middleware : [middleware];\n serverInstance.middleware.push(...middlewareArray);\n return serverInstance;\n };\n}\n\n/**\n * Creates the server register method for plugins\n */\nfunction createRegisterMethod(serverInstance: Server): Server['register'] {\n return async plugin => {\n validatePlugin(plugin);\n serverInstance.plugins.push(plugin);\n await plugin.register(serverInstance);\n return serverInstance;\n };\n}\n\n/**\n * Creates a BlaizeJS server instance\n */\nexport function create(options: ServerOptionsInput = {}): Server {\n // Create and validate options\n const mergedOptions = createServerOptions(options);\n\n let validatedOptions: ServerOptions;\n try {\n validatedOptions = validateServerOptions(mergedOptions);\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to create server: ${error.message}`);\n }\n throw new Error(`Failed to create server: ${String(error)}`);\n }\n\n // Extract options and prepare initial components\n const { port, host, middleware, plugins } = validatedOptions;\n // TODO: create registries to manage middleware and plugins\n const initialMiddleware = Array.isArray(middleware) ? [...middleware] : [];\n const initialPlugins = Array.isArray(plugins) ? [...plugins] : [];\n\n // Initialize core server components\n const contextStorage = new AsyncLocalStorage<Context>();\n const router = createRouter({\n routesDir: validatedOptions.routesDir,\n watchMode: process.env.NODE_ENV === 'development',\n });\n // Create plugin lifecycle manager\n const pluginManager = createPluginLifecycleManager({\n debug: process.env.NODE_ENV === 'development',\n continueOnError: true,\n });\n const events = new EventEmitter();\n\n // Create server instance with minimal properties\n const serverInstance: Server = {\n server: null as any,\n port,\n host,\n context: contextStorage,\n events,\n plugins: [],\n middleware: [],\n _signalHandlers: { unregister: () => {} },\n use: () => serverInstance,\n register: async () => serverInstance,\n listen: async () => serverInstance,\n close: async () => {},\n router,\n pluginManager,\n };\n\n // Add methods to the server instance\n serverInstance.listen = createListenMethod(\n serverInstance,\n validatedOptions,\n initialMiddleware,\n initialPlugins\n );\n serverInstance.close = createCloseMethod(serverInstance);\n serverInstance.use = createUseMethod(serverInstance);\n serverInstance.register = createRegisterMethod(serverInstance);\n\n return serverInstance;\n}\n","import * as fs from 'node:fs';\nimport * as http from 'node:http';\nimport * as http2 from 'node:http2';\n\nimport { generateDevCertificates } from './dev-certificate';\nimport { createRequestHandler } from './request-handler';\n\nimport type { Server, Http2Options, ServerOptions } from '@blaize-types/server';\n\n// Extract certificate handling to a separate function\nasync function prepareCertificates(\n http2Options: Http2Options\n): Promise<{ keyFile?: string; certFile?: string }> {\n // Not using HTTP/2? No certificates needed\n if (!http2Options.enabled) {\n return {};\n }\n\n const { keyFile, certFile } = http2Options;\n\n // If certificates are missing and in development, generate them\n const isDevMode = process.env.NODE_ENV === 'development';\n const certificatesMissing = !keyFile || !certFile;\n\n if (certificatesMissing && isDevMode) {\n const devCerts = await generateDevCertificates();\n return devCerts;\n }\n\n // If certificates are still missing, throw error\n if (certificatesMissing) {\n throw new Error(\n 'HTTP/2 requires SSL certificates. Provide keyFile and certFile in http2 options. ' +\n 'In development, set NODE_ENV=development to generate them automatically.'\n );\n }\n\n return { keyFile, certFile };\n}\n\n// Create server based on protocol\nfunction createServerInstance(\n isHttp2: boolean,\n certOptions: { keyFile?: string; certFile?: string }\n): http.Server | http2.Http2SecureServer {\n if (!isHttp2) {\n return http.createServer();\n }\n\n // Create HTTP/2 server options\n const http2ServerOptions: http2.SecureServerOptions = {\n allowHTTP1: true, // Allow fallback to HTTP/1.1\n };\n\n // Read certificate files\n try {\n if (certOptions.keyFile) {\n http2ServerOptions.key = fs.readFileSync(certOptions.keyFile);\n }\n if (certOptions.certFile) {\n http2ServerOptions.cert = fs.readFileSync(certOptions.certFile);\n }\n } catch (err) {\n throw new Error(\n `Failed to read certificate files: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n\n return http2.createSecureServer(http2ServerOptions);\n}\n\n// Start listening on the specified port and host\nfunction listenOnPort(\n server: http.Server | http2.Http2SecureServer,\n port: number,\n host: string,\n isHttp2: boolean\n): Promise<void> {\n return new Promise((resolve, reject) => {\n server.listen(port, host, () => {\n const protocol = isHttp2 ? 'https' : 'http';\n const url = `${protocol}://${host}:${port}`;\n console.log(`\n🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥\n\n ⚡ BlaizeJS DEVELOPMENT SERVER HOT AND READY ⚡\n \n 🚀 Server: ${url}\n 🔥 Hot Reload: Enabled\n 🛠️ Mode: Development\n \n Time to build something amazing! 🚀\n\n🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥\n`);\n resolve();\n });\n\n server.on('error', err => {\n console.error('Server error:', err);\n reject(err);\n });\n });\n}\n\nasync function initializePlugins(serverInstance: Server): Promise<void> {\n for (const plugin of serverInstance.plugins) {\n if (typeof plugin.initialize === 'function') {\n await plugin.initialize(serverInstance);\n }\n }\n}\n\n// Main server start function - now with much lower complexity\nexport async function startServer(\n serverInstance: Server,\n serverOptions: ServerOptions\n): Promise<void> {\n // Server already running? Do nothing.\n if (serverInstance.server) {\n return;\n }\n\n try {\n // Get effective port and host\n const port = serverOptions.port;\n const host = serverOptions.host;\n\n // Initialize all registered plugins\n await initializePlugins(serverInstance);\n\n // Determine if using HTTP/2\n const http2Options = serverOptions.http2 || { enabled: true };\n const isHttp2 = !!http2Options.enabled;\n\n // Prepare certificates if needed\n const certOptions = await prepareCertificates(http2Options);\n\n // Update the server options if we generated certificates\n if (serverOptions.http2 && certOptions.keyFile && certOptions.certFile) {\n serverOptions.http2.keyFile = certOptions.keyFile;\n serverOptions.http2.certFile = certOptions.certFile;\n }\n\n // Create the server instance\n const server = createServerInstance(isHttp2, certOptions);\n\n // Store the server in the instance\n serverInstance.server = server;\n\n // Update server instance properties\n serverInstance.port = port;\n serverInstance.host = host;\n\n // Configure request handling\n const requestHandler = createRequestHandler(serverInstance);\n server.on('request', requestHandler);\n\n // Start listening\n await listenOnPort(server, port, host, isHttp2);\n } catch (error) {\n console.error('Failed to start server:', error);\n throw error;\n }\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport * as selfsigned from 'selfsigned';\n\nexport interface DevCertificates {\n keyFile: string;\n certFile: string;\n}\n\nexport async function generateDevCertificates(): Promise<DevCertificates> {\n const certDir = path.join(process.cwd(), '.blaizejs', 'certs');\n const keyPath = path.join(certDir, 'dev.key');\n const certPath = path.join(certDir, 'dev.cert');\n \n // Check if certificates already exist\n if (fs.existsSync(keyPath) && fs.existsSync(certPath)) {\n return {\n keyFile: keyPath,\n certFile: certPath\n };\n }\n \n // Create directory if it doesn't exist\n if (!fs.existsSync(certDir)) {\n fs.mkdirSync(certDir, { recursive: true });\n }\n \n // Generate self-signed certificate\n const attrs = [{ name: 'commonName', value: 'localhost' }];\n const options = {\n days: 365,\n algorithm: 'sha256',\n keySize: 2048,\n extensions: [\n { name: 'basicConstraints', cA: true },\n {\n name: 'keyUsage',\n keyCertSign: true,\n digitalSignature: true,\n nonRepudiation: true,\n keyEncipherment: true,\n dataEncipherment: true\n },\n {\n name: 'extKeyUsage',\n serverAuth: true,\n clientAuth: true\n },\n {\n name: 'subjectAltName',\n altNames: [\n { type: 2, value: 'localhost' },\n { type: 7, ip: '127.0.0.1' }\n ]\n }\n ]\n };\n \n // Generate the certificates\n const pems = selfsigned.generate(attrs, options);\n \n // Write the key and certificate to files\n fs.writeFileSync(keyPath, Buffer.from(pems.private, 'utf-8'));\n fs.writeFileSync(certPath, Buffer.from(pems.cert, 'utf-8'));\n \n console.log(`\\n🔒 Generated self-signed certificates for development at ${certDir}\\n`);\n \n return {\n keyFile: keyPath,\n certFile: certPath\n };\n}","export class ResponseSentError extends Error {\n constructor(message: string = '❌ Response has already been sent') {\n super(message);\n this.name = 'ResponseSentError';\n }\n}\n\nexport class ResponseSentHeaderError extends ResponseSentError {\n constructor(message: string = 'Cannot set header after response has been sent') {\n super(message);\n }\n}\n\nexport class ResponseSentContentError extends ResponseSentError {\n constructor(message: string = 'Cannot set content type after response has been sent') {\n super(message);\n }\n}\n\nexport class ParseUrlError extends ResponseSentError {\n constructor(message: string = 'Invalide URL') {\n super(message);\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\n\nimport type { Context, QueryParams, State, UnknownFunction } from '@blaize-types/context';\n\n/**\n * AsyncLocalStorage instance for storing request context\n */\nexport const contextStorage = new AsyncLocalStorage<Context>();\n\n/**\n * Returns the current context from AsyncLocalStorage\n */\nexport function getContext<S extends State = State, TBody = unknown, TQuery = QueryParams>():\n | Context<S, TBody, TQuery>\n | undefined {\n return contextStorage.getStore() as Context<S, TBody, TQuery> | undefined;\n}\n\n/**\n * Wraps a callback function with a context\n */\nexport function runWithContext<T>(\n context: Context,\n callback: () => T | Promise<T>\n): T | Promise<T> {\n return contextStorage.run(context, callback);\n}\n\n/**\n * Middleware function that ensures a context is available in AsyncLocalStorage\n */\nexport async function contextMiddleware(\n context: Context,\n next: () => Promise<void>\n): Promise<void> {\n return runWithContext(context, next);\n}\n\n/**\n * Utility to check if code is running within a context\n */\nexport function hasContext(): boolean {\n return contextStorage.getStore() !== undefined;\n}\n\n/**\n * Creates a function that will run with the current context\n *\n * @param fn The function to bind to the current context\n * @returns A function that will execute with the bound context\n */\nexport function bindContext<TFunction extends UnknownFunction>(fn: TFunction): TFunction {\n const context = getContext();\n if (!context) {\n return fn;\n }\n\n // Using function instead of arrow function to preserve 'this'\n return function (this: unknown, ...args: Parameters<TFunction>): ReturnType<TFunction> {\n return runWithContext(context, () => fn.apply(this, args)) as ReturnType<TFunction>;\n } as TFunction;\n}\n","import { randomUUID } from 'node:crypto';\nimport { createWriteStream, type WriteStream } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { Readable } from 'node:stream';\n\nimport { extractBoundary, parseContentDisposition, parseContentType } from './utils';\n\nimport type { UnifiedRequest } from '@blaize-types/context';\nimport type { UploadedFile, MultipartData, ParseOptions, ParserState } from '@blaize-types/upload';\n\n// Default options with sensible defaults\nconst DEFAULT_OPTIONS: Required<ParseOptions> = {\n maxFileSize: 10 * 1024 * 1024, // 10MB\n maxFiles: 10,\n maxFieldSize: 1 * 1024 * 1024, // 1MB\n allowedMimeTypes: [],\n allowedExtensions: [],\n strategy: 'stream',\n tempDir: tmpdir(),\n computeHash: false,\n};\n\n/**\n * Create initial parser state\n */\nfunction createParserState(boundary: string, options: Partial<ParseOptions> = {}): ParserState {\n return {\n boundary: Buffer.from(`--${boundary}`),\n options: { ...DEFAULT_OPTIONS, ...options },\n fields: new Map(),\n files: new Map(),\n buffer: Buffer.alloc(0),\n stage: 'boundary',\n currentHeaders: '',\n currentField: null,\n currentFilename: undefined,\n currentMimetype: 'application/octet-stream',\n currentContentLength: 0,\n fileCount: 0,\n fieldCount: 0,\n currentBufferChunks: [],\n currentStream: null,\n currentTempPath: null,\n currentWriteStream: null,\n streamController: null,\n cleanupTasks: [],\n // Track validation state\n hasFoundValidBoundary: false,\n hasProcessedAnyPart: false,\n isFinished: false,\n };\n}\n\n/**\n * Process a chunk of data through the parser state machine\n */\nasync function processChunk(state: ParserState, chunk: Buffer): Promise<ParserState> {\n const newBuffer = Buffer.concat([state.buffer, chunk]);\n let currentState = { ...state, buffer: newBuffer };\n\n // Process buffer until no more progress can be made\n while (currentState.buffer.length > 0 && !currentState.isFinished) {\n const nextState = await processCurrentStage(currentState);\n if (nextState === currentState) break; // No progress made, need more data\n currentState = nextState;\n }\n\n return currentState;\n}\n\n/**\n * Process current stage of parsing\n */\nasync function processCurrentStage(state: ParserState): Promise<ParserState> {\n switch (state.stage) {\n case 'boundary':\n return processBoundary(state);\n case 'headers':\n return processHeaders(state);\n case 'content':\n return processContent(state);\n default: {\n const { InternalServerError } = await import('../errors/internal-server-error');\n throw new InternalServerError(`Invalid parser stage`, {\n operation: state.stage,\n });\n }\n }\n}\n\n/**\n * Process boundary detection\n */\nfunction processBoundary(state: ParserState): ParserState {\n const boundaryIndex = state.buffer.indexOf(state.boundary);\n if (boundaryIndex === -1) return state;\n\n // Mark that we found at least one boundary\n const hasFoundValidBoundary = true;\n\n // Consume boundary and check for end\n let buffer = state.buffer.subarray(boundaryIndex + state.boundary.length);\n\n // Check for end boundary (-- after boundary)\n if (buffer.length >= 2 && buffer.subarray(0, 2).equals(Buffer.from('--'))) {\n return {\n ...state,\n buffer,\n hasFoundValidBoundary,\n isFinished: true,\n stage: 'boundary',\n };\n }\n\n // Skip CRLF after boundary\n if (buffer.length >= 2 && buffer.subarray(0, 2).equals(Buffer.from('\\r\\n'))) {\n buffer = buffer.subarray(2);\n }\n\n return {\n ...state,\n buffer,\n hasFoundValidBoundary,\n stage: 'headers',\n currentHeaders: '',\n };\n}\n\n/**\n * Process headers section\n */\nasync function processHeaders(state: ParserState): Promise<ParserState> {\n const headerEnd = state.buffer.indexOf('\\r\\n\\r\\n');\n if (headerEnd === -1) return state;\n\n const headers = state.buffer.subarray(0, headerEnd).toString('utf8');\n const buffer = state.buffer.subarray(headerEnd + 4);\n\n const disposition = parseContentDisposition(headers);\n if (!disposition) {\n // ✅ HTTP 400 - Bad Request for malformed headers\n const { ValidationError } = await import('../errors/validation-error');\n throw new ValidationError('Missing or invalid Content-Disposition header');\n }\n\n const mimetype = parseContentType(headers);\n const isFile = disposition.filename !== undefined;\n\n // Validation\n if (isFile && state.fileCount >= state.options.maxFiles) {\n const { PayloadTooLargeError } = await import('../errors/payload-too-large-error');\n throw new PayloadTooLargeError('Too many files in upload', {\n fileCount: state.fileCount + 1,\n maxFiles: state.options.maxFiles,\n filename: disposition.filename,\n });\n }\n\n if (\n isFile &&\n state.options.allowedMimeTypes.length > 0 &&\n !state.options.allowedMimeTypes.includes(mimetype)\n ) {\n const { UnsupportedMediaTypeError } = await import('../errors/unsupported-media-type-error');\n throw new UnsupportedMediaTypeError('File type not allowed', {\n receivedMimeType: mimetype,\n allowedMimeTypes: state.options.allowedMimeTypes,\n filename: disposition.filename,\n });\n }\n\n return {\n ...state,\n buffer,\n stage: 'content',\n currentHeaders: headers,\n currentField: disposition.name,\n currentFilename: disposition.filename,\n currentMimetype: mimetype,\n currentContentLength: 0,\n fileCount: isFile ? state.fileCount + 1 : state.fileCount,\n fieldCount: isFile ? state.fieldCount : state.fieldCount + 1,\n currentBufferChunks: [],\n };\n}\n\n/**\n * Process content section\n */\nasync function processContent(state: ParserState): Promise<ParserState> {\n const nextBoundaryIndex = state.buffer.indexOf(state.boundary);\n\n let contentChunk: Buffer;\n let isComplete = false;\n let buffer = state.buffer;\n\n if (nextBoundaryIndex === -1) {\n // No boundary found, process safely\n const safeLength = Math.max(0, state.buffer.length - state.boundary.length);\n if (safeLength === 0) return state; // Need more data\n\n contentChunk = state.buffer.subarray(0, safeLength);\n buffer = state.buffer.subarray(safeLength);\n } else {\n // Found boundary, process content before it (minus CRLF)\n const contentEnd = Math.max(0, nextBoundaryIndex - 2);\n contentChunk = state.buffer.subarray(0, contentEnd);\n buffer = state.buffer.subarray(nextBoundaryIndex);\n isComplete = true;\n }\n\n let updatedState = { ...state, buffer };\n\n if (contentChunk.length > 0) {\n updatedState = await processContentChunk(updatedState, contentChunk);\n }\n\n if (isComplete) {\n updatedState = await finalizeCurrentPart(updatedState);\n updatedState = {\n ...updatedState,\n stage: 'boundary' as const,\n hasProcessedAnyPart: true, // Mark that we've processed at least one part\n };\n }\n\n return updatedState;\n}\n\n/**\n * Process a chunk of content data\n */\nasync function processContentChunk(state: ParserState, chunk: Buffer): Promise<ParserState> {\n const newContentLength = state.currentContentLength + chunk.length;\n\n // Size validation\n const maxSize =\n state.currentFilename !== undefined ? state.options.maxFileSize : state.options.maxFieldSize;\n\n if (newContentLength > maxSize) {\n const isFile = state.currentFilename !== undefined;\n const { PayloadTooLargeError } = await import('../errors/payload-too-large-error');\n const payloadErrorDetals = state.currentField\n ? {\n contentType: isFile ? 'file' : 'field',\n currentSize: newContentLength,\n maxSize,\n field: state.currentField,\n filename: state.currentFilename,\n }\n : {\n contentType: isFile ? 'file' : 'field',\n currentSize: newContentLength,\n maxSize,\n filename: state.currentFilename,\n };\n throw new PayloadTooLargeError(\n `${isFile ? 'File' : 'Field'} size exceeds limit`,\n payloadErrorDetals\n );\n }\n\n if (state.currentFilename !== undefined) {\n return processFileChunk(state, chunk, newContentLength);\n } else {\n return {\n ...state,\n currentContentLength: newContentLength,\n currentBufferChunks: [...state.currentBufferChunks, chunk],\n };\n }\n}\n\n/**\n * Process file chunk based on strategy\n */\nasync function processFileChunk(\n state: ParserState,\n chunk: Buffer,\n newContentLength: number\n): Promise<ParserState> {\n switch (state.options.strategy) {\n case 'memory':\n return {\n ...state,\n currentContentLength: newContentLength,\n currentBufferChunks: [...state.currentBufferChunks, chunk],\n };\n\n case 'stream':\n if (state.streamController) {\n state.streamController.enqueue(chunk);\n }\n return { ...state, currentContentLength: newContentLength };\n\n case 'temp':\n if (state.currentWriteStream) {\n await writeToStream(state.currentWriteStream, chunk);\n }\n return { ...state, currentContentLength: newContentLength };\n\n default: {\n const { ValidationError } = await import('../errors/validation-error');\n throw new ValidationError(`Invalid parsing strategy`);\n // TODO: create new error type to support \"strategy\" + \"supportedStrategies\"\n // throw new ValidationError(`Invalid parsing strategy`, {\n // strategy: state.options.strategy,\n // supportedStrategies: ['memory', 'stream', 'temp'],\n // });\n }\n }\n}\n\n/**\n * Initialize file processing for current part\n */\nasync function initializeFileProcessing(state: ParserState): Promise<ParserState> {\n if (state.currentFilename === undefined) return state;\n\n switch (state.options.strategy) {\n case 'memory':\n return { ...state, currentBufferChunks: [] };\n\n case 'stream': {\n let streamController: ReadableStreamDefaultController<Uint8Array> | null = null;\n const stream = new ReadableStream<Uint8Array>({\n start: controller => {\n streamController = controller;\n },\n });\n\n return {\n ...state,\n currentStream: stream as any, // Type cast for Node.js compatibility\n streamController,\n };\n }\n\n case 'temp': {\n const tempPath = join(state.options.tempDir, `upload-${randomUUID()}`);\n const writeStream = createWriteStream(tempPath);\n const cleanupTask = async () => {\n try {\n const { unlink } = await import('node:fs/promises');\n await unlink(tempPath);\n } catch (error) {\n console.warn(`Failed to cleanup temp file: ${tempPath}`, error);\n }\n };\n\n return {\n ...state,\n currentTempPath: tempPath,\n currentWriteStream: writeStream,\n cleanupTasks: [...state.cleanupTasks, cleanupTask],\n };\n }\n\n default: {\n const { ValidationError } = await import('../errors/validation-error');\n throw new ValidationError(`Invalid file processing strategy`);\n // throw new ValidationError(`Invalid file processing strategy`, {\n // strategy: state.options.strategy,\n // });\n }\n }\n}\n\n/**\n * Finalize current part and add to collections\n */\nasync function finalizeCurrentPart(state: ParserState): Promise<ParserState> {\n if (!state.currentField) return resetCurrentPart(state);\n\n if (state.currentFilename !== undefined) {\n return finalizeFile(state);\n } else {\n return finalizeField(state);\n }\n}\n\n/**\n * Finalize file processing\n */\nasync function finalizeFile(state: ParserState): Promise<ParserState> {\n if (!state.currentField || state.currentFilename === undefined) {\n return resetCurrentPart(state);\n }\n\n let stream: Readable;\n let buffer: Buffer | undefined;\n let tempPath: string | undefined;\n\n switch (state.options.strategy) {\n case 'memory':\n buffer = Buffer.concat(state.currentBufferChunks);\n stream = Readable.from(buffer);\n break;\n\n case 'stream':\n if (state.streamController) {\n state.streamController.close();\n }\n stream = state.currentStream!;\n break;\n\n case 'temp':\n if (state.currentWriteStream) {\n await closeStream(state.currentWriteStream);\n }\n tempPath = state.currentTempPath!;\n stream = Readable.from(Buffer.alloc(0)); // Placeholder\n break;\n\n default: {\n // ✅ HTTP 400 - Bad Request for invalid strategy\n const { ValidationError } = await import('../errors/validation-error');\n throw new ValidationError(`Invalid file finalization strategy`);\n // throw new ValidationError(`Invalid file finalization strategy`, {\n // strategy: state.options.strategy,\n // });\n }\n }\n\n const file: UploadedFile = {\n filename: state.currentFilename,\n fieldname: state.currentField,\n mimetype: state.currentMimetype,\n size: state.currentContentLength,\n stream,\n buffer,\n tempPath,\n };\n\n const updatedFiles = addToCollection(state.files, state.currentField, file);\n\n return {\n ...resetCurrentPart(state),\n files: updatedFiles,\n };\n}\n\n/**\n * Finalize field processing\n */\nfunction finalizeField(state: ParserState): ParserState {\n if (!state.currentField) return resetCurrentPart(state);\n\n const value = Buffer.concat(state.currentBufferChunks).toString('utf8');\n const updatedFields = addToCollection(state.fields, state.currentField, value);\n\n return {\n ...resetCurrentPart(state),\n fields: updatedFields,\n };\n}\n\n/**\n * Reset current part state\n */\nfunction resetCurrentPart(state: ParserState): ParserState {\n return {\n ...state,\n currentField: null,\n currentFilename: undefined,\n currentContentLength: 0,\n currentBufferChunks: [],\n currentStream: null,\n streamController: null,\n currentTempPath: null,\n currentWriteStream: null,\n };\n}\n\n/**\n * Add item to collection immutably\n */\nfunction addToCollection<T>(collection: Map<string, T[]>, key: string, value: T): Map<string, T[]> {\n const newCollection = new Map(collection);\n const existing = newCollection.get(key) || [];\n newCollection.set(key, [...existing, value]);\n return newCollection;\n}\n\n/**\n * Finalize parsing and return results\n */\nasync function finalize(state: ParserState): Promise<MultipartData> {\n // Validate that we found valid multipart data\n if (!state.hasFoundValidBoundary) {\n const { ValidationError } = await import('../errors/validation-error');\n throw new ValidationError('No valid multipart boundary found');\n // throw new ValidationError('No valid multipart boundary found', {\n // errorType: 'invalid_multipart',\n // reason: 'Missing or malformed boundary markers',\n // });`\n }\n\n // If we found boundaries but didn't process any parts, it's empty/invalid\n if (state.hasFoundValidBoundary && !state.hasProcessedAnyPart) {\n const { ValidationError } = await import('../errors/validation-error');\n throw new ValidationError('Empty multipart request');\n // throw new ValidationError('Empty multipart request', {\n // errorType: 'empty_multipart',\n // reason: 'Valid boundaries found but no data parts processed',\n // });\n }\n\n const fields: Record<string, string | string[]> = {};\n for (const [key, values] of state.fields.entries()) {\n fields[key] = values.length === 1 ? values[0]! : values;\n }\n\n const files: Record<string, UploadedFile | UploadedFile[]> = {};\n for (const [key, fileList] of state.files.entries()) {\n files[key] = fileList.length === 1 ? fileList[0]! : fileList;\n }\n\n return { fields, files };\n}\n\n/**\n * Cleanup resources\n */\nasync function cleanup(state: ParserState): Promise<void> {\n // Execute all cleanup tasks\n await Promise.allSettled(state.cleanupTasks.map(task => task()));\n\n // Close any open streams\n if (state.streamController) {\n state.streamController.close();\n }\n\n if (state.currentWriteStream) {\n await closeStream(state.currentWriteStream);\n }\n}\n\n// Helper functions\nasync function writeToStream(stream: WriteStream, chunk: Buffer): Promise<void> {\n return new Promise((resolve, reject) => {\n stream.write(chunk, error => {\n if (error) reject(error);\n else resolve();\n });\n });\n}\n\nasync function closeStream(stream: WriteStream): Promise<void> {\n return new Promise(resolve => {\n stream.end(() => resolve());\n });\n}\n\n/**\n * Main parsing function (functional interface)\n */\nexport async function parseMultipartRequest(\n request: UnifiedRequest,\n options: Partial<ParseOptions> = {}\n): Promise<MultipartData> {\n const contentType = (request.headers['content-type'] as string) || '';\n const boundary = extractBoundary(contentType);\n\n if (!boundary) {\n const { UnsupportedMediaTypeError } = await import('../errors/unsupported-media-type-error');\n throw new UnsupportedMediaTypeError('Missing boundary in multipart content-type', {\n receivedContentType: contentType,\n expectedFormat: 'multipart/form-data; boundary=...',\n });\n }\n\n let state = createParserState(boundary, options);\n\n // Initialize file processing if needed\n if (state.currentFilename !== undefined) {\n state = await initializeFileProcessing(state);\n }\n\n try {\n // Process request stream\n for await (const chunk of request) {\n state = await processChunk(state, chunk as Buffer);\n }\n\n return finalize(state);\n } finally {\n await cleanup(state);\n }\n}\n","// Hoisted regex patterns\nconst BOUNDARY_REGEX = /boundary=([^;]+)/i;\nconst CONTENT_DISPOSITION_REGEX =\n /Content-Disposition:\\s*form-data;\\s*name=\"([^\"]+)\"(?:;[\\s\\r\\n]*filename=\"([^\"]*)\")?/i;\nconst CONTENT_TYPE_REGEX = /Content-Type:\\s*([^\\r\\n]+)/i;\nconst MULTIPART_REGEX = /multipart\\/form-data/i;\n\n/**\n * Extract boundary from Content-Type header\n */\nexport function extractBoundary(contentType: string): string | null {\n const match = contentType.match(BOUNDARY_REGEX);\n if (!match || !match[1]) return null;\n\n let boundary = match[1].trim();\n if (boundary.startsWith('\"') && boundary.endsWith('\"')) {\n boundary = boundary.slice(1, -1);\n }\n\n return boundary || null;\n}\n\n/**\n * Parse Content-Disposition header\n */\nexport function parseContentDisposition(\n headers: string\n): { name: string; filename?: string } | null {\n const match = headers.match(CONTENT_DISPOSITION_REGEX);\n if (!match || !match[1]) return null;\n\n return {\n name: match[1],\n filename: match[2] !== undefined ? match[2] : undefined,\n };\n}\n\n/**\n * Parse Content-Type header\n */\nexport function parseContentType(headers: string): string {\n const match = headers.match(CONTENT_TYPE_REGEX);\n return match && match[1]?.trim() ? match[1].trim() : 'application/octet-stream';\n}\n\n/**\n * Check if content type is multipart\n */\nexport function isMultipartContent(contentType: string): boolean {\n return MULTIPART_REGEX.test(contentType);\n}\n","import {\n ParseUrlError,\n ResponseSentContentError,\n ResponseSentError,\n ResponseSentHeaderError,\n} from './errors';\nimport { hasContext, getContext } from './store';\nimport { parseMultipartRequest } from '../upload/multipart-parser';\nimport { isMultipartContent } from '../upload/utils';\n\nimport type {\n Context,\n ContextOptions,\n MultipartLimits,\n QueryParams,\n RequestParams,\n State,\n StreamOptions,\n UnifiedRequest,\n UnifiedResponse,\n} from '@blaize-types/context';\nimport type { BodyParseError } from '@blaize-types/errors';\n\nconst CONTENT_TYPE_HEADER = 'Content-Type';\n\nconst DEFAULT_BODY_LIMITS = {\n json: 512 * 1024, // 512KB - Most APIs should be much smaller\n form: 1024 * 1024, // 1MB - Reasonable for form submissions\n text: 5 * 1024 * 1024, // 5MB - Documents, logs, code files\n multipart: {\n maxFileSize: 50 * 1024 * 1024, // 50MB per file\n maxTotalSize: 100 * 1024 * 1024, // 100MB total request\n maxFiles: 10,\n maxFieldSize: 1024 * 1024, // 1MB for form fields\n },\n raw: 10 * 1024 * 1024, // 10MB for unknown content types\n};\n\n/**\n * Parse URL and extract path and query parameters using modern URL API\n */\nfunction parseRequestUrl(req: UnifiedRequest): {\n path: string;\n url: URL | null;\n query: QueryParams;\n} {\n const originalUrl = (req as any).url || '/';\n\n // Construct full URL for parsing\n const host = req.headers.host || 'localhost';\n const protocol = req.socket && (req.socket as any).encrypted ? 'https' : 'http';\n const fullUrl = `${protocol}://${host}${originalUrl.startsWith('/') ? '' : '/'}${originalUrl}`;\n try {\n const url = new URL(fullUrl);\n\n // Extract path\n const path = url.pathname;\n\n // Parse query parameters using URLSearchParams\n const query: QueryParams = {};\n url.searchParams.forEach((value, key) => {\n // Handle array parameters (key=value1&key=value2)\n if (query[key] !== undefined) {\n if (Array.isArray(query[key])) {\n (query[key] as string[]).push(value);\n } else {\n query[key] = [query[key] as string, value];\n }\n } else {\n query[key] = value;\n }\n });\n\n return { path, url, query };\n } catch (error) {\n // Fallback for invalid URLs\n console.warn(`Invalid URL: ${fullUrl}`, error);\n throw new ParseUrlError(`Invalid URL: ${fullUrl}`);\n }\n}\n\n/**\n * Determine if the request is using HTTP/2\n */\nfunction isHttp2Request(req: UnifiedRequest): boolean {\n // Check for HTTP/2 specific properties\n return 'stream' in req || ('httpVersionMajor' in req && (req as any).httpVersionMajor === 2);\n}\n\n/**\n * Get the HTTP protocol (http or https)\n */\nfunction getProtocol(req: UnifiedRequest): string {\n // Check for encrypted socket\n const encrypted = req.socket && (req.socket as any).encrypted;\n // Check for X-Forwarded-Proto header (common in proxy environments)\n const forwardedProto = req.headers['x-forwarded-proto'];\n\n if (forwardedProto) {\n if (Array.isArray(forwardedProto)) {\n // Handle array of header values (uncommon but possible)\n return forwardedProto[0]?.split(',')[0]?.trim() || 'http';\n } else {\n // Handle string header value (typical case)\n return forwardedProto.split(',')[0]?.trim() || 'http';\n }\n }\n\n // Default protocol based on socket encryption\n return encrypted ? 'https' : 'http';\n}\n\n/**\n * Create a new context object for a request/response cycle\n */\nexport async function createContext<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n res: UnifiedResponse,\n options: ContextOptions = {}\n): Promise<Context<State, TBody, TQuery>> {\n // Extract basic request information\n const { path, url, query } = parseRequestUrl(req);\n const method = req.method || 'GET';\n const isHttp2 = isHttp2Request(req);\n const protocol = getProtocol(req);\n\n // Initialize state\n const params: RequestParams = {};\n const state = { ...(options.initialState || {}) };\n\n // Track response status\n const responseState = { sent: false };\n\n // Create the context object with its components\n const ctx: Context<State, TBody, TQuery> = {\n request: createRequestObject<TBody, TQuery>(req, {\n path,\n url,\n query: query as TQuery,\n params,\n method,\n isHttp2,\n protocol,\n }),\n response: {} as Context<State, TBody, TQuery>['response'],\n state,\n };\n\n ctx.response = createResponseObject(res, responseState, ctx);\n\n // Parse body if requested\n if (options.parseBody) {\n await parseBodyIfNeeded(req, ctx, options);\n }\n\n return ctx;\n}\n\n/**\n * Create the request object portion of the context\n */\nfunction createRequestObject<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n info: {\n path: string;\n url: URL | null;\n query: TQuery;\n params: RequestParams;\n method: string;\n isHttp2: boolean;\n protocol: string;\n }\n): Context<State, TBody, TQuery>['request'] {\n return {\n raw: req,\n ...info,\n header: createRequestHeaderGetter(req),\n headers: createRequestHeadersGetter(req),\n body: undefined as unknown as TBody,\n };\n}\n\n/**\n * Create a function to get a single request header\n */\nfunction createRequestHeaderGetter(req: UnifiedRequest) {\n return (name: string): string | undefined => {\n const value = req.headers[name.toLowerCase()];\n if (Array.isArray(value)) {\n return value.join(', ');\n }\n return value || undefined;\n };\n}\n\n/**\n * Create a function to get multiple request headers\n */\nfunction createRequestHeadersGetter(req: UnifiedRequest) {\n const headerGetter = createRequestHeaderGetter(req);\n\n return (names?: string[]): Record<string, string | undefined> => {\n if (names && Array.isArray(names) && names.length > 0) {\n return names.reduce<Record<string, string | undefined>>((acc, name) => {\n acc[name] = headerGetter(name);\n return acc;\n }, {});\n } else {\n return Object.entries(req.headers).reduce<Record<string, string | undefined>>(\n (acc, [key, value]) => {\n acc[key] = Array.isArray(value) ? value.join(', ') : value || undefined;\n return acc;\n },\n {}\n );\n }\n };\n}\n\n/**\n * Create the response object portion of the context\n */\nfunction createResponseObject<S extends State = State, TBody = unknown, TQuery = QueryParams>(\n res: UnifiedResponse,\n responseState: { sent: boolean },\n ctx: Context<S, TBody, TQuery>\n): Context<S, TBody, TQuery>['response'] {\n return {\n raw: res,\n\n get sent() {\n return responseState.sent;\n },\n\n status: createStatusSetter(res, responseState, ctx),\n header: createHeaderSetter(res, responseState, ctx),\n headers: createHeadersSetter(res, responseState, ctx),\n type: createContentTypeSetter(res, responseState, ctx),\n\n json: createJsonResponder(res, responseState),\n text: createTextResponder(res, responseState),\n html: createHtmlResponder(res, responseState),\n redirect: createRedirectResponder(res, responseState),\n stream: createStreamResponder(res, responseState),\n };\n}\n\n/**\n * Create a function to set response status\n */\nfunction createStatusSetter<S extends State = State, TBody = unknown, TQuery = QueryParams>(\n res: UnifiedResponse,\n responseState: { sent: boolean },\n ctx: Context<S, TBody, TQuery>\n) {\n return function statusSetter(code: number): Context['response'] {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n res.statusCode = code;\n return ctx.response;\n };\n}\n\n/**\n * Create a function to set a response header\n */\nfunction createHeaderSetter<S extends State = State, TBody = unknown, TQuery = QueryParams>(\n res: UnifiedResponse,\n responseState: { sent: boolean },\n ctx: Context<S, TBody, TQuery>\n) {\n return function headerSetter(name: string, value: string) {\n if (responseState.sent) {\n throw new ResponseSentHeaderError();\n }\n res.setHeader(name, value);\n return ctx.response;\n };\n}\n\n/**\n * Create a function to set multiple response headers\n */\nfunction createHeadersSetter<S extends State = State, TBody = unknown, TQuery = QueryParams>(\n res: UnifiedResponse,\n responseState: { sent: boolean },\n ctx: Context<S, TBody, TQuery>\n) {\n return function headersSetter(headers: Record<string, string>) {\n if (responseState.sent) {\n throw new ResponseSentHeaderError();\n }\n for (const [name, value] of Object.entries(headers)) {\n res.setHeader(name, value);\n }\n return ctx.response;\n };\n}\n\n/**\n * Create a function to set content type header\n */\nfunction createContentTypeSetter<S extends State = State, TBody = unknown, TQuery = QueryParams>(\n res: UnifiedResponse,\n responseState: { sent: boolean },\n ctx: Context<S, TBody, TQuery>\n) {\n return function typeSetter(type: string) {\n if (responseState.sent) {\n throw new ResponseSentContentError();\n }\n res.setHeader(CONTENT_TYPE_HEADER, type);\n return ctx.response;\n };\n}\n\n/**\n * Create a function to send JSON response\n */\nfunction createJsonResponder(res: UnifiedResponse, responseState: { sent: boolean }) {\n return function jsonResponder(body: unknown, status?: number) {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n\n if (status !== undefined) {\n res.statusCode = status;\n }\n\n res.setHeader(CONTENT_TYPE_HEADER, 'application/json');\n res.end(JSON.stringify(body));\n responseState.sent = true;\n };\n}\n\n/**\n * Create a function to send text response\n */\nfunction createTextResponder(res: UnifiedResponse, responseState: { sent: boolean }) {\n return function textResponder(body: string, status?: number) {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n\n if (status !== undefined) {\n res.statusCode = status;\n }\n\n res.setHeader(CONTENT_TYPE_HEADER, 'text/plain');\n res.end(body);\n responseState.sent = true;\n };\n}\n\n/**\n * Create a function to send HTML response\n */\nfunction createHtmlResponder(res: UnifiedResponse, responseState: { sent: boolean }) {\n return function htmlResponder(body: string, status?: number) {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n\n if (status !== undefined) {\n res.statusCode = status;\n }\n\n res.setHeader(CONTENT_TYPE_HEADER, 'text/html');\n res.end(body);\n responseState.sent = true;\n };\n}\n\n/**\n * Create a function to send redirect response\n */\nfunction createRedirectResponder(res: UnifiedResponse, responseState: { sent: boolean }) {\n return function redirectResponder(url: string, status = 302) {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n\n res.statusCode = status;\n res.setHeader('Location', url);\n res.end();\n responseState.sent = true;\n };\n}\n\n/**\n * Create a function to stream response\n */\nfunction createStreamResponder(res: UnifiedResponse, responseState: { sent: boolean }) {\n return function streamResponder(readable: NodeJS.ReadableStream, options: StreamOptions = {}) {\n if (responseState.sent) {\n throw new ResponseSentError();\n }\n\n if (options.status !== undefined) {\n res.statusCode = options.status;\n }\n\n if (options.contentType) {\n res.setHeader(CONTENT_TYPE_HEADER, options.contentType);\n }\n\n if (options.headers) {\n for (const [name, value] of Object.entries(options.headers)) {\n res.setHeader(name, value);\n }\n }\n\n // Handle streaming\n readable.pipe(res);\n\n // Mark as sent when the stream ends\n readable.on('end', () => {\n responseState.sent = true;\n });\n\n // Handle errors\n readable.on('error', err => {\n console.error('Stream error:', err);\n if (!responseState.sent) {\n res.statusCode = 500;\n res.end('Stream error');\n responseState.sent = true;\n }\n });\n };\n}\n\n/**\n * Parse request body if enabled in options\n */\nasync function parseBodyIfNeeded<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n ctx: Context<State, TBody, TQuery>,\n options: ContextOptions = {}\n): Promise<void> {\n // Skip parsing for methods that typically don't have bodies\n if (shouldSkipParsing(req.method)) {\n return;\n }\n\n const contentType = req.headers['content-type'] || '';\n const contentLength = parseInt(req.headers['content-length'] || '0', 10);\n\n // Skip if no content\n if (contentLength === 0) {\n return;\n }\n\n const limits = {\n json: options.bodyLimits?.json ?? DEFAULT_BODY_LIMITS.json,\n form: options.bodyLimits?.form ?? DEFAULT_BODY_LIMITS.form,\n text: options.bodyLimits?.text ?? DEFAULT_BODY_LIMITS.text,\n raw: options.bodyLimits?.raw ?? DEFAULT_BODY_LIMITS.raw,\n multipart: {\n maxFileSize:\n options.bodyLimits?.multipart?.maxFileSize ?? DEFAULT_BODY_LIMITS.multipart.maxFileSize,\n maxFiles: options.bodyLimits?.multipart?.maxFiles ?? DEFAULT_BODY_LIMITS.multipart.maxFiles,\n maxFieldSize:\n options.bodyLimits?.multipart?.maxFieldSize ?? DEFAULT_BODY_LIMITS.multipart.maxFieldSize,\n maxTotalSize:\n options.bodyLimits?.multipart?.maxTotalSize ?? DEFAULT_BODY_LIMITS.multipart.maxTotalSize,\n },\n };\n\n try {\n // Apply content-type specific size validation\n if (contentType.includes('application/json')) {\n if (contentLength > limits.json) {\n throw new Error(`JSON body too large: ${contentLength} > ${limits.json} bytes`);\n }\n await parseJsonBody(req, ctx);\n } else if (contentType.includes('application/x-www-form-urlencoded')) {\n if (contentLength > limits.form) {\n throw new Error(`Form body too large: ${contentLength} > ${limits.form} bytes`);\n }\n await parseFormUrlEncodedBody(req, ctx);\n } else if (contentType.includes('text/')) {\n if (contentLength > limits.text) {\n throw new Error(`Text body too large: ${contentLength} > ${limits.text} bytes`);\n }\n await parseTextBody(req, ctx);\n } else if (isMultipartContent(contentType)) {\n // Multipart has its own sophisticated size validation\n await parseMultipartBody(req, ctx, limits.multipart);\n } else {\n // Unknown content type - apply raw limit\n if (contentLength > limits.raw) {\n throw new Error(`Request body too large: ${contentLength} > ${limits.raw} bytes`);\n }\n // Don't parse unknown content types, but allow them through\n return;\n }\n } catch (error) {\n const errorType = contentType.includes('multipart')\n ? 'multipart_parse_error'\n : 'body_read_error';\n setBodyError(ctx, errorType, 'Error reading request body', error);\n }\n}\n\n/**\n * Determine if body parsing should be skipped based on HTTP method\n */\nfunction shouldSkipParsing(method?: string): boolean {\n const skipMethods = ['GET', 'HEAD', 'OPTIONS'];\n return skipMethods.includes(method || 'GET');\n}\n\n/**\n * Parse JSON request body\n */\nasync function parseJsonBody<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n ctx: Context<State, TBody, TQuery>\n): Promise<void> {\n const body = await readRequestBody(req);\n\n if (!body) {\n console.warn('Empty body, skipping JSON parsing');\n return;\n }\n\n // Check if the body is actually \"null\" string\n if (body.trim() === 'null') {\n console.warn('Body is the string \"null\"');\n ctx.request.body = null as TBody;\n return;\n }\n\n try {\n const json = JSON.parse(body);\n ctx.request.body = json as TBody;\n } catch (error) {\n ctx.request.body = null as TBody;\n setBodyError(ctx, 'json_parse_error', 'Invalid JSON in request body', error);\n }\n}\n\n/**\n * Parse URL-encoded form data\n */\nasync function parseFormUrlEncodedBody<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n ctx: Context<State, TBody, TQuery>\n): Promise<void> {\n const body = await readRequestBody(req);\n if (!body) return;\n\n try {\n ctx.request.body = parseUrlEncodedData(body) as TBody;\n } catch (error) {\n ctx.request.body = null as TBody;\n setBodyError(ctx, 'form_parse_error', 'Invalid form data in request body', error);\n }\n}\n\n/**\n * Parse URL-encoded data into an object\n */\nfunction parseUrlEncodedData(body: string): Record<string, string | string[]> {\n const params = new URLSearchParams(body);\n const formData: Record<string, string | string[]> = {};\n\n params.forEach((value, key) => {\n if (formData[key] !== undefined) {\n if (Array.isArray(formData[key])) {\n (formData[key] as string[]).push(value);\n } else {\n formData[key] = [formData[key] as string, value];\n }\n } else {\n formData[key] = value;\n }\n });\n\n return formData;\n}\n\n/**\n * Parse plain text body\n */\nasync function parseTextBody<TBody = null, TQuery = QueryParams>(\n req: UnifiedRequest,\n ctx: Context<State, TBody, TQuery>\n): Promise<void> {\n const body = await readRequestBody(req);\n if (body) {\n ctx.request.body = body as TBody;\n }\n}\n\n/**\n * Parse multipart/form-data request body with improved error handling\n */\nasync function parseMultipartBody<TBody = unknown, TQuery = QueryParams>(\n req: UnifiedRequest,\n ctx: Context<State, TBody, TQuery>,\n multipartLimits: MultipartLimits\n): Promise<void> {\n try {\n const limits = multipartLimits || DEFAULT_BODY_LIMITS.multipart;\n const multipartData = await parseMultipartRequest(req, {\n strategy: 'stream',\n maxFileSize: limits.maxFileSize,\n maxFiles: limits.maxFiles,\n maxFieldSize: limits.maxFieldSize,\n // Could add total size validation here\n });\n\n // Extend context with multipart data (type-safe assignments)\n (ctx.request as any).multipart = multipartData;\n (ctx.request as any).files = multipartData.files;\n\n // Set body to fields for backward compatibility with existing form handling\n ctx.request.body = multipartData.fields as TBody;\n } catch (error) {\n ctx.request.body = null as TBody;\n setBodyError(ctx, 'multipart_parse_error', 'Failed to parse multipart data', error);\n }\n}\n\n/**\n * Set body parsing error in context state with proper typing\n */\nfunction setBodyError<TBody = unknown, TQuery = QueryParams>(\n ctx: Context<State, TBody, TQuery>,\n type: BodyParseError['type'],\n message: string,\n error: unknown\n): void {\n const bodyError: BodyParseError = { type, message, error };\n ctx.state._bodyError = bodyError;\n}\n\n/**\n * Read the entire request body as a string\n */\nasync function readRequestBody(req: UnifiedRequest): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n const chunks: Buffer[] = [];\n\n req.on('data', (chunk: Buffer | string) => {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n });\n\n req.on('end', () => {\n resolve(Buffer.concat(chunks).toString('utf8'));\n });\n\n req.on('error', err => {\n reject(err);\n });\n });\n}\n\n/**\n * Get the current context or throw an error if none exists\n */\nexport function getCurrentContext<\n S extends State = State,\n TBody = unknown,\n TQuery = QueryParams,\n>(): Context<S, TBody, TQuery> {\n const ctx = getContext<S, TBody, TQuery>();\n if (!ctx) {\n throw new Error(\n 'No context found. Ensure this function is called within a request handler, ' +\n 'middleware, or function wrapped with runWithContext().'\n );\n }\n return ctx;\n}\n\n/**\n * Check if we're currently in a request context\n */\nexport function isInRequestContext(): boolean {\n return hasContext();\n}\n","/**\n * NotFoundError class for resource not found errors\n *\n * This error is thrown when a requested resource cannot be found.\n * It provides context about what resource was being looked for and how.\n */\n\nimport { BlaizeError, ErrorType } from '@blaize-types/errors';\n\nimport { getCurrentCorrelationId } from './correlation';\n\nimport type { NotFoundErrorDetails } from '@blaize-types/errors';\n/**\n * Error thrown when a requested resource cannot be found\n *\n * Automatically sets HTTP status to 404 and provides context\n * about the missing resource for better debugging and user experience.\n *\n * @example Basic usage:\n * ```typescript\n * throw new NotFoundError('User not found');\n * ```\n *\n * @example With resource context:\n * ```typescript\n * throw new NotFoundError('User not found', {\n * resourceType: 'User',\n * resourceId: 'user-123',\n * suggestion: 'Check if the user ID is correct'\n * });\n * ```\n *\n * @example API endpoint not found:\n * ```typescript\n * throw new NotFoundError('Endpoint not found', {\n * path: '/api/v1/unknown',\n * method: 'GET',\n * suggestion: 'Check the API documentation'\n * });\n * ```\n */\nexport class NotFoundError extends BlaizeError<NotFoundErrorDetails> {\n /**\n * Creates a new NotFoundError instance\n *\n * @param title - Human-readable error message\n * @param details - Optional context about the missing resource\n * @param correlationId - Optional correlation ID (uses current context if not provided)\n */\n constructor(\n title: string,\n details: NotFoundErrorDetails | undefined = undefined,\n correlationId: string | undefined = undefined\n ) {\n super(\n ErrorType.NOT_FOUND,\n title,\n 404, // HTTP 404 Not Found\n correlationId ?? getCurrentCorrelationId(),\n details\n );\n }\n}\n","import { BlaizeError } from '@blaize-types/errors';\n\nimport { generateCorrelationId } from './correlation';\nimport { InternalServerError } from './internal-server-error';\n\nimport type { BlaizeErrorResponse } from '@blaize-types/errors';\n\n/**\n * Checks if an error is a handled BlaizeError instance\n */\nexport function isHandledError(error: unknown): error is BlaizeError {\n return error instanceof BlaizeError;\n}\n\n/**\n * Formats any error into a standardized BlaizeErrorResponse\n */\nexport function formatErrorResponse(error: unknown): BlaizeErrorResponse {\n // Handle BlaizeError instances - they're already properly formatted\n if (isHandledError(error)) {\n return {\n type: error.type,\n title: error.title,\n status: error.status,\n correlationId: error.correlationId,\n timestamp: error.timestamp.toISOString(),\n details: error.details,\n };\n }\n\n // Handle unexpected errors by wrapping them in InternalServerError\n const correlationId = generateCorrelationId();\n let originalMessage: string;\n\n if (error instanceof Error) {\n originalMessage = error.message;\n } else if (error === null || error === undefined) {\n originalMessage = 'Unknown error occurred';\n } else {\n originalMessage = String(error);\n }\n\n // Create InternalServerError for unexpected errors\n const wrappedError = new InternalServerError(\n 'Internal Server Error',\n { originalMessage },\n correlationId\n );\n\n return {\n type: wrappedError.type,\n title: wrappedError.title,\n status: wrappedError.status,\n correlationId: wrappedError.correlationId,\n timestamp: wrappedError.timestamp.toISOString(),\n details: wrappedError.details,\n };\n}\n\n/**\n * Extracts correlation ID from request headers or generates a new one\n */\nexport function extractOrGenerateCorrelationId(\n headerGetter: (name: string) => string | undefined\n): string {\n return headerGetter('x-correlation-id') ?? generateCorrelationId();\n}\n\n/**\n * Sets response headers for error responses\n */\nexport function setErrorResponseHeaders(\n headerSetter: (name: string, value: string) => void,\n correlationId: string\n): void {\n headerSetter('x-correlation-id', correlationId);\n // Add any other standard error headers here if needed\n}\n","import {\n formatErrorResponse,\n extractOrGenerateCorrelationId,\n setErrorResponseHeaders,\n} from '../errors/boundary';\n\nimport type { Context } from '@blaize-types/context';\nimport type { Middleware, MiddlewareFunction, NextFunction } from '@blaize-types/middleware';\n\n/**\n * Options for configuring the error boundary middleware\n */\nexport interface ErrorBoundaryOptions {\n /** Enable debug logging of caught errors */\n debug?: boolean;\n}\n\n/**\n * Creates an error boundary middleware that catches all errors and converts them to proper HTTP responses\n *\n * This middleware should be placed early in the middleware chain to catch all downstream errors.\n * It ensures that:\n * - All BlaizeError instances are properly formatted as HTTP responses\n * - Unexpected errors are wrapped in InternalServerError and logged\n * - Correlation IDs are preserved and added to response headers\n * - No unhandled errors escape the middleware chain\n */\nexport function createErrorBoundary(options: ErrorBoundaryOptions = {}): Middleware {\n const { debug = false } = options;\n\n const middlewareFn: MiddlewareFunction = async (ctx: Context, next: NextFunction) => {\n try {\n await next();\n } catch (error) {\n // Don't handle errors if response was already sent\n if (ctx.response.sent) {\n if (debug) {\n console.error('Error occurred after response was sent:', error);\n }\n return;\n }\n\n // Log error in debug mode\n if (debug) {\n console.error('Error boundary caught error:', error);\n }\n\n // Extract or generate correlation ID from request\n const correlationId = extractOrGenerateCorrelationId(ctx.request.header);\n\n // Format the error as a proper response\n const errorResponse = formatErrorResponse(error);\n\n // Ensure correlation ID is consistent\n errorResponse.correlationId = correlationId;\n\n // Set appropriate response headers\n setErrorResponseHeaders(ctx.response.header, correlationId);\n\n // Send the formatted error response\n ctx.response.status(errorResponse.status).json(errorResponse);\n }\n };\n\n return {\n name: 'ErrorBoundary',\n execute: middlewareFn,\n debug,\n };\n}\n","import { createContext } from '../context/create';\nimport { runWithContext } from '../context/store';\nimport { NotFoundError } from '../errors/not-found-error';\nimport { compose } from '../middleware/compose';\nimport { createErrorBoundary } from '../middleware/error-boundary';\n\nimport type { Server, RequestHandler } from '@blaize-types/server';\n\nexport function createRequestHandler(serverInstance: Server): RequestHandler {\n return async (req, res) => {\n try {\n // Create context for this request\n const context = await createContext(req, res, {\n parseBody: true, // Enable automatic body parsing\n });\n\n // Create error boundary middleware that catches all thrown error classes\n const errorBoundary = createErrorBoundary();\n\n // Compose all middleware with error boundary first (to catch all errors)\n const allMiddleware = [errorBoundary, ...serverInstance.middleware];\n\n // Compose all middleware into a single function\n const handler = compose(allMiddleware);\n\n // Run the request with context in AsyncLocalStorage\n await runWithContext(context, async () => {\n await handler(context, async () => {\n if (!context.response.sent) {\n // Let the router handle the request\n await serverInstance.router.handleRequest(context);\n // If router didn't handle it either, send a 404\n if (!context.response.sent) {\n throw new NotFoundError(\n `Route not found: ${context.request.method} ${context.request.path}`\n );\n }\n }\n });\n });\n } catch (error) {\n // Handle errors in context creation\n console.error('Error creating context:', error);\n res.writeHead(500, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({\n error: 'Internal Server Error',\n message: 'Failed to process request',\n })\n );\n }\n };\n}\n","import type { Server, StopOptions } from '@blaize-types/server';\n\n// Add a global flag to prevent multiple shutdowns\nlet isShuttingDown = false;\n\n// Replace the stopServer function in stop.ts with this version:\n\nexport async function stopServer(serverInstance: Server, options: StopOptions = {}): Promise<void> {\n const server = serverInstance.server;\n const events = serverInstance.events;\n\n if (isShuttingDown) {\n console.log('⚠️ Shutdown already in progress, ignoring duplicate shutdown request');\n return;\n }\n\n if (!server) {\n return;\n }\n\n isShuttingDown = true;\n const timeout = options.timeout || 5000; // Reduced to 5 seconds for faster restarts\n\n try {\n if (options.onStopping) {\n await options.onStopping();\n }\n\n events.emit('stopping');\n\n // Close router watchers with timeout\n if (serverInstance.router && typeof serverInstance.router.close === 'function') {\n console.log('🔌 Closing router watchers...');\n try {\n // Add timeout to router close\n await Promise.race([\n serverInstance.router.close(),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error('Router close timeout')), 2000)\n ),\n ]);\n console.log('✅ Router watchers closed');\n } catch (error) {\n console.error('❌ Error closing router watchers:', error);\n // Continue with shutdown\n }\n }\n\n // Notify plugins with timeout\n try {\n await Promise.race([\n serverInstance.pluginManager.onServerStop(serverInstance, server),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error('Plugin stop timeout')), 2000)\n ),\n ]);\n } catch (error) {\n console.error('❌ Plugin stop timeout:', error);\n // Continue with shutdown\n }\n\n // Create server close promise with shorter timeout\n const closePromise = new Promise<void>((resolve, reject) => {\n server.close((err?: Error) => {\n if (err) return reject(err);\n resolve();\n });\n });\n\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(() => {\n reject(new Error('Server shutdown timeout'));\n }, timeout);\n });\n\n await Promise.race([closePromise, timeoutPromise]);\n\n // Terminate plugins with timeout\n try {\n await Promise.race([\n serverInstance.pluginManager.terminatePlugins(serverInstance),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error('Plugin terminate timeout')), 1000)\n ),\n ]);\n } catch (error) {\n console.error('❌ Plugin terminate timeout:', error);\n // Continue with shutdown\n }\n\n if (options.onStopped) {\n await options.onStopped();\n }\n\n events.emit('stopped');\n serverInstance.server = null as any;\n\n console.log('✅ Graceful shutdown completed');\n isShuttingDown = false;\n } catch (error) {\n isShuttingDown = false;\n console.error('⚠️ Shutdown error (forcing exit):', error);\n\n // Force close the server if graceful shutdown fails\n if (server && typeof server.close === 'function') {\n server.close();\n }\n\n // In development, force exit to allow tsx to restart\n if (process.env.NODE_ENV === 'development') {\n console.log('🔄 Forcing exit for development restart...');\n process.exit(0);\n }\n\n events.emit('error', error);\n throw error;\n }\n}\n\n/**\n * Register signal handlers for graceful shutdown\n */\nexport function registerSignalHandlers(stopFn: () => Promise<void>): { unregister: () => void } {\n const isDevelopment = process.env.NODE_ENV === 'development';\n\n if (isDevelopment) {\n // Development: Force exit for fast restarts\n const sigintHandler = () => {\n console.log('📤 SIGINT received, forcing exit for development restart...');\n process.exit(0);\n };\n\n const sigtermHandler = () => {\n console.log('📤 SIGTERM received, forcing exit for development restart...');\n process.exit(0);\n };\n\n process.on('SIGINT', sigintHandler);\n process.on('SIGTERM', sigtermHandler);\n\n return {\n unregister: () => {\n process.removeListener('SIGINT', sigintHandler);\n process.removeListener('SIGTERM', sigtermHandler);\n },\n };\n } else {\n // Production: Graceful shutdown\n const sigintHandler = () => {\n console.log('📤 SIGINT received, starting graceful shutdown...');\n stopFn().catch(console.error);\n };\n\n const sigtermHandler = () => {\n console.log('📤 SIGTERM received, starting graceful shutdown...');\n stopFn().catch(console.error);\n };\n\n process.on('SIGINT', sigintHandler);\n process.on('SIGTERM', sigtermHandler);\n\n return {\n unregister: () => {\n process.removeListener('SIGINT', sigintHandler);\n process.removeListener('SIGTERM', sigtermHandler);\n },\n };\n }\n}\n","import { z } from 'zod';\n\nimport type { Middleware } from '@blaize-types/middleware';\nimport type { Plugin } from '@blaize-types/plugins';\nimport type { ServerOptions, ServerOptionsInput } from '@blaize-types/server';\n\n// Create a more flexible validation for the middleware function type\nconst middlewareSchema = z.custom<Middleware>(\n data =>\n data !== null &&\n typeof data === 'object' &&\n 'execute' in data &&\n typeof data.execute === 'function',\n {\n message: 'Expected middleware to have an execute function',\n }\n);\n\n// Create a schema for plugins\nconst pluginSchema = z.custom<Plugin>(\n data =>\n data !== null &&\n typeof data === 'object' &&\n 'register' in data &&\n typeof data.register === 'function',\n {\n message: 'Expected a valid plugin object with a register method',\n }\n);\n\n// Create a schema for HTTP/2 options with conditional validation\nconst http2Schema = z\n .object({\n enabled: z.boolean().optional().default(true),\n keyFile: z.string().optional(),\n certFile: z.string().optional(),\n })\n .refine(\n data => {\n // If HTTP/2 is enabled and not in development mode,\n // both keyFile and certFile must be provided\n if (data.enabled && process.env.NODE_ENV === 'production') {\n return data.keyFile && data.certFile;\n }\n return true;\n },\n {\n message:\n 'When HTTP/2 is enabled (outside of development mode), both keyFile and certFile must be provided',\n }\n );\n\n// Validation schema for server options\nexport const serverOptionsSchema = z.object({\n port: z.number().int().positive().optional().default(3000),\n host: z.string().optional().default('localhost'),\n routesDir: z.string().optional().default('./routes'),\n http2: http2Schema.optional().default({\n enabled: true,\n }),\n middleware: z.array(middlewareSchema).optional().default([]),\n plugins: z.array(pluginSchema).optional().default([]),\n});\n\nexport function validateServerOptions(options: ServerOptionsInput): ServerOptions {\n try {\n return serverOptionsSchema.parse(options);\n } catch (error) {\n // Properly type the error as Zod validation error\n if (error instanceof z.ZodError) {\n // Format the Zod error for better readability\n const formattedError = error.format();\n throw new Error(`Invalid server options: ${JSON.stringify(formattedError, null, 2)}`);\n }\n // For other types of errors\n throw new Error(`Invalid server options: ${String(error)}`);\n }\n}\n","import type { Plugin, PluginLifecycleManager, PluginLifecycleOptions } from '@blaize-types/plugins';\nimport type { Server } from '@blaize-types/server';\n\n/**\n * Create a plugin lifecycle manager\n */\nexport function createPluginLifecycleManager(\n options: PluginLifecycleOptions = {}\n): PluginLifecycleManager {\n const { continueOnError = true, debug = false, onError } = options;\n\n /**\n * Log debug messages if enabled\n */\n function log(message: string, ...args: any[]) {\n if (debug) {\n console.log(`[PluginLifecycle] ${message}`, ...args);\n }\n }\n\n /**\n * Handle plugin errors\n */\n function handleError(plugin: Plugin, phase: string, error: Error) {\n const errorMessage = `Plugin ${plugin.name} failed during ${phase}: ${error.message}`;\n\n if (onError) {\n onError(plugin, phase, error);\n } else {\n console.error(errorMessage, error);\n }\n\n if (!continueOnError) {\n throw new Error(errorMessage);\n }\n }\n\n return {\n /**\n * Initialize all plugins\n */\n async initializePlugins(server: Server): Promise<void> {\n log('Initializing plugins...');\n\n for (const plugin of server.plugins) {\n if (plugin.initialize) {\n try {\n log(`Initializing plugin: ${plugin.name}`);\n await plugin.initialize(server);\n } catch (error) {\n handleError(plugin, 'initialize', error as Error);\n }\n }\n }\n\n log(`Initialized ${server.plugins.length} plugins`);\n },\n\n /**\n * Terminate all plugins in reverse order\n */\n async terminatePlugins(server: Server): Promise<void> {\n log('Terminating plugins...');\n\n const pluginsToTerminate = [...server.plugins].reverse();\n\n for (const plugin of pluginsToTerminate) {\n if (plugin.terminate) {\n try {\n log(`Terminating plugin: ${plugin.name}`);\n await plugin.terminate(server);\n } catch (error) {\n handleError(plugin, 'terminate', error as Error);\n }\n }\n }\n\n log(`Terminated ${pluginsToTerminate.length} plugins`);\n },\n\n /**\n * Notify plugins that the server has started\n */\n async onServerStart(server: Server, httpServer: any): Promise<void> {\n log('Notifying plugins of server start...');\n\n for (const plugin of server.plugins) {\n if (plugin.onServerStart) {\n try {\n log(`Notifying plugin of server start: ${plugin.name}`);\n await plugin.onServerStart(httpServer);\n } catch (error) {\n handleError(plugin, 'onServerStart', error as Error);\n }\n }\n }\n },\n\n /**\n * Notify plugins that the server is stopping\n */\n async onServerStop(server: Server, httpServer: any): Promise<void> {\n log('Notifying plugins of server stop...');\n\n const pluginsToNotify = [...server.plugins].reverse();\n\n for (const plugin of pluginsToNotify) {\n if (plugin.onServerStop) {\n try {\n log(`Notifying plugin of server stop: ${plugin.name}`);\n await plugin.onServerStop(httpServer);\n } catch (error) {\n handleError(plugin, 'onServerStop', error as Error);\n }\n }\n }\n },\n };\n}\n","export class PluginError extends Error {\n constructor(\n public pluginName: string,\n message: string,\n public cause?: Error\n ) {\n super(`Plugin \"${pluginName}\": ${message}`);\n this.name = 'PluginError';\n }\n}\n\nexport class PluginLifecycleError extends PluginError {\n constructor(\n pluginName: string,\n public phase: 'register' | 'initialize' | 'terminate' | 'start' | 'stop',\n cause: Error\n ) {\n super(pluginName, `Failed during ${phase} phase: ${cause.message}`, cause);\n this.name = 'PluginLifecycleError';\n }\n}\n\nexport class PluginDependencyError extends PluginError {\n constructor(\n pluginName: string,\n public missingDependency: string\n ) {\n super(pluginName, `Missing dependency: ${missingDependency}`);\n this.name = 'PluginDependencyError';\n }\n}\n\n// packages/blaizejs/src/plugins/errors.ts (or add to existing errors file)\n\nexport class PluginValidationError extends Error {\n constructor(\n public pluginName: string,\n message: string\n ) {\n super(`Plugin validation error${pluginName ? ` for \"${pluginName}\"` : ''}: ${message}`);\n this.name = 'PluginValidationError';\n }\n}\n\nexport class PluginRegistrationError extends Error {\n constructor(\n public pluginName: string,\n message: string\n ) {\n super(`Plugin registration error for \"${pluginName}\": ${message}`);\n this.name = 'PluginRegistrationError';\n }\n}\n","import { PluginValidationError } from './errors';\n\nimport type { Plugin } from '@blaize-types/plugins';\n\nexport interface PluginValidationOptions {\n /** Require specific plugin properties */\n requireVersion?: boolean;\n /** Validate plugin name format */\n validateNameFormat?: boolean;\n /** Check for reserved plugin names */\n checkReservedNames?: boolean;\n}\n\n/**\n * Reserved plugin names that cannot be used\n */\nconst RESERVED_NAMES = new Set([\n 'core',\n 'server',\n 'router',\n 'middleware',\n 'context',\n 'blaize',\n 'blaizejs',\n]);\n\n/**\n * Valid plugin name pattern (lowercase, letters, numbers, hyphens)\n */\nconst VALID_NAME_PATTERN = /^[a-z]([a-z0-9-]*[a-z0-9])?$/;\n\n/**\n * Valid semantic version pattern\n */\nconst VALID_VERSION_PATTERN = /^\\d+\\.\\d+\\.\\d+(?:-[a-zA-Z0-9-.]+)?(?:\\+[a-zA-Z0-9-.]+)?$/;\n\n/**\n * Validate a plugin object\n */\nexport function validatePlugin(\n plugin: unknown,\n options: PluginValidationOptions = {}\n): asserts plugin is Plugin {\n const { requireVersion = true, validateNameFormat = true, checkReservedNames = true } = options;\n\n // Basic type validation\n if (!plugin || typeof plugin !== 'object') {\n throw new PluginValidationError('', 'Plugin must be an object');\n }\n\n const p = plugin as any;\n\n // Validate name\n if (!p.name || typeof p.name !== 'string') {\n throw new PluginValidationError('', 'Plugin must have a name (string)');\n }\n\n // Validate name format\n if (validateNameFormat && !VALID_NAME_PATTERN.test(p.name)) {\n throw new PluginValidationError(\n p.name,\n 'Plugin name must be lowercase letters, numbers, and hyphens only'\n );\n }\n\n // Check reserved names\n if (checkReservedNames && RESERVED_NAMES.has(p.name.toLowerCase())) {\n throw new PluginValidationError(p.name, `Plugin name \"${p.name}\" is reserved`);\n }\n\n // Validate version\n if (requireVersion) {\n if (!p.version || typeof p.version !== 'string') {\n throw new PluginValidationError(p.name, 'Plugin must have a version (string)');\n }\n\n if (!VALID_VERSION_PATTERN.test(p.version)) {\n throw new PluginValidationError(\n p.name,\n 'Plugin version must follow semantic versioning (e.g., \"1.0.0\")'\n );\n }\n }\n\n // Validate register method\n if (!p.register || typeof p.register !== 'function') {\n throw new PluginValidationError(p.name, 'Plugin must have a register method (function)');\n }\n\n // Validate optional lifecycle methods\n const lifecycleMethods = ['initialize', 'terminate', 'onServerStart', 'onServerStop'];\n\n for (const method of lifecycleMethods) {\n if (p[method] && typeof p[method] !== 'function') {\n throw new PluginValidationError(p.name, `Plugin ${method} must be a function if provided`);\n }\n }\n\n // Validate dependencies if present\n // if (p.dependencies) {\n // if (!Array.isArray(p.dependencies) && typeof p.dependencies !== 'string') {\n // throw new PluginValidationError(\n // p.name,\n // 'Plugin dependencies must be a string or array of strings'\n // );\n // }\n\n // const deps = Array.isArray(p.dependencies) ? p.dependencies : [p.dependencies];\n // for (const dep of deps) {\n // if (typeof dep !== 'string') {\n // throw new PluginValidationError(p.name, 'Plugin dependencies must be strings');\n // }\n // }\n // }\n}\n\n/**\n * Validate plugin options object\n */\nexport function validatePluginOptions(pluginName: string, options: unknown, schema?: any): void {\n // Basic validation\n if (options !== undefined && typeof options !== 'object') {\n throw new PluginValidationError(pluginName, 'Plugin options must be an object');\n }\n\n // If a schema is provided, validate against it\n if (schema && options) {\n try {\n schema.parse(options);\n } catch (error) {\n throw new PluginValidationError(\n pluginName,\n `Plugin options validation failed: ${(error as Error).message}`\n );\n }\n }\n}\n\n/**\n * Validate plugin factory function\n */\nexport function validatePluginFactory(\n factory: unknown\n): asserts factory is (...args: any[]) => any {\n if (typeof factory !== 'function') {\n throw new PluginValidationError('', 'Plugin factory must be a function');\n }\n}\n\n/**\n * Check if a plugin name is valid\n */\nexport function isValidPluginName(name: string): boolean {\n return (\n typeof name === 'string' &&\n name.length > 0 &&\n VALID_NAME_PATTERN.test(name) &&\n !RESERVED_NAMES.has(name.toLowerCase())\n );\n}\n\n/**\n * Check if a version string is valid\n */\nexport function isValidVersion(version: string): boolean {\n return typeof version === 'string' && VALID_VERSION_PATTERN.test(version);\n}\n\n/**\n * Sanitize plugin name (remove invalid characters)\n */\nexport function sanitizePluginName(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, '-')\n .replace(/^-+|-+$/g, '')\n .replace(/-+/g, '-');\n}\n","import * as crypto from 'node:crypto';\nimport * as fs from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport * as path from 'node:path';\n\nimport { loadRouteModule } from './loader';\n\nimport type { FileCache, Route } from '@blaize-types/router';\n\nconst fileRouteCache = new Map<string, FileCache>();\n\nexport async function processChangedFile(\n filePath: string,\n routesDir: string,\n updateCache: boolean = true\n): Promise<Route[]> {\n const stat = await fs.stat(filePath);\n const lastModified = stat.mtime.getTime();\n const cachedEntry = fileRouteCache.get(filePath);\n\n // Skip if file hasn't changed by timestamp (only when updating cache)\n if (updateCache && cachedEntry && cachedEntry.timestamp === lastModified) {\n return cachedEntry.routes;\n }\n\n // Clear module cache for this specific file\n invalidateModuleCache(filePath);\n\n // Load only this file\n const routes = await loadRouteModule(filePath, routesDir);\n\n // Only update cache if requested\n if (updateCache) {\n // Calculate content hash for change detection\n const hash = hashRoutes(routes);\n\n // Update cache\n fileRouteCache.set(filePath, {\n routes,\n timestamp: lastModified,\n hash,\n });\n }\n\n return routes;\n}\n\nexport function hasRouteContentChanged(filePath: string, newRoutes: Route[]): boolean {\n const cachedEntry = fileRouteCache.get(filePath);\n if (!cachedEntry) {\n return true;\n }\n\n const newHash = hashRoutes(newRoutes);\n\n return cachedEntry.hash !== newHash;\n}\n\nexport function clearFileCache(filePath?: string): void {\n if (filePath) {\n fileRouteCache.delete(filePath);\n } else {\n fileRouteCache.clear();\n }\n}\n\nfunction hashRoutes(routes: Route[]): string {\n const routeData = routes.map(route => ({\n path: route.path,\n methods: Object.keys(route)\n .filter(key => key !== 'path')\n .sort()\n .map(method => {\n const methodDef = route[method as keyof Route] as any;\n const handlerString = methodDef?.handler ? methodDef.handler.toString() : null;\n return {\n method,\n // Include handler function string for change detection\n handler: handlerString,\n // Include middleware if present\n middleware: methodDef?.middleware ? methodDef.middleware.length : 0,\n // Include schema structure (but not full serialization which can be unstable)\n hasSchema: !!methodDef?.schema,\n schemaKeys: methodDef?.schema ? Object.keys(methodDef.schema).sort() : [],\n };\n }),\n }));\n\n const dataString = JSON.stringify(routeData);\n const hash = crypto.createHash('md5').update(dataString).digest('hex');\n\n return hash;\n}\n\nfunction invalidateModuleCache(filePath: string): void {\n try {\n // Try to resolve the absolute path\n const absolutePath = path.resolve(filePath);\n\n // Check if we're in a CommonJS environment (require is available)\n if (typeof require !== 'undefined') {\n // Delete from require cache if it exists\n delete require.cache[absolutePath];\n\n // Also try to resolve using require.resolve if the file exists\n try {\n const resolvedPath = require.resolve(absolutePath);\n delete require.cache[resolvedPath];\n } catch (resolveError) {\n // Type guard to ensure resolveError is an Error object\n const errorMessage =\n resolveError instanceof Error ? resolveError.message : String(resolveError);\n console.log(`⚠️ Could not resolve path: ${errorMessage}`);\n }\n } else {\n // In pure ESM environment, try to use createRequire for cache invalidation\n try {\n const require = createRequire(import.meta.url);\n delete require.cache[absolutePath];\n\n try {\n const resolvedPath = require.resolve(absolutePath);\n delete require.cache[resolvedPath];\n } catch {\n console.log(`⚠️ Could not resolve ESM path`);\n }\n } catch {\n console.log(`⚠️ createRequire not available in pure ESM`);\n }\n }\n } catch (error) {\n console.log(`⚠️ Error during module cache invalidation for ${filePath}:`, error);\n }\n}\n","import { parseRoutePath } from './parser';\n\nimport type { Route, RouteDefinition } from '@blaize-types/router';\n\nexport async function dynamicImport(filePath: string) {\n // Add a cache-busting query parameter for ESM\n const cacheBuster = `?t=${Date.now()}`;\n const importPath = filePath + cacheBuster;\n\n try {\n const module = await import(importPath);\n console.log(`✅ Successfully imported module`);\n return module;\n } catch (error) {\n // Type guard to ensure resolveError is an Error object\n const errorMessage = error instanceof Error ? error.message : String(error);\n console.log(`⚠️ Error importing with cache buster, trying original path:`, errorMessage);\n // Fallback to original path\n return import(filePath);\n }\n}\n\n/**\n * Load route modules from a file - supports both default export and named exports\n */\nexport async function loadRouteModule(filePath: string, basePath: string): Promise<Route[]> {\n try {\n // Parse the route path from the file path\n const parsedRoute = parseRoutePath(filePath, basePath);\n // Dynamically import the module\n const module = await dynamicImport(filePath);\n console.log('📦 Module exports:', Object.keys(module));\n\n const routes: Route[] = [];\n\n // Method 1: Check for default export (existing pattern)\n if (module.default && typeof module.default === 'object') {\n const route: Route = {\n ...(module.default as RouteDefinition),\n path: parsedRoute.routePath,\n };\n\n routes.push(route);\n }\n\n // Method 2: Check for named exports that look like routes\n Object.entries(module).forEach(([exportName, exportValue]) => {\n // Skip default export (already handled) and non-objects\n if (exportName === 'default' || !exportValue || typeof exportValue !== 'object') {\n return;\n }\n\n // Check if this export looks like a route (has path property and HTTP methods)\n const potentialRoute = exportValue as any;\n\n if (isValidRoute(potentialRoute)) {\n // For named exports, we might want to use the export name or the route's path\n const route: Route = {\n ...potentialRoute,\n // Use the route's own path if it has one, otherwise derive from file\n path: parsedRoute.routePath,\n };\n\n routes.push(route);\n }\n });\n\n if (routes.length === 0) {\n console.warn(`Route file ${filePath} does not export any valid route definitions`);\n return [];\n }\n\n console.log(`✅ Successfully Loaded ${routes.length} route(s)`);\n return routes;\n } catch (error) {\n console.error(`Failed to load route module ${filePath}:`, error);\n return [];\n }\n}\n\n/**\n * Check if an object looks like a valid route\n */\nfunction isValidRoute(obj: any): boolean {\n if (!obj || typeof obj !== 'object') {\n return false;\n }\n\n // Check if it has at least one HTTP method\n const httpMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];\n const hasHttpMethod = httpMethods.some(\n method => obj[method] && typeof obj[method] === 'object' && obj[method].handler\n );\n\n return hasHttpMethod;\n}\n","import * as os from 'node:os';\n\nimport { processChangedFile } from './cache';\nimport { findRouteFiles } from './finder';\n\nimport type { Route } from '@blaize-types/router';\n\nexport async function processFilesInParallel(\n filePaths: string[],\n processor: (filePath: string) => Promise<Route[]>,\n concurrency: number = Math.max(1, Math.floor(os.cpus().length / 2))\n): Promise<Route[][]> {\n const chunks = chunkArray(filePaths, concurrency);\n const results: Route[][] = [];\n\n for (const chunk of chunks) {\n const chunkResults = await Promise.allSettled(chunk.map(filePath => processor(filePath)));\n\n const successfulResults = chunkResults\n .filter(result => result.status === 'fulfilled')\n .map(result => (result as PromiseFulfilledResult<Route[]>).value);\n\n results.push(...successfulResults);\n }\n\n return results;\n}\n\nexport async function loadInitialRoutesParallel(routesDir: string): Promise<Route[]> {\n const files = await findRouteFiles(routesDir);\n const routeArrays = await processFilesInParallel(files, filePath =>\n processChangedFile(filePath, routesDir)\n );\n\n return routeArrays.flat();\n}\n\nfunction chunkArray<T>(array: T[], chunkSize: number): T[][] {\n const chunks: T[][] = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n chunks.push(array.slice(i, i + chunkSize));\n }\n return chunks;\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\n\nimport type { FindRouteFilesOptions } from '@blaize-types/router';\n\n/**\n * Find all route files in the specified directory\n */\nexport async function findRouteFiles(\n routesDir: string,\n options: FindRouteFilesOptions = {}\n): Promise<string[]> {\n // Convert to absolute path if it's relative\n const absoluteDir = path.isAbsolute(routesDir)\n ? routesDir\n : path.resolve(process.cwd(), routesDir);\n\n console.log('Creating router with routes directory:', absoluteDir);\n\n // Check if directory exists\n try {\n const stats = await fs.stat(absoluteDir);\n if (!stats.isDirectory()) {\n throw new Error(`Route directory is not a directory: ${absoluteDir}`);\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`Route directory not found: ${absoluteDir}`);\n }\n throw error;\n }\n\n const routeFiles: string[] = [];\n const ignore = options.ignore || ['node_modules', '.git'];\n\n async function scanDirectory(dir: string) {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n\n // Skip ignored directories\n if (entry.isDirectory() && ignore.includes(entry.name)) {\n continue;\n }\n\n if (entry.isDirectory()) {\n await scanDirectory(fullPath);\n } else if (isRouteFile(entry.name)) {\n routeFiles.push(fullPath);\n }\n }\n }\n\n await scanDirectory(absoluteDir);\n return routeFiles;\n}\n\n/**\n * Check if a file is a valid route file\n */\nfunction isRouteFile(filename: string): boolean {\n // Route files are TypeScript/JavaScript files that don't start with underscore\n return !filename.startsWith('_') && (filename.endsWith('.ts') || filename.endsWith('.js'));\n}\n","import type { ReloadMetrics } from '@blaize-types/router';\n\nconst profilerState: ReloadMetrics = {\n fileChanges: 0,\n totalReloadTime: 0,\n averageReloadTime: 0,\n slowReloads: [],\n};\n\nexport function trackReloadPerformance(filePath: string, startTime: number): void {\n const duration = Date.now() - startTime;\n\n profilerState.fileChanges++;\n profilerState.totalReloadTime += duration;\n profilerState.averageReloadTime = profilerState.totalReloadTime / profilerState.fileChanges;\n\n if (duration > 100) {\n profilerState.slowReloads.push({ file: filePath, time: duration });\n if (profilerState.slowReloads.length > 10) {\n profilerState.slowReloads.shift();\n }\n }\n\n if (process.env.NODE_ENV === 'development') {\n const emoji = duration < 50 ? '⚡' : duration < 100 ? '🔄' : '🐌';\n console.log(`${emoji} Route reload: ${filePath} (${duration}ms)`);\n }\n}\n\nexport function getReloadMetrics(): Readonly<ReloadMetrics> {\n return { ...profilerState };\n}\n\nexport function resetReloadMetrics(): void {\n profilerState.fileChanges = 0;\n profilerState.totalReloadTime = 0;\n profilerState.averageReloadTime = 0;\n profilerState.slowReloads = [];\n}\n\nexport function withPerformanceTracking<T extends (...args: any[]) => Promise<any>>(\n fn: T,\n filePath: string\n): T {\n console.log(`Tracking performance for: ${filePath}`);\n return (async (...args: Parameters<T>) => {\n const startTime = Date.now();\n try {\n const result = await fn(...args);\n trackReloadPerformance(filePath, startTime);\n return result;\n } catch (error) {\n trackReloadPerformance(filePath, startTime);\n throw error;\n }\n }) as T;\n}\n","import * as path from 'node:path';\n\nimport { watch } from 'chokidar';\n\nimport { hasRouteContentChanged, processChangedFile } from './cache';\nimport { findRouteFiles } from './finder';\n\nimport type { Route, WatchOptions } from '@blaize-types/router';\n\n/**\n * Watch for route file changes\n */\nexport function watchRoutes(routesDir: string, options: WatchOptions = {}) {\n // Debounce rapid file changes\n const debounceMs = options.debounceMs || 16;\n const debouncedCallbacks = new Map<string, NodeJS.Timeout>();\n\n function createDebouncedCallback<T extends (...args: any[]) => void>(\n fn: T,\n filePath: string\n ): (...args: Parameters<T>) => void {\n return (...args: Parameters<T>) => {\n // Clear existing timeout for this file\n const existingTimeout = debouncedCallbacks.get(filePath);\n if (existingTimeout) {\n clearTimeout(existingTimeout);\n }\n\n // Set new timeout\n const timeoutId = setTimeout(() => {\n fn(...args);\n debouncedCallbacks.delete(filePath);\n }, debounceMs);\n\n debouncedCallbacks.set(filePath, timeoutId);\n };\n }\n // Track loaded routes by file path - now stores arrays of routes\n const routesByPath = new Map<string, Route[]>();\n\n // Initial loading of routes\n async function loadInitialRoutes() {\n try {\n const files = await findRouteFiles(routesDir, {\n ignore: options.ignore,\n });\n\n for (const filePath of files) {\n await loadAndNotify(filePath);\n }\n } catch (error) {\n handleError(error);\n }\n }\n\n // Optimized load and notify function\n async function loadAndNotify(filePath: string) {\n try {\n const existingRoutes = routesByPath.get(filePath);\n\n // Step 1: Load new routes WITHOUT updating cache\n const newRoutes = await processChangedFile(filePath, routesDir, false);\n\n if (!newRoutes || newRoutes.length === 0) {\n return;\n }\n\n // Step 2: Check if content has actually changed (cache still has old data)\n if (existingRoutes && !hasRouteContentChanged(filePath, newRoutes)) {\n return;\n }\n\n // Step 3: Content changed! Now update the cache\n await processChangedFile(filePath, routesDir, true);\n\n const normalizedPath = path.normalize(filePath);\n\n if (existingRoutes) {\n routesByPath.set(filePath, newRoutes);\n if (options.onRouteChanged) {\n options.onRouteChanged(normalizedPath, newRoutes);\n }\n } else {\n routesByPath.set(filePath, newRoutes);\n if (options.onRouteAdded) {\n options.onRouteAdded(normalizedPath, newRoutes);\n }\n }\n } catch (error) {\n console.log(`⚠️ Error processing file ${filePath}:`, error);\n handleError(error);\n }\n }\n\n // Handle route file removal\n function handleRemoved(filePath: string) {\n const normalizedPath = path.normalize(filePath);\n const routes = routesByPath.get(normalizedPath);\n\n if (routes && routes.length > 0 && options.onRouteRemoved) {\n options.onRouteRemoved(normalizedPath, routes);\n }\n\n routesByPath.delete(normalizedPath);\n }\n\n // Handle errors\n function handleError(error: unknown) {\n if (options.onError && error instanceof Error) {\n options.onError(error);\n } else {\n console.error('⚠️ Route watcher error:', error);\n }\n }\n\n // Start file watcher\n // Create optimized watcher\n const watcher = watch(routesDir, {\n // Much faster response times\n awaitWriteFinish: {\n stabilityThreshold: 50, // Reduced from 300ms\n pollInterval: 10, // Reduced from 100ms\n },\n\n // Performance optimizations\n usePolling: false,\n atomic: true,\n followSymlinks: false,\n depth: 10,\n\n // More aggressive ignoring\n ignored: [\n /(^|[/\\\\])\\../,\n /node_modules/,\n /\\.git/,\n /\\.DS_Store/,\n /Thumbs\\.db/,\n /\\.(test|spec)\\.(ts|js)$/,\n /\\.d\\.ts$/,\n /\\.map$/,\n /~$/,\n ...(options.ignore || []),\n ],\n });\n\n // Set up event handlers\n watcher\n .on('add', filePath => {\n const debouncedLoad = createDebouncedCallback(loadAndNotify, filePath);\n debouncedLoad(filePath);\n })\n .on('change', filePath => {\n const debouncedLoad = createDebouncedCallback(loadAndNotify, filePath);\n\n // Call debounced load for changed file\n debouncedLoad(filePath);\n })\n .on('unlink', filePath => {\n const debouncedRemove = createDebouncedCallback(handleRemoved, filePath);\n debouncedRemove(filePath);\n })\n .on('error', handleError);\n\n // Load initial routes\n loadInitialRoutes().catch(handleError);\n\n // Return control methods\n return {\n close: () => {\n // Clear any pending debounced callbacks\n debouncedCallbacks.forEach(timeout => clearTimeout(timeout));\n debouncedCallbacks.clear();\n\n return watcher.close();\n },\n getRoutes: () => {\n const allRoutes: Route[] = [];\n for (const routes of routesByPath.values()) {\n allRoutes.push(...routes);\n }\n return allRoutes;\n },\n getRoutesByFile: () => new Map(routesByPath),\n };\n}\n","/*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */\nimport { stat as statcb } from 'fs';\nimport { stat, readdir } from 'fs/promises';\nimport { EventEmitter } from 'events';\nimport * as sysPath from 'path';\nimport { readdirp } from 'readdirp';\nimport { NodeFsHandler, EVENTS as EV, isWindows, isIBMi, EMPTY_FN, STR_CLOSE, STR_END, } from './handler.js';\nconst SLASH = '/';\nconst SLASH_SLASH = '//';\nconst ONE_DOT = '.';\nconst TWO_DOTS = '..';\nconst STRING_TYPE = 'string';\nconst BACK_SLASH_RE = /\\\\/g;\nconst DOUBLE_SLASH_RE = /\\/\\//;\nconst DOT_RE = /\\..*\\.(sw[px])$|~$|\\.subl.*\\.tmp/;\nconst REPLACER_RE = /^\\.[/\\\\]/;\nfunction arrify(item) {\n return Array.isArray(item) ? item : [item];\n}\nconst isMatcherObject = (matcher) => typeof matcher === 'object' && matcher !== null && !(matcher instanceof RegExp);\nfunction createPattern(matcher) {\n if (typeof matcher === 'function')\n return matcher;\n if (typeof matcher === 'string')\n return (string) => matcher === string;\n if (matcher instanceof RegExp)\n return (string) => matcher.test(string);\n if (typeof matcher === 'object' && matcher !== null) {\n return (string) => {\n if (matcher.path === string)\n return true;\n if (matcher.recursive) {\n const relative = sysPath.relative(matcher.path, string);\n if (!relative) {\n return false;\n }\n return !relative.startsWith('..') && !sysPath.isAbsolute(relative);\n }\n return false;\n };\n }\n return () => false;\n}\nfunction normalizePath(path) {\n if (typeof path !== 'string')\n throw new Error('string expected');\n path = sysPath.normalize(path);\n path = path.replace(/\\\\/g, '/');\n let prepend = false;\n if (path.startsWith('//'))\n prepend = true;\n const DOUBLE_SLASH_RE = /\\/\\//;\n while (path.match(DOUBLE_SLASH_RE))\n path = path.replace(DOUBLE_SLASH_RE, '/');\n if (prepend)\n path = '/' + path;\n return path;\n}\nfunction matchPatterns(patterns, testString, stats) {\n const path = normalizePath(testString);\n for (let index = 0; index < patterns.length; index++) {\n const pattern = patterns[index];\n if (pattern(path, stats)) {\n return true;\n }\n }\n return false;\n}\nfunction anymatch(matchers, testString) {\n if (matchers == null) {\n throw new TypeError('anymatch: specify first argument');\n }\n // Early cache for matchers.\n const matchersArray = arrify(matchers);\n const patterns = matchersArray.map((matcher) => createPattern(matcher));\n if (testString == null) {\n return (testString, stats) => {\n return matchPatterns(patterns, testString, stats);\n };\n }\n return matchPatterns(patterns, testString);\n}\nconst unifyPaths = (paths_) => {\n const paths = arrify(paths_).flat();\n if (!paths.every((p) => typeof p === STRING_TYPE)) {\n throw new TypeError(`Non-string provided as watch path: ${paths}`);\n }\n return paths.map(normalizePathToUnix);\n};\n// If SLASH_SLASH occurs at the beginning of path, it is not replaced\n// because \"//StoragePC/DrivePool/Movies\" is a valid network path\nconst toUnix = (string) => {\n let str = string.replace(BACK_SLASH_RE, SLASH);\n let prepend = false;\n if (str.startsWith(SLASH_SLASH)) {\n prepend = true;\n }\n while (str.match(DOUBLE_SLASH_RE)) {\n str = str.replace(DOUBLE_SLASH_RE, SLASH);\n }\n if (prepend) {\n str = SLASH + str;\n }\n return str;\n};\n// Our version of upath.normalize\n// TODO: this is not equal to path-normalize module - investigate why\nconst normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));\n// TODO: refactor\nconst normalizeIgnored = (cwd = '') => (path) => {\n if (typeof path === 'string') {\n return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));\n }\n else {\n return path;\n }\n};\nconst getAbsolutePath = (path, cwd) => {\n if (sysPath.isAbsolute(path)) {\n return path;\n }\n return sysPath.join(cwd, path);\n};\nconst EMPTY_SET = Object.freeze(new Set());\n/**\n * Directory entry.\n */\nclass DirEntry {\n constructor(dir, removeWatcher) {\n this.path = dir;\n this._removeWatcher = removeWatcher;\n this.items = new Set();\n }\n add(item) {\n const { items } = this;\n if (!items)\n return;\n if (item !== ONE_DOT && item !== TWO_DOTS)\n items.add(item);\n }\n async remove(item) {\n const { items } = this;\n if (!items)\n return;\n items.delete(item);\n if (items.size > 0)\n return;\n const dir = this.path;\n try {\n await readdir(dir);\n }\n catch (err) {\n if (this._removeWatcher) {\n this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));\n }\n }\n }\n has(item) {\n const { items } = this;\n if (!items)\n return;\n return items.has(item);\n }\n getChildren() {\n const { items } = this;\n if (!items)\n return [];\n return [...items.values()];\n }\n dispose() {\n this.items.clear();\n this.path = '';\n this._removeWatcher = EMPTY_FN;\n this.items = EMPTY_SET;\n Object.freeze(this);\n }\n}\nconst STAT_METHOD_F = 'stat';\nconst STAT_METHOD_L = 'lstat';\nexport class WatchHelper {\n constructor(path, follow, fsw) {\n this.fsw = fsw;\n const watchPath = path;\n this.path = path = path.replace(REPLACER_RE, '');\n this.watchPath = watchPath;\n this.fullWatchPath = sysPath.resolve(watchPath);\n this.dirParts = [];\n this.dirParts.forEach((parts) => {\n if (parts.length > 1)\n parts.pop();\n });\n this.followSymlinks = follow;\n this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;\n }\n entryPath(entry) {\n return sysPath.join(this.watchPath, sysPath.relative(this.watchPath, entry.fullPath));\n }\n filterPath(entry) {\n const { stats } = entry;\n if (stats && stats.isSymbolicLink())\n return this.filterDir(entry);\n const resolvedPath = this.entryPath(entry);\n // TODO: what if stats is undefined? remove !\n return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);\n }\n filterDir(entry) {\n return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);\n }\n}\n/**\n * Watches files & directories for changes. Emitted events:\n * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`\n *\n * new FSWatcher()\n * .add(directories)\n * .on('add', path => log('File', path, 'was added'))\n */\nexport class FSWatcher extends EventEmitter {\n // Not indenting methods for history sake; for now.\n constructor(_opts = {}) {\n super();\n this.closed = false;\n this._closers = new Map();\n this._ignoredPaths = new Set();\n this._throttled = new Map();\n this._streams = new Set();\n this._symlinkPaths = new Map();\n this._watched = new Map();\n this._pendingWrites = new Map();\n this._pendingUnlinks = new Map();\n this._readyCount = 0;\n this._readyEmitted = false;\n const awf = _opts.awaitWriteFinish;\n const DEF_AWF = { stabilityThreshold: 2000, pollInterval: 100 };\n const opts = {\n // Defaults\n persistent: true,\n ignoreInitial: false,\n ignorePermissionErrors: false,\n interval: 100,\n binaryInterval: 300,\n followSymlinks: true,\n usePolling: false,\n // useAsync: false,\n atomic: true, // NOTE: overwritten later (depends on usePolling)\n ..._opts,\n // Change format\n ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),\n awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === 'object' ? { ...DEF_AWF, ...awf } : false,\n };\n // Always default to polling on IBM i because fs.watch() is not available on IBM i.\n if (isIBMi)\n opts.usePolling = true;\n // Editor atomic write normalization enabled by default with fs.watch\n if (opts.atomic === undefined)\n opts.atomic = !opts.usePolling;\n // opts.atomic = typeof _opts.atomic === 'number' ? _opts.atomic : 100;\n // Global override. Useful for developers, who need to force polling for all\n // instances of chokidar, regardless of usage / dependency depth\n const envPoll = process.env.CHOKIDAR_USEPOLLING;\n if (envPoll !== undefined) {\n const envLower = envPoll.toLowerCase();\n if (envLower === 'false' || envLower === '0')\n opts.usePolling = false;\n else if (envLower === 'true' || envLower === '1')\n opts.usePolling = true;\n else\n opts.usePolling = !!envLower;\n }\n const envInterval = process.env.CHOKIDAR_INTERVAL;\n if (envInterval)\n opts.interval = Number.parseInt(envInterval, 10);\n // This is done to emit ready only once, but each 'add' will increase that?\n let readyCalls = 0;\n this._emitReady = () => {\n readyCalls++;\n if (readyCalls >= this._readyCount) {\n this._emitReady = EMPTY_FN;\n this._readyEmitted = true;\n // use process.nextTick to allow time for listener to be bound\n process.nextTick(() => this.emit(EV.READY));\n }\n };\n this._emitRaw = (...args) => this.emit(EV.RAW, ...args);\n this._boundRemove = this._remove.bind(this);\n this.options = opts;\n this._nodeFsHandler = new NodeFsHandler(this);\n // You’re frozen when your heart’s not open.\n Object.freeze(opts);\n }\n _addIgnoredPath(matcher) {\n if (isMatcherObject(matcher)) {\n // return early if we already have a deeply equal matcher object\n for (const ignored of this._ignoredPaths) {\n if (isMatcherObject(ignored) &&\n ignored.path === matcher.path &&\n ignored.recursive === matcher.recursive) {\n return;\n }\n }\n }\n this._ignoredPaths.add(matcher);\n }\n _removeIgnoredPath(matcher) {\n this._ignoredPaths.delete(matcher);\n // now find any matcher objects with the matcher as path\n if (typeof matcher === 'string') {\n for (const ignored of this._ignoredPaths) {\n // TODO (43081j): make this more efficient.\n // probably just make a `this._ignoredDirectories` or some\n // such thing.\n if (isMatcherObject(ignored) && ignored.path === matcher) {\n this._ignoredPaths.delete(ignored);\n }\n }\n }\n }\n // Public methods\n /**\n * Adds paths to be watched on an existing FSWatcher instance.\n * @param paths_ file or file list. Other arguments are unused\n */\n add(paths_, _origAdd, _internal) {\n const { cwd } = this.options;\n this.closed = false;\n this._closePromise = undefined;\n let paths = unifyPaths(paths_);\n if (cwd) {\n paths = paths.map((path) => {\n const absPath = getAbsolutePath(path, cwd);\n // Check `path` instead of `absPath` because the cwd portion can't be a glob\n return absPath;\n });\n }\n paths.forEach((path) => {\n this._removeIgnoredPath(path);\n });\n this._userIgnored = undefined;\n if (!this._readyCount)\n this._readyCount = 0;\n this._readyCount += paths.length;\n Promise.all(paths.map(async (path) => {\n const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, undefined, 0, _origAdd);\n if (res)\n this._emitReady();\n return res;\n })).then((results) => {\n if (this.closed)\n return;\n results.forEach((item) => {\n if (item)\n this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));\n });\n });\n return this;\n }\n /**\n * Close watchers or start ignoring events from specified paths.\n */\n unwatch(paths_) {\n if (this.closed)\n return this;\n const paths = unifyPaths(paths_);\n const { cwd } = this.options;\n paths.forEach((path) => {\n // convert to absolute path unless relative path already matches\n if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {\n if (cwd)\n path = sysPath.join(cwd, path);\n path = sysPath.resolve(path);\n }\n this._closePath(path);\n this._addIgnoredPath(path);\n if (this._watched.has(path)) {\n this._addIgnoredPath({\n path,\n recursive: true,\n });\n }\n // reset the cached userIgnored anymatch fn\n // to make ignoredPaths changes effective\n this._userIgnored = undefined;\n });\n return this;\n }\n /**\n * Close watchers and remove all listeners from watched paths.\n */\n close() {\n if (this._closePromise) {\n return this._closePromise;\n }\n this.closed = true;\n // Memory management.\n this.removeAllListeners();\n const closers = [];\n this._closers.forEach((closerList) => closerList.forEach((closer) => {\n const promise = closer();\n if (promise instanceof Promise)\n closers.push(promise);\n }));\n this._streams.forEach((stream) => stream.destroy());\n this._userIgnored = undefined;\n this._readyCount = 0;\n this._readyEmitted = false;\n this._watched.forEach((dirent) => dirent.dispose());\n this._closers.clear();\n this._watched.clear();\n this._streams.clear();\n this._symlinkPaths.clear();\n this._throttled.clear();\n this._closePromise = closers.length\n ? Promise.all(closers).then(() => undefined)\n : Promise.resolve();\n return this._closePromise;\n }\n /**\n * Expose list of watched paths\n * @returns for chaining\n */\n getWatched() {\n const watchList = {};\n this._watched.forEach((entry, dir) => {\n const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;\n const index = key || ONE_DOT;\n watchList[index] = entry.getChildren().sort();\n });\n return watchList;\n }\n emitWithAll(event, args) {\n this.emit(event, ...args);\n if (event !== EV.ERROR)\n this.emit(EV.ALL, event, ...args);\n }\n // Common helpers\n // --------------\n /**\n * Normalize and emit events.\n * Calling _emit DOES NOT MEAN emit() would be called!\n * @param event Type of event\n * @param path File or directory path\n * @param stats arguments to be passed with event\n * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag\n */\n async _emit(event, path, stats) {\n if (this.closed)\n return;\n const opts = this.options;\n if (isWindows)\n path = sysPath.normalize(path);\n if (opts.cwd)\n path = sysPath.relative(opts.cwd, path);\n const args = [path];\n if (stats != null)\n args.push(stats);\n const awf = opts.awaitWriteFinish;\n let pw;\n if (awf && (pw = this._pendingWrites.get(path))) {\n pw.lastChange = new Date();\n return this;\n }\n if (opts.atomic) {\n if (event === EV.UNLINK) {\n this._pendingUnlinks.set(path, [event, ...args]);\n setTimeout(() => {\n this._pendingUnlinks.forEach((entry, path) => {\n this.emit(...entry);\n this.emit(EV.ALL, ...entry);\n this._pendingUnlinks.delete(path);\n });\n }, typeof opts.atomic === 'number' ? opts.atomic : 100);\n return this;\n }\n if (event === EV.ADD && this._pendingUnlinks.has(path)) {\n event = EV.CHANGE;\n this._pendingUnlinks.delete(path);\n }\n }\n if (awf && (event === EV.ADD || event === EV.CHANGE) && this._readyEmitted) {\n const awfEmit = (err, stats) => {\n if (err) {\n event = EV.ERROR;\n args[0] = err;\n this.emitWithAll(event, args);\n }\n else if (stats) {\n // if stats doesn't exist the file must have been deleted\n if (args.length > 1) {\n args[1] = stats;\n }\n else {\n args.push(stats);\n }\n this.emitWithAll(event, args);\n }\n };\n this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);\n return this;\n }\n if (event === EV.CHANGE) {\n const isThrottled = !this._throttle(EV.CHANGE, path, 50);\n if (isThrottled)\n return this;\n }\n if (opts.alwaysStat &&\n stats === undefined &&\n (event === EV.ADD || event === EV.ADD_DIR || event === EV.CHANGE)) {\n const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;\n let stats;\n try {\n stats = await stat(fullPath);\n }\n catch (err) {\n // do nothing\n }\n // Suppress event when fs_stat fails, to avoid sending undefined 'stat'\n if (!stats || this.closed)\n return;\n args.push(stats);\n }\n this.emitWithAll(event, args);\n return this;\n }\n /**\n * Common handler for errors\n * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag\n */\n _handleError(error) {\n const code = error && error.code;\n if (error &&\n code !== 'ENOENT' &&\n code !== 'ENOTDIR' &&\n (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))) {\n this.emit(EV.ERROR, error);\n }\n return error || this.closed;\n }\n /**\n * Helper utility for throttling\n * @param actionType type being throttled\n * @param path being acted upon\n * @param timeout duration of time to suppress duplicate actions\n * @returns tracking object or false if action should be suppressed\n */\n _throttle(actionType, path, timeout) {\n if (!this._throttled.has(actionType)) {\n this._throttled.set(actionType, new Map());\n }\n const action = this._throttled.get(actionType);\n if (!action)\n throw new Error('invalid throttle');\n const actionPath = action.get(path);\n if (actionPath) {\n actionPath.count++;\n return false;\n }\n // eslint-disable-next-line prefer-const\n let timeoutObject;\n const clear = () => {\n const item = action.get(path);\n const count = item ? item.count : 0;\n action.delete(path);\n clearTimeout(timeoutObject);\n if (item)\n clearTimeout(item.timeoutObject);\n return count;\n };\n timeoutObject = setTimeout(clear, timeout);\n const thr = { timeoutObject, clear, count: 0 };\n action.set(path, thr);\n return thr;\n }\n _incrReadyCount() {\n return this._readyCount++;\n }\n /**\n * Awaits write operation to finish.\n * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.\n * @param path being acted upon\n * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished\n * @param event\n * @param awfEmit Callback to be called when ready for event to be emitted.\n */\n _awaitWriteFinish(path, threshold, event, awfEmit) {\n const awf = this.options.awaitWriteFinish;\n if (typeof awf !== 'object')\n return;\n const pollInterval = awf.pollInterval;\n let timeoutHandler;\n let fullPath = path;\n if (this.options.cwd && !sysPath.isAbsolute(path)) {\n fullPath = sysPath.join(this.options.cwd, path);\n }\n const now = new Date();\n const writes = this._pendingWrites;\n function awaitWriteFinishFn(prevStat) {\n statcb(fullPath, (err, curStat) => {\n if (err || !writes.has(path)) {\n if (err && err.code !== 'ENOENT')\n awfEmit(err);\n return;\n }\n const now = Number(new Date());\n if (prevStat && curStat.size !== prevStat.size) {\n writes.get(path).lastChange = now;\n }\n const pw = writes.get(path);\n const df = now - pw.lastChange;\n if (df >= threshold) {\n writes.delete(path);\n awfEmit(undefined, curStat);\n }\n else {\n timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);\n }\n });\n }\n if (!writes.has(path)) {\n writes.set(path, {\n lastChange: now,\n cancelWait: () => {\n writes.delete(path);\n clearTimeout(timeoutHandler);\n return event;\n },\n });\n timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);\n }\n }\n /**\n * Determines whether user has asked to ignore this path.\n */\n _isIgnored(path, stats) {\n if (this.options.atomic && DOT_RE.test(path))\n return true;\n if (!this._userIgnored) {\n const { cwd } = this.options;\n const ign = this.options.ignored;\n const ignored = (ign || []).map(normalizeIgnored(cwd));\n const ignoredPaths = [...this._ignoredPaths];\n const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];\n this._userIgnored = anymatch(list, undefined);\n }\n return this._userIgnored(path, stats);\n }\n _isntIgnored(path, stat) {\n return !this._isIgnored(path, stat);\n }\n /**\n * Provides a set of common helpers and properties relating to symlink handling.\n * @param path file or directory pattern being watched\n */\n _getWatchHelpers(path) {\n return new WatchHelper(path, this.options.followSymlinks, this);\n }\n // Directory helpers\n // -----------------\n /**\n * Provides directory tracking objects\n * @param directory path of the directory\n */\n _getWatchedDir(directory) {\n const dir = sysPath.resolve(directory);\n if (!this._watched.has(dir))\n this._watched.set(dir, new DirEntry(dir, this._boundRemove));\n return this._watched.get(dir);\n }\n // File helpers\n // ------------\n /**\n * Check for read permissions: https://stackoverflow.com/a/11781404/1358405\n */\n _hasReadPermissions(stats) {\n if (this.options.ignorePermissionErrors)\n return true;\n return Boolean(Number(stats.mode) & 0o400);\n }\n /**\n * Handles emitting unlink events for\n * files and directories, and via recursion, for\n * files and directories within directories that are unlinked\n * @param directory within which the following item is located\n * @param item base path of item/directory\n */\n _remove(directory, item, isDirectory) {\n // if what is being deleted is a directory, get that directory's paths\n // for recursive deleting and cleaning of watched object\n // if it is not a directory, nestedDirectoryChildren will be empty array\n const path = sysPath.join(directory, item);\n const fullPath = sysPath.resolve(path);\n isDirectory =\n isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath);\n // prevent duplicate handling in case of arriving here nearly simultaneously\n // via multiple paths (such as _handleFile and _handleDir)\n if (!this._throttle('remove', path, 100))\n return;\n // if the only watched file is removed, watch for its return\n if (!isDirectory && this._watched.size === 1) {\n this.add(directory, item, true);\n }\n // This will create a new entry in the watched object in either case\n // so we got to do the directory check beforehand\n const wp = this._getWatchedDir(path);\n const nestedDirectoryChildren = wp.getChildren();\n // Recursively remove children directories / files.\n nestedDirectoryChildren.forEach((nested) => this._remove(path, nested));\n // Check if item was on the watched list and remove it\n const parent = this._getWatchedDir(directory);\n const wasTracked = parent.has(item);\n parent.remove(item);\n // Fixes issue #1042 -> Relative paths were detected and added as symlinks\n // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),\n // but never removed from the map in case the path was deleted.\n // This leads to an incorrect state if the path was recreated:\n // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553\n if (this._symlinkPaths.has(fullPath)) {\n this._symlinkPaths.delete(fullPath);\n }\n // If we wait for this file to be fully written, cancel the wait.\n let relPath = path;\n if (this.options.cwd)\n relPath = sysPath.relative(this.options.cwd, path);\n if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {\n const event = this._pendingWrites.get(relPath).cancelWait();\n if (event === EV.ADD)\n return;\n }\n // The Entry will either be a directory that just got removed\n // or a bogus entry to a file, in either case we have to remove it\n this._watched.delete(path);\n this._watched.delete(fullPath);\n const eventName = isDirectory ? EV.UNLINK_DIR : EV.UNLINK;\n if (wasTracked && !this._isIgnored(path))\n this._emit(eventName, path);\n // Avoid conflicts if we later create another file with the same name\n this._closePath(path);\n }\n /**\n * Closes all watchers for a path\n */\n _closePath(path) {\n this._closeFile(path);\n const dir = sysPath.dirname(path);\n this._getWatchedDir(dir).remove(sysPath.basename(path));\n }\n /**\n * Closes only file-specific watchers\n */\n _closeFile(path) {\n const closers = this._closers.get(path);\n if (!closers)\n return;\n closers.forEach((closer) => closer());\n this._closers.delete(path);\n }\n _addPathCloser(path, closer) {\n if (!closer)\n return;\n let list = this._closers.get(path);\n if (!list) {\n list = [];\n this._closers.set(path, list);\n }\n list.push(closer);\n }\n _readdirp(root, opts) {\n if (this.closed)\n return;\n const options = { type: EV.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };\n let stream = readdirp(root, options);\n this._streams.add(stream);\n stream.once(STR_CLOSE, () => {\n stream = undefined;\n });\n stream.once(STR_END, () => {\n if (stream) {\n this._streams.delete(stream);\n stream = undefined;\n }\n });\n return stream;\n }\n}\n/**\n * Instantiates watcher with paths to be tracked.\n * @param paths file / directory paths\n * @param options opts, such as `atomic`, `awaitWriteFinish`, `ignored`, and others\n * @returns an instance of FSWatcher for chaining.\n * @example\n * const watcher = watch('.').on('all', (event, path) => { console.log(event, path); });\n * watch('.', { atomic: true, awaitWriteFinish: true, ignored: (f, stats) => stats?.isFile() && !f.endsWith('.js') })\n */\nexport function watch(paths, options = {}) {\n const watcher = new FSWatcher(options);\n watcher.add(paths);\n return watcher;\n}\nexport default { watch, FSWatcher };\n","import { stat, lstat, readdir, realpath } from 'node:fs/promises';\nimport { Readable } from 'node:stream';\nimport { resolve as presolve, relative as prelative, join as pjoin, sep as psep } from 'node:path';\nexport const EntryTypes = {\n FILE_TYPE: 'files',\n DIR_TYPE: 'directories',\n FILE_DIR_TYPE: 'files_directories',\n EVERYTHING_TYPE: 'all',\n};\nconst defaultOptions = {\n root: '.',\n fileFilter: (_entryInfo) => true,\n directoryFilter: (_entryInfo) => true,\n type: EntryTypes.FILE_TYPE,\n lstat: false,\n depth: 2147483648,\n alwaysStat: false,\n highWaterMark: 4096,\n};\nObject.freeze(defaultOptions);\nconst RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';\nconst NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);\nconst ALL_TYPES = [\n EntryTypes.DIR_TYPE,\n EntryTypes.EVERYTHING_TYPE,\n EntryTypes.FILE_DIR_TYPE,\n EntryTypes.FILE_TYPE,\n];\nconst DIR_TYPES = new Set([\n EntryTypes.DIR_TYPE,\n EntryTypes.EVERYTHING_TYPE,\n EntryTypes.FILE_DIR_TYPE,\n]);\nconst FILE_TYPES = new Set([\n EntryTypes.EVERYTHING_TYPE,\n EntryTypes.FILE_DIR_TYPE,\n EntryTypes.FILE_TYPE,\n]);\nconst isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code);\nconst wantBigintFsStats = process.platform === 'win32';\nconst emptyFn = (_entryInfo) => true;\nconst normalizeFilter = (filter) => {\n if (filter === undefined)\n return emptyFn;\n if (typeof filter === 'function')\n return filter;\n if (typeof filter === 'string') {\n const fl = filter.trim();\n return (entry) => entry.basename === fl;\n }\n if (Array.isArray(filter)) {\n const trItems = filter.map((item) => item.trim());\n return (entry) => trItems.some((f) => entry.basename === f);\n }\n return emptyFn;\n};\n/** Readable readdir stream, emitting new files as they're being listed. */\nexport class ReaddirpStream extends Readable {\n constructor(options = {}) {\n super({\n objectMode: true,\n autoDestroy: true,\n highWaterMark: options.highWaterMark,\n });\n const opts = { ...defaultOptions, ...options };\n const { root, type } = opts;\n this._fileFilter = normalizeFilter(opts.fileFilter);\n this._directoryFilter = normalizeFilter(opts.directoryFilter);\n const statMethod = opts.lstat ? lstat : stat;\n // Use bigint stats if it's windows and stat() supports options (node 10+).\n if (wantBigintFsStats) {\n this._stat = (path) => statMethod(path, { bigint: true });\n }\n else {\n this._stat = statMethod;\n }\n this._maxDepth = opts.depth ?? defaultOptions.depth;\n this._wantsDir = type ? DIR_TYPES.has(type) : false;\n this._wantsFile = type ? FILE_TYPES.has(type) : false;\n this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;\n this._root = presolve(root);\n this._isDirent = !opts.alwaysStat;\n this._statsProp = this._isDirent ? 'dirent' : 'stats';\n this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };\n // Launch stream with one parent, the root dir.\n this.parents = [this._exploreDir(root, 1)];\n this.reading = false;\n this.parent = undefined;\n }\n async _read(batch) {\n if (this.reading)\n return;\n this.reading = true;\n try {\n while (!this.destroyed && batch > 0) {\n const par = this.parent;\n const fil = par && par.files;\n if (fil && fil.length > 0) {\n const { path, depth } = par;\n const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path));\n const awaited = await Promise.all(slice);\n for (const entry of awaited) {\n if (!entry)\n continue;\n if (this.destroyed)\n return;\n const entryType = await this._getEntryType(entry);\n if (entryType === 'directory' && this._directoryFilter(entry)) {\n if (depth <= this._maxDepth) {\n this.parents.push(this._exploreDir(entry.fullPath, depth + 1));\n }\n if (this._wantsDir) {\n this.push(entry);\n batch--;\n }\n }\n else if ((entryType === 'file' || this._includeAsFile(entry)) &&\n this._fileFilter(entry)) {\n if (this._wantsFile) {\n this.push(entry);\n batch--;\n }\n }\n }\n }\n else {\n const parent = this.parents.pop();\n if (!parent) {\n this.push(null);\n break;\n }\n this.parent = await parent;\n if (this.destroyed)\n return;\n }\n }\n }\n catch (error) {\n this.destroy(error);\n }\n finally {\n this.reading = false;\n }\n }\n async _exploreDir(path, depth) {\n let files;\n try {\n files = await readdir(path, this._rdOptions);\n }\n catch (error) {\n this._onError(error);\n }\n return { files, depth, path };\n }\n async _formatEntry(dirent, path) {\n let entry;\n const basename = this._isDirent ? dirent.name : dirent;\n try {\n const fullPath = presolve(pjoin(path, basename));\n entry = { path: prelative(this._root, fullPath), fullPath, basename };\n entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);\n }\n catch (err) {\n this._onError(err);\n return;\n }\n return entry;\n }\n _onError(err) {\n if (isNormalFlowError(err) && !this.destroyed) {\n this.emit('warn', err);\n }\n else {\n this.destroy(err);\n }\n }\n async _getEntryType(entry) {\n // entry may be undefined, because a warning or an error were emitted\n // and the statsProp is undefined\n if (!entry && this._statsProp in entry) {\n return '';\n }\n const stats = entry[this._statsProp];\n if (stats.isFile())\n return 'file';\n if (stats.isDirectory())\n return 'directory';\n if (stats && stats.isSymbolicLink()) {\n const full = entry.fullPath;\n try {\n const entryRealPath = await realpath(full);\n const entryRealPathStats = await lstat(entryRealPath);\n if (entryRealPathStats.isFile()) {\n return 'file';\n }\n if (entryRealPathStats.isDirectory()) {\n const len = entryRealPath.length;\n if (full.startsWith(entryRealPath) && full.substr(len, 1) === psep) {\n const recursiveError = new Error(`Circular symlink detected: \"${full}\" points to \"${entryRealPath}\"`);\n // @ts-ignore\n recursiveError.code = RECURSIVE_ERROR_CODE;\n return this._onError(recursiveError);\n }\n return 'directory';\n }\n }\n catch (error) {\n this._onError(error);\n return '';\n }\n }\n }\n _includeAsFile(entry) {\n const stats = entry && entry[this._statsProp];\n return stats && this._wantsEverything && !stats.isDirectory();\n }\n}\n/**\n * Streaming version: Reads all files and directories in given root recursively.\n * Consumes ~constant small amount of RAM.\n * @param root Root directory\n * @param options Options to specify root (start directory), filters and recursion depth\n */\nexport function readdirp(root, options = {}) {\n // @ts-ignore\n let type = options.entryType || options.type;\n if (type === 'both')\n type = EntryTypes.FILE_DIR_TYPE; // backwards-compatibility\n if (type)\n options.type = type;\n if (!root) {\n throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');\n }\n else if (typeof root !== 'string') {\n throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');\n }\n else if (type && !ALL_TYPES.includes(type)) {\n throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);\n }\n options.root = root;\n return new ReaddirpStream(options);\n}\n/**\n * Promise version: Reads all files and directories in given root recursively.\n * Compared to streaming version, will consume a lot of RAM e.g. when 1 million files are listed.\n * @returns array of paths and their entry infos\n */\nexport function readdirpPromise(root, options = {}) {\n return new Promise((resolve, reject) => {\n const files = [];\n readdirp(root, options)\n .on('data', (entry) => files.push(entry))\n .on('end', () => resolve(files))\n .on('error', (error) => reject(error));\n });\n}\nexport default readdirp;\n","import { watchFile, unwatchFile, watch as fs_watch } from 'fs';\nimport { open, stat, lstat, realpath as fsrealpath } from 'fs/promises';\nimport * as sysPath from 'path';\nimport { type as osType } from 'os';\nexport const STR_DATA = 'data';\nexport const STR_END = 'end';\nexport const STR_CLOSE = 'close';\nexport const EMPTY_FN = () => { };\nexport const IDENTITY_FN = (val) => val;\nconst pl = process.platform;\nexport const isWindows = pl === 'win32';\nexport const isMacos = pl === 'darwin';\nexport const isLinux = pl === 'linux';\nexport const isFreeBSD = pl === 'freebsd';\nexport const isIBMi = osType() === 'OS400';\nexport const EVENTS = {\n ALL: 'all',\n READY: 'ready',\n ADD: 'add',\n CHANGE: 'change',\n ADD_DIR: 'addDir',\n UNLINK: 'unlink',\n UNLINK_DIR: 'unlinkDir',\n RAW: 'raw',\n ERROR: 'error',\n};\nconst EV = EVENTS;\nconst THROTTLE_MODE_WATCH = 'watch';\nconst statMethods = { lstat, stat };\nconst KEY_LISTENERS = 'listeners';\nconst KEY_ERR = 'errHandlers';\nconst KEY_RAW = 'rawEmitters';\nconst HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];\n// prettier-ignore\nconst binaryExtensions = new Set([\n '3dm', '3ds', '3g2', '3gp', '7z', 'a', 'aac', 'adp', 'afdesign', 'afphoto', 'afpub', 'ai',\n 'aif', 'aiff', 'alz', 'ape', 'apk', 'appimage', 'ar', 'arj', 'asf', 'au', 'avi',\n 'bak', 'baml', 'bh', 'bin', 'bk', 'bmp', 'btif', 'bz2', 'bzip2',\n 'cab', 'caf', 'cgm', 'class', 'cmx', 'cpio', 'cr2', 'cur', 'dat', 'dcm', 'deb', 'dex', 'djvu',\n 'dll', 'dmg', 'dng', 'doc', 'docm', 'docx', 'dot', 'dotm', 'dra', 'DS_Store', 'dsk', 'dts',\n 'dtshd', 'dvb', 'dwg', 'dxf',\n 'ecelp4800', 'ecelp7470', 'ecelp9600', 'egg', 'eol', 'eot', 'epub', 'exe',\n 'f4v', 'fbs', 'fh', 'fla', 'flac', 'flatpak', 'fli', 'flv', 'fpx', 'fst', 'fvt',\n 'g3', 'gh', 'gif', 'graffle', 'gz', 'gzip',\n 'h261', 'h263', 'h264', 'icns', 'ico', 'ief', 'img', 'ipa', 'iso',\n 'jar', 'jpeg', 'jpg', 'jpgv', 'jpm', 'jxr', 'key', 'ktx',\n 'lha', 'lib', 'lvp', 'lz', 'lzh', 'lzma', 'lzo',\n 'm3u', 'm4a', 'm4v', 'mar', 'mdi', 'mht', 'mid', 'midi', 'mj2', 'mka', 'mkv', 'mmr', 'mng',\n 'mobi', 'mov', 'movie', 'mp3',\n 'mp4', 'mp4a', 'mpeg', 'mpg', 'mpga', 'mxu',\n 'nef', 'npx', 'numbers', 'nupkg',\n 'o', 'odp', 'ods', 'odt', 'oga', 'ogg', 'ogv', 'otf', 'ott',\n 'pages', 'pbm', 'pcx', 'pdb', 'pdf', 'pea', 'pgm', 'pic', 'png', 'pnm', 'pot', 'potm',\n 'potx', 'ppa', 'ppam',\n 'ppm', 'pps', 'ppsm', 'ppsx', 'ppt', 'pptm', 'pptx', 'psd', 'pya', 'pyc', 'pyo', 'pyv',\n 'qt',\n 'rar', 'ras', 'raw', 'resources', 'rgb', 'rip', 'rlc', 'rmf', 'rmvb', 'rpm', 'rtf', 'rz',\n 's3m', 's7z', 'scpt', 'sgi', 'shar', 'snap', 'sil', 'sketch', 'slk', 'smv', 'snk', 'so',\n 'stl', 'suo', 'sub', 'swf',\n 'tar', 'tbz', 'tbz2', 'tga', 'tgz', 'thmx', 'tif', 'tiff', 'tlz', 'ttc', 'ttf', 'txz',\n 'udf', 'uvh', 'uvi', 'uvm', 'uvp', 'uvs', 'uvu',\n 'viv', 'vob',\n 'war', 'wav', 'wax', 'wbmp', 'wdp', 'weba', 'webm', 'webp', 'whl', 'wim', 'wm', 'wma',\n 'wmv', 'wmx', 'woff', 'woff2', 'wrm', 'wvx',\n 'xbm', 'xif', 'xla', 'xlam', 'xls', 'xlsb', 'xlsm', 'xlsx', 'xlt', 'xltm', 'xltx', 'xm',\n 'xmind', 'xpi', 'xpm', 'xwd', 'xz',\n 'z', 'zip', 'zipx',\n]);\nconst isBinaryPath = (filePath) => binaryExtensions.has(sysPath.extname(filePath).slice(1).toLowerCase());\n// TODO: emit errors properly. Example: EMFILE on Macos.\nconst foreach = (val, fn) => {\n if (val instanceof Set) {\n val.forEach(fn);\n }\n else {\n fn(val);\n }\n};\nconst addAndConvert = (main, prop, item) => {\n let container = main[prop];\n if (!(container instanceof Set)) {\n main[prop] = container = new Set([container]);\n }\n container.add(item);\n};\nconst clearItem = (cont) => (key) => {\n const set = cont[key];\n if (set instanceof Set) {\n set.clear();\n }\n else {\n delete cont[key];\n }\n};\nconst delFromSet = (main, prop, item) => {\n const container = main[prop];\n if (container instanceof Set) {\n container.delete(item);\n }\n else if (container === item) {\n delete main[prop];\n }\n};\nconst isEmptySet = (val) => (val instanceof Set ? val.size === 0 : !val);\nconst FsWatchInstances = new Map();\n/**\n * Instantiates the fs_watch interface\n * @param path to be watched\n * @param options to be passed to fs_watch\n * @param listener main event handler\n * @param errHandler emits info about errors\n * @param emitRaw emits raw event data\n * @returns {NativeFsWatcher}\n */\nfunction createFsWatchInstance(path, options, listener, errHandler, emitRaw) {\n const handleEvent = (rawEvent, evPath) => {\n listener(path);\n emitRaw(rawEvent, evPath, { watchedPath: path });\n // emit based on events occurring for files from a directory's watcher in\n // case the file's watcher misses it (and rely on throttling to de-dupe)\n if (evPath && path !== evPath) {\n fsWatchBroadcast(sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath));\n }\n };\n try {\n return fs_watch(path, {\n persistent: options.persistent,\n }, handleEvent);\n }\n catch (error) {\n errHandler(error);\n return undefined;\n }\n}\n/**\n * Helper for passing fs_watch event data to a collection of listeners\n * @param fullPath absolute path bound to fs_watch instance\n */\nconst fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {\n const cont = FsWatchInstances.get(fullPath);\n if (!cont)\n return;\n foreach(cont[listenerType], (listener) => {\n listener(val1, val2, val3);\n });\n};\n/**\n * Instantiates the fs_watch interface or binds listeners\n * to an existing one covering the same file system entry\n * @param path\n * @param fullPath absolute path\n * @param options to be passed to fs_watch\n * @param handlers container for event listener functions\n */\nconst setFsWatchListener = (path, fullPath, options, handlers) => {\n const { listener, errHandler, rawEmitter } = handlers;\n let cont = FsWatchInstances.get(fullPath);\n let watcher;\n if (!options.persistent) {\n watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter);\n if (!watcher)\n return;\n return watcher.close.bind(watcher);\n }\n if (cont) {\n addAndConvert(cont, KEY_LISTENERS, listener);\n addAndConvert(cont, KEY_ERR, errHandler);\n addAndConvert(cont, KEY_RAW, rawEmitter);\n }\n else {\n watcher = createFsWatchInstance(path, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, // no need to use broadcast here\n fsWatchBroadcast.bind(null, fullPath, KEY_RAW));\n if (!watcher)\n return;\n watcher.on(EV.ERROR, async (error) => {\n const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);\n if (cont)\n cont.watcherUnusable = true; // documented since Node 10.4.1\n // Workaround for https://github.com/joyent/node/issues/4337\n if (isWindows && error.code === 'EPERM') {\n try {\n const fd = await open(path, 'r');\n await fd.close();\n broadcastErr(error);\n }\n catch (err) {\n // do nothing\n }\n }\n else {\n broadcastErr(error);\n }\n });\n cont = {\n listeners: listener,\n errHandlers: errHandler,\n rawEmitters: rawEmitter,\n watcher,\n };\n FsWatchInstances.set(fullPath, cont);\n }\n // const index = cont.listeners.indexOf(listener);\n // removes this instance's listeners and closes the underlying fs_watch\n // instance if there are no more listeners left\n return () => {\n delFromSet(cont, KEY_LISTENERS, listener);\n delFromSet(cont, KEY_ERR, errHandler);\n delFromSet(cont, KEY_RAW, rawEmitter);\n if (isEmptySet(cont.listeners)) {\n // Check to protect against issue gh-730.\n // if (cont.watcherUnusable) {\n cont.watcher.close();\n // }\n FsWatchInstances.delete(fullPath);\n HANDLER_KEYS.forEach(clearItem(cont));\n // @ts-ignore\n cont.watcher = undefined;\n Object.freeze(cont);\n }\n };\n};\n// fs_watchFile helpers\n// object to hold per-process fs_watchFile instances\n// (may be shared across chokidar FSWatcher instances)\nconst FsWatchFileInstances = new Map();\n/**\n * Instantiates the fs_watchFile interface or binds listeners\n * to an existing one covering the same file system entry\n * @param path to be watched\n * @param fullPath absolute path\n * @param options options to be passed to fs_watchFile\n * @param handlers container for event listener functions\n * @returns closer\n */\nconst setFsWatchFileListener = (path, fullPath, options, handlers) => {\n const { listener, rawEmitter } = handlers;\n let cont = FsWatchFileInstances.get(fullPath);\n // let listeners = new Set();\n // let rawEmitters = new Set();\n const copts = cont && cont.options;\n if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {\n // \"Upgrade\" the watcher to persistence or a quicker interval.\n // This creates some unlikely edge case issues if the user mixes\n // settings in a very weird way, but solving for those cases\n // doesn't seem worthwhile for the added complexity.\n // listeners = cont.listeners;\n // rawEmitters = cont.rawEmitters;\n unwatchFile(fullPath);\n cont = undefined;\n }\n if (cont) {\n addAndConvert(cont, KEY_LISTENERS, listener);\n addAndConvert(cont, KEY_RAW, rawEmitter);\n }\n else {\n // TODO\n // listeners.add(listener);\n // rawEmitters.add(rawEmitter);\n cont = {\n listeners: listener,\n rawEmitters: rawEmitter,\n options,\n watcher: watchFile(fullPath, options, (curr, prev) => {\n foreach(cont.rawEmitters, (rawEmitter) => {\n rawEmitter(EV.CHANGE, fullPath, { curr, prev });\n });\n const currmtime = curr.mtimeMs;\n if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {\n foreach(cont.listeners, (listener) => listener(path, curr));\n }\n }),\n };\n FsWatchFileInstances.set(fullPath, cont);\n }\n // const index = cont.listeners.indexOf(listener);\n // Removes this instance's listeners and closes the underlying fs_watchFile\n // instance if there are no more listeners left.\n return () => {\n delFromSet(cont, KEY_LISTENERS, listener);\n delFromSet(cont, KEY_RAW, rawEmitter);\n if (isEmptySet(cont.listeners)) {\n FsWatchFileInstances.delete(fullPath);\n unwatchFile(fullPath);\n cont.options = cont.watcher = undefined;\n Object.freeze(cont);\n }\n };\n};\n/**\n * @mixin\n */\nexport class NodeFsHandler {\n constructor(fsW) {\n this.fsw = fsW;\n this._boundHandleError = (error) => fsW._handleError(error);\n }\n /**\n * Watch file for changes with fs_watchFile or fs_watch.\n * @param path to file or dir\n * @param listener on fs change\n * @returns closer for the watcher instance\n */\n _watchWithNodeFs(path, listener) {\n const opts = this.fsw.options;\n const directory = sysPath.dirname(path);\n const basename = sysPath.basename(path);\n const parent = this.fsw._getWatchedDir(directory);\n parent.add(basename);\n const absolutePath = sysPath.resolve(path);\n const options = {\n persistent: opts.persistent,\n };\n if (!listener)\n listener = EMPTY_FN;\n let closer;\n if (opts.usePolling) {\n const enableBin = opts.interval !== opts.binaryInterval;\n options.interval = enableBin && isBinaryPath(basename) ? opts.binaryInterval : opts.interval;\n closer = setFsWatchFileListener(path, absolutePath, options, {\n listener,\n rawEmitter: this.fsw._emitRaw,\n });\n }\n else {\n closer = setFsWatchListener(path, absolutePath, options, {\n listener,\n errHandler: this._boundHandleError,\n rawEmitter: this.fsw._emitRaw,\n });\n }\n return closer;\n }\n /**\n * Watch a file and emit add event if warranted.\n * @returns closer for the watcher instance\n */\n _handleFile(file, stats, initialAdd) {\n if (this.fsw.closed) {\n return;\n }\n const dirname = sysPath.dirname(file);\n const basename = sysPath.basename(file);\n const parent = this.fsw._getWatchedDir(dirname);\n // stats is always present\n let prevStats = stats;\n // if the file is already being watched, do nothing\n if (parent.has(basename))\n return;\n const listener = async (path, newStats) => {\n if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5))\n return;\n if (!newStats || newStats.mtimeMs === 0) {\n try {\n const newStats = await stat(file);\n if (this.fsw.closed)\n return;\n // Check that change event was not fired because of changed only accessTime.\n const at = newStats.atimeMs;\n const mt = newStats.mtimeMs;\n if (!at || at <= mt || mt !== prevStats.mtimeMs) {\n this.fsw._emit(EV.CHANGE, file, newStats);\n }\n if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats.ino) {\n this.fsw._closeFile(path);\n prevStats = newStats;\n const closer = this._watchWithNodeFs(file, listener);\n if (closer)\n this.fsw._addPathCloser(path, closer);\n }\n else {\n prevStats = newStats;\n }\n }\n catch (error) {\n // Fix issues where mtime is null but file is still present\n this.fsw._remove(dirname, basename);\n }\n // add is about to be emitted if file not already tracked in parent\n }\n else if (parent.has(basename)) {\n // Check that change event was not fired because of changed only accessTime.\n const at = newStats.atimeMs;\n const mt = newStats.mtimeMs;\n if (!at || at <= mt || mt !== prevStats.mtimeMs) {\n this.fsw._emit(EV.CHANGE, file, newStats);\n }\n prevStats = newStats;\n }\n };\n // kick off the watcher\n const closer = this._watchWithNodeFs(file, listener);\n // emit an add event if we're supposed to\n if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {\n if (!this.fsw._throttle(EV.ADD, file, 0))\n return;\n this.fsw._emit(EV.ADD, file, stats);\n }\n return closer;\n }\n /**\n * Handle symlinks encountered while reading a dir.\n * @param entry returned by readdirp\n * @param directory path of dir being read\n * @param path of this item\n * @param item basename of this item\n * @returns true if no more processing is needed for this entry.\n */\n async _handleSymlink(entry, directory, path, item) {\n if (this.fsw.closed) {\n return;\n }\n const full = entry.fullPath;\n const dir = this.fsw._getWatchedDir(directory);\n if (!this.fsw.options.followSymlinks) {\n // watch symlink directly (don't follow) and detect changes\n this.fsw._incrReadyCount();\n let linkPath;\n try {\n linkPath = await fsrealpath(path);\n }\n catch (e) {\n this.fsw._emitReady();\n return true;\n }\n if (this.fsw.closed)\n return;\n if (dir.has(item)) {\n if (this.fsw._symlinkPaths.get(full) !== linkPath) {\n this.fsw._symlinkPaths.set(full, linkPath);\n this.fsw._emit(EV.CHANGE, path, entry.stats);\n }\n }\n else {\n dir.add(item);\n this.fsw._symlinkPaths.set(full, linkPath);\n this.fsw._emit(EV.ADD, path, entry.stats);\n }\n this.fsw._emitReady();\n return true;\n }\n // don't follow the same symlink more than once\n if (this.fsw._symlinkPaths.has(full)) {\n return true;\n }\n this.fsw._symlinkPaths.set(full, true);\n }\n _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {\n // Normalize the directory name on Windows\n directory = sysPath.join(directory, '');\n throttler = this.fsw._throttle('readdir', directory, 1000);\n if (!throttler)\n return;\n const previous = this.fsw._getWatchedDir(wh.path);\n const current = new Set();\n let stream = this.fsw._readdirp(directory, {\n fileFilter: (entry) => wh.filterPath(entry),\n directoryFilter: (entry) => wh.filterDir(entry),\n });\n if (!stream)\n return;\n stream\n .on(STR_DATA, async (entry) => {\n if (this.fsw.closed) {\n stream = undefined;\n return;\n }\n const item = entry.path;\n let path = sysPath.join(directory, item);\n current.add(item);\n if (entry.stats.isSymbolicLink() &&\n (await this._handleSymlink(entry, directory, path, item))) {\n return;\n }\n if (this.fsw.closed) {\n stream = undefined;\n return;\n }\n // Files that present in current directory snapshot\n // but absent in previous are added to watch list and\n // emit `add` event.\n if (item === target || (!target && !previous.has(item))) {\n this.fsw._incrReadyCount();\n // ensure relativeness of path is preserved in case of watcher reuse\n path = sysPath.join(dir, sysPath.relative(dir, path));\n this._addToNodeFs(path, initialAdd, wh, depth + 1);\n }\n })\n .on(EV.ERROR, this._boundHandleError);\n return new Promise((resolve, reject) => {\n if (!stream)\n return reject();\n stream.once(STR_END, () => {\n if (this.fsw.closed) {\n stream = undefined;\n return;\n }\n const wasThrottled = throttler ? throttler.clear() : false;\n resolve(undefined);\n // Files that absent in current directory snapshot\n // but present in previous emit `remove` event\n // and are removed from @watched[directory].\n previous\n .getChildren()\n .filter((item) => {\n return item !== directory && !current.has(item);\n })\n .forEach((item) => {\n this.fsw._remove(directory, item);\n });\n stream = undefined;\n // one more time for any missed in case changes came in extremely quickly\n if (wasThrottled)\n this._handleRead(directory, false, wh, target, dir, depth, throttler);\n });\n });\n }\n /**\n * Read directory to add / remove files from `@watched` list and re-read it on change.\n * @param dir fs path\n * @param stats\n * @param initialAdd\n * @param depth relative to user-supplied path\n * @param target child path targeted for watch\n * @param wh Common watch helpers for this path\n * @param realpath\n * @returns closer for the watcher instance.\n */\n async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {\n const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));\n const tracked = parentDir.has(sysPath.basename(dir));\n if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {\n this.fsw._emit(EV.ADD_DIR, dir, stats);\n }\n // ensure dir is tracked (harmless if redundant)\n parentDir.add(sysPath.basename(dir));\n this.fsw._getWatchedDir(dir);\n let throttler;\n let closer;\n const oDepth = this.fsw.options.depth;\n if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {\n if (!target) {\n await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);\n if (this.fsw.closed)\n return;\n }\n closer = this._watchWithNodeFs(dir, (dirPath, stats) => {\n // if current directory is removed, do nothing\n if (stats && stats.mtimeMs === 0)\n return;\n this._handleRead(dirPath, false, wh, target, dir, depth, throttler);\n });\n }\n return closer;\n }\n /**\n * Handle added file, directory, or glob pattern.\n * Delegates call to _handleFile / _handleDir after checks.\n * @param path to file or ir\n * @param initialAdd was the file added at watch instantiation?\n * @param priorWh depth relative to user-supplied path\n * @param depth Child path actually targeted for watch\n * @param target Child path actually targeted for watch\n */\n async _addToNodeFs(path, initialAdd, priorWh, depth, target) {\n const ready = this.fsw._emitReady;\n if (this.fsw._isIgnored(path) || this.fsw.closed) {\n ready();\n return false;\n }\n const wh = this.fsw._getWatchHelpers(path);\n if (priorWh) {\n wh.filterPath = (entry) => priorWh.filterPath(entry);\n wh.filterDir = (entry) => priorWh.filterDir(entry);\n }\n // evaluate what is at the path we're being asked to watch\n try {\n const stats = await statMethods[wh.statMethod](wh.watchPath);\n if (this.fsw.closed)\n return;\n if (this.fsw._isIgnored(wh.watchPath, stats)) {\n ready();\n return false;\n }\n const follow = this.fsw.options.followSymlinks;\n let closer;\n if (stats.isDirectory()) {\n const absPath = sysPath.resolve(path);\n const targetPath = follow ? await fsrealpath(path) : path;\n if (this.fsw.closed)\n return;\n closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);\n if (this.fsw.closed)\n return;\n // preserve this symlink's target path\n if (absPath !== targetPath && targetPath !== undefined) {\n this.fsw._symlinkPaths.set(absPath, targetPath);\n }\n }\n else if (stats.isSymbolicLink()) {\n const targetPath = follow ? await fsrealpath(path) : path;\n if (this.fsw.closed)\n return;\n const parent = sysPath.dirname(wh.watchPath);\n this.fsw._getWatchedDir(parent).add(wh.watchPath);\n this.fsw._emit(EV.ADD, wh.watchPath, stats);\n closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);\n if (this.fsw.closed)\n return;\n // preserve this symlink's target path\n if (targetPath !== undefined) {\n this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath);\n }\n }\n else {\n closer = this._handleFile(wh.watchPath, stats, initialAdd);\n }\n ready();\n if (closer)\n this.fsw._addPathCloser(path, closer);\n return false;\n }\n catch (error) {\n if (this.fsw._handleError(error)) {\n ready();\n return path;\n }\n }\n }\n}\n","import { z } from 'zod';\n\nimport { validateBody } from './body';\nimport { validateParams } from './params';\nimport { validateQuery } from './query';\nimport { validateResponse } from './response';\nimport { InternalServerError } from '../../errors/internal-server-error';\nimport { ValidationError } from '../../errors/validation-error';\n\nimport type { Context } from '@blaize-types/context';\nimport type { Middleware, MiddlewareFunction, NextFunction } from '@blaize-types/middleware';\nimport type { RouteSchema } from '@blaize-types/router';\n\n/**\n * Create a validation middleware for request data\n */\nexport function createRequestValidator(schema: RouteSchema, debug: boolean = false): Middleware {\n const middlewareFn: MiddlewareFunction = async (ctx: Context, next: NextFunction) => {\n // Validate params if schema exists - throw immediately on failure\n if (schema.params && ctx.request.params) {\n try {\n ctx.request.params = validateParams(ctx.request.params, schema.params);\n } catch (error) {\n const fieldErrors = extractZodFieldErrors(error);\n const errorCount = fieldErrors.reduce((sum, fe) => sum + fe.messages.length, 0);\n\n throw new ValidationError('Request validation failed', {\n fields: fieldErrors,\n errorCount,\n section: 'params',\n });\n }\n }\n\n // Validate query if schema exists - throw immediately on failure\n if (schema.query && ctx.request.query) {\n try {\n ctx.request.query = validateQuery(ctx.request.query, schema.query);\n } catch (error) {\n const fieldErrors = extractZodFieldErrors(error);\n const errorCount = fieldErrors.reduce((sum, fe) => sum + fe.messages.length, 0);\n\n throw new ValidationError('Request validation failed', {\n fields: fieldErrors,\n errorCount,\n section: 'query',\n });\n }\n }\n\n // Validate body if schema exists - throw immediately on failure\n if (schema.body) {\n try {\n ctx.request.body = validateBody(ctx.request.body, schema.body);\n } catch (error) {\n const fieldErrors = extractZodFieldErrors(error);\n const errorCount = fieldErrors.reduce((sum, fe) => sum + fe.messages.length, 0);\n\n throw new ValidationError('Request validation failed', {\n fields: fieldErrors,\n errorCount,\n section: 'body',\n });\n }\n }\n // Continue if validation passed\n await next();\n };\n\n return {\n name: 'RequestValidator',\n execute: middlewareFn,\n debug,\n };\n}\n\n/**\n * Create a validation middleware for response data\n */\nexport function createResponseValidator<T>(\n responseSchema: z.ZodType<T, z.ZodTypeDef, unknown>,\n debug: boolean = false\n): Middleware {\n const middlewareFn: MiddlewareFunction = async (ctx, next) => {\n // Store the original json method\n const originalJson = ctx.response.json;\n\n // Override the json method to validate the response\n ctx.response.json = (body: unknown, status?: number) => {\n try {\n // Validate the response body\n const validatedBody = validateResponse(body, responseSchema);\n\n // Restore the original json method\n ctx.response.json = originalJson;\n\n // Send the validated response\n return originalJson.call(ctx.response, validatedBody, status);\n } catch (error) {\n // Restore the original json method\n ctx.response.json = originalJson;\n\n throw new InternalServerError('Response validation failed', {\n responseSchema: responseSchema.description || 'Unknown schema',\n validationError: extractZodFieldErrors(error),\n originalResponse: body,\n });\n }\n };\n\n await next();\n };\n\n return {\n name: 'ResponseValidator',\n execute: middlewareFn,\n debug,\n };\n}\n\n/**\n * Extract structured field errors from Zod validation errors\n *\n * Converts Zod errors into a clean array of error messages per field.\n *\n * @param error - The validation error (typically a ZodError)\n * @returns Array of error messages for the field\n *\n * @example\n * ```typescript\n * const zodError = new z.ZodError([\n * { path: ['email'], message: 'Invalid email' },\n * { path: ['email'], message: 'Email is required' }\n * ]);\n *\n * const fieldErrors = extractZodFieldErrors(zodError);\n * // Returns: ['Invalid email', 'Email is required']\n * ```\n */\nfunction extractZodFieldErrors(error: unknown): { field: string; messages: string[] }[] {\n if (error instanceof z.ZodError) {\n // Group errors by field path\n const fieldErrorMap = new Map<string, string[]>();\n\n for (const issue of error.issues) {\n // Get the field path (e.g., ['user', 'email'] becomes 'user.email')\n const fieldPath = issue.path.length > 0 ? issue.path.join('.') : 'root';\n\n if (!fieldErrorMap.has(fieldPath)) {\n fieldErrorMap.set(fieldPath, []);\n }\n fieldErrorMap.get(fieldPath)!.push(issue.message);\n }\n\n // Convert map to array of field errors\n return Array.from(fieldErrorMap.entries()).map(([field, messages]) => ({\n field,\n messages,\n }));\n }\n\n if (error instanceof Error) {\n return [{ field: 'unknown', messages: [error.message] }];\n }\n\n return [{ field: 'unknown', messages: [String(error)] }];\n}\n\n/**\n * 🔄 DEPRECATED: Keep for backward compatibility but mark as deprecated\n *\n * This function maintains the old API for any existing code that might depend on it.\n * New code should use extractZodFieldErrors for better structured error handling.\n *\n * @deprecated Use extractZodFieldErrors instead for better structured error details\n * @param error - The validation error to format\n * @returns Formatted error object (maintains old structure)\n */\nexport function formatValidationError(error: unknown): unknown {\n // Handle Zod errors\n if (\n error &&\n typeof error === 'object' &&\n 'format' in error &&\n typeof error.format === 'function'\n ) {\n return error.format();\n }\n\n // Handle other error types\n return error instanceof Error ? error.message : String(error);\n}\n","import { z } from 'zod';\n\n/**\n * Validate request body\n */\nexport function validateBody<T>(body: unknown, schema: z.ZodType<T>): T {\n if (schema instanceof z.ZodObject) {\n return schema.strict().parse(body) as T;\n }\n // Parse and validate with the provided schema\n return schema.parse(body);\n}\n","import { z } from 'zod';\n\n/**\n * Validate request parameters\n */\nexport function validateParams<T>(\n params: Record<string, string>,\n schema: z.ZodType<T, z.ZodTypeDef, unknown>\n): T {\n if (schema instanceof z.ZodObject) {\n // If schema is an object, ensure strict parsing\n return schema.strict().parse(params) as T;\n }\n // Parse and validate with the provided schema\n return schema.parse(params);\n}\n","import { z } from 'zod';\n\n/**\n * Validate query parameters\n */\nexport function validateQuery<T>(\n query: Record<string, string | string[] | undefined>,\n schema: z.ZodType<T, z.ZodTypeDef, unknown>\n): T {\n if (schema instanceof z.ZodObject) {\n // If schema is an object, ensure strict parsing\n return schema.strict().parse(query) as T;\n }\n // Parse and validate with the provided schema\n return schema.parse(query);\n}\n","import { z } from 'zod';\n\n/**\n * Validate response body\n */\nexport function validateResponse<T>(\n response: unknown,\n schema: z.ZodType<T, z.ZodTypeDef, unknown>\n): T {\n if (schema instanceof z.ZodObject) {\n return schema.strict().parse(response) as T;\n }\n // Parse and validate with the provided schema\n return schema.parse(response);\n}\n","import { compose } from '../../middleware/compose';\nimport { createRequestValidator, createResponseValidator } from '../validation';\n\nimport type { Context } from '@blaize-types/context';\nimport type { RouteMethodOptions } from '@blaize-types/router';\n\n/**\n * Execute a route handler with its middleware\n */\nexport async function executeHandler(\n ctx: Context,\n routeOptions: RouteMethodOptions,\n params: Record<string, string>\n): Promise<void> {\n // Set up middleware chain\n const middleware = [...(routeOptions.middleware || [])];\n\n // Add validation middleware if schemas are defined\n if (routeOptions.schema) {\n if (routeOptions.schema.params || routeOptions.schema.query || routeOptions.schema.body) {\n middleware.unshift(createRequestValidator(routeOptions.schema));\n }\n\n if (routeOptions.schema.response) {\n middleware.push(createResponseValidator(routeOptions.schema.response));\n }\n }\n\n // Compose middleware with the final handler\n const handler = compose([...middleware]);\n\n // Execute the middleware chain\n await handler(ctx, async () => {\n // Execute the handler with the new argument style\n const result = await routeOptions.handler(ctx, params);\n\n // Handle the result if it wasn't already handled by the handler\n if (!ctx.response.sent && result !== undefined) {\n ctx.response.json(result);\n }\n });\n}\n","/**\n * Extract parameter values from a URL path\n */\nexport function extractParams(\n path: string,\n pattern: RegExp,\n paramNames: string[]\n): Record<string, string> {\n const match = pattern.exec(path);\n if (!match) {\n return {};\n }\n\n const params: Record<string, string> = {};\n\n // Extract parameter values from regex match groups\n for (let i = 0; i < paramNames.length; i++) {\n // Add 1 to index since the first capture group is at index 1\n params[paramNames[i]!] = match[i + 1] || '';\n }\n\n return params;\n}\n\n/**\n * Compile a path pattern with parameters\n */\nexport function compilePathPattern(path: string): { pattern: RegExp; paramNames: string[] } {\n const paramNames: string[] = [];\n\n // Special case for root path\n if (path === '/') {\n return {\n pattern: /^\\/$/,\n paramNames: [],\n };\n }\n\n // First escape special regex characters (except for : and [ ] which we process specially)\n let patternString = path.replace(/([.+*?^$(){}|\\\\])/g, '\\\\$1');\n\n // Replace route parameters with regex capture groups\n patternString = patternString\n // Replace :param syntax with capture groups\n .replace(/\\/:([^/]+)/g, (_, paramName) => {\n paramNames.push(paramName);\n return '/([^/]+)';\n })\n // Replace [param] syntax (for file-based routing)\n .replace(/\\/\\[([^\\]]+)\\]/g, (_, paramName) => {\n paramNames.push(paramName);\n return '/([^/]+)';\n });\n\n // Make the trailing slash optional (if not already the root path)\n // This adds an optional trailing slash to the end of the pattern\n patternString = `${patternString}(?:/)?`;\n\n // Create the regex pattern\n // This is safe because we've escaped special RegExp characters and\n // we're using developer-defined routes, not user input\n const pattern = new RegExp(`^${patternString}$`);\n\n return {\n pattern,\n paramNames,\n };\n}\n\n/**\n * Convert parameters object to URL query string\n */\nexport function paramsToQuery(params: Record<string, string | number | boolean>): string {\n const parts: string[] = [];\n\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined && value !== null) {\n const encodedKey = encodeURIComponent(key);\n const encodedValue = encodeURIComponent(String(value));\n parts.push(`${encodedKey}=${encodedValue}`);\n }\n }\n\n return parts.length > 0 ? `?${parts.join('&')}` : '';\n}\n\n/**\n * Build a URL with path parameters\n */\nexport function buildUrl(\n pathPattern: string,\n params: Record<string, string | number | boolean> = {},\n query: Record<string, string | number | boolean> = {}\n): string {\n // Extract path parameters and query parameters\n const pathParams: Record<string, string | number | boolean> = {};\n const queryParams: Record<string, string | number | boolean> = { ...query };\n\n // Find all parameter names in the path\n const paramNames: string[] = [];\n pathPattern.replace(/\\/:([^/]+)/g, (_, paramName) => {\n paramNames.push(paramName);\n return '/';\n });\n\n // Separate params into path params and additional query params\n for (const [key, value] of Object.entries(params)) {\n if (paramNames.includes(key)) {\n pathParams[key] = value;\n } else {\n queryParams[key] = value;\n }\n }\n\n // Replace path parameters\n let url = pathPattern;\n for (const [key, value] of Object.entries(pathParams)) {\n url = url.replace(`:${key}`, encodeURIComponent(String(value)));\n }\n\n // Add query string if needed\n const queryString = paramsToQuery(queryParams);\n\n return url + queryString;\n}\n","import { compilePathPattern, extractParams } from './params';\n\nimport type {\n HttpMethod,\n RouteMethodOptions,\n RouteMatch,\n Matcher,\n RouteEntry,\n Route,\n} from '../../index';\n\n/**\n * Create a route matcher\n */\nexport function createMatcher(): Matcher {\n // Private state\n const routes: RouteEntry[] = [];\n\n return {\n /**\n * Add a route to the matcher\n */\n add(path: string, method: HttpMethod, routeOptions: RouteMethodOptions) {\n const { pattern, paramNames } = compilePathPattern(path);\n\n const newRoute: RouteEntry = {\n path,\n method,\n pattern,\n paramNames,\n routeOptions,\n };\n\n // Find the insertion point using findIndex\n const insertIndex = routes.findIndex(route => paramNames.length < route.paramNames.length);\n\n // If no insertion point found, append to end\n if (insertIndex === -1) {\n routes.push(newRoute);\n } else {\n routes.splice(insertIndex, 0, newRoute);\n }\n },\n\n /**\n * Remove a route from the matcher by path\n */\n remove(path: string) {\n // Remove all routes that match the given path\n for (let i = routes.length - 1; i >= 0; i--) {\n if ((routes[i] as Route).path === path) {\n routes.splice(i, 1);\n }\n }\n },\n\n /**\n * Clear all routes from the matcher\n */\n clear() {\n routes.length = 0;\n },\n\n /**\n * Match a URL path to a route\n */\n match(path: string, method: HttpMethod): RouteMatch | null {\n // First, try to find an exact match for the method\n const pathname = path.split('?')[0];\n if (!pathname) return null;\n\n for (const route of routes) {\n // Skip routes that don't match the method\n if (route.method !== method) continue;\n\n // Try to match the path\n const match = route.pattern.exec(pathname);\n if (match) {\n // Extract parameters from the match\n const params = extractParams(path, route.pattern, route.paramNames);\n\n return {\n route: route.routeOptions,\n params,\n };\n }\n }\n\n // If no exact method match, check if path exists but method is different\n // This allows returning 405 Method Not Allowed instead of 404 Not Found\n const matchingPath = routes.find(\n route => route.method !== method && route.pattern.test(path)\n );\n\n if (matchingPath) {\n // Return null but with allowedMethods to indicate method not allowed\n return {\n route: null,\n params: {},\n methodNotAllowed: true,\n allowedMethods: routes\n .filter(route => route.pattern.test(path))\n .map(route => route.method),\n } as unknown as RouteMatch; // Type assertion for the extended return type\n }\n\n return null; // No match found\n },\n\n /**\n * Get all registered routes\n */\n getRoutes(): { path: string; method: HttpMethod }[] {\n return routes.map(route => ({\n path: route.path,\n method: route.method,\n }));\n },\n\n /**\n * Find routes matching a specific path\n */\n findRoutes(\n path: string\n ): { path: string; method: HttpMethod; params: Record<string, string> }[] {\n return routes\n .filter(route => route.pattern.test(path))\n .map(route => ({\n path: route.path,\n method: route.method,\n params: extractParams(path, route.pattern, route.paramNames),\n }));\n },\n };\n}\n","import type { Route, RouteRegistry } from '@blaize-types/router';\n\nexport function createRouteRegistry(): RouteRegistry {\n return {\n routesByPath: new Map(),\n routesByFile: new Map(),\n pathToFile: new Map(),\n };\n}\n\nexport function updateRoutesFromFile(\n registry: RouteRegistry,\n filePath: string,\n newRoutes: Route[]\n): { added: Route[]; removed: string[]; changed: Route[] } {\n console.log(`Updating routes from file: ${filePath}`);\n const oldPaths = registry.routesByFile.get(filePath) || new Set();\n const newPaths = new Set(newRoutes.map(r => r.path));\n\n // Fast diff calculation\n const added = newRoutes.filter(r => !oldPaths.has(r.path));\n const removed = Array.from(oldPaths).filter(p => !newPaths.has(p));\n const potentiallyChanged = newRoutes.filter(r => oldPaths.has(r.path));\n\n // Check for actual content changes\n const changed = potentiallyChanged.filter(route => {\n const existingRoute = registry.routesByPath.get(route.path);\n return !existingRoute || !routesEqual(existingRoute, route);\n });\n\n // Apply updates\n applyRouteUpdates(registry, filePath, { added, removed, changed });\n\n return { added, removed, changed };\n}\n\nexport function getRouteFromRegistry(registry: RouteRegistry, path: string): Route | undefined {\n return registry.routesByPath.get(path);\n}\n\nexport function getAllRoutesFromRegistry(registry: RouteRegistry): Route[] {\n return Array.from(registry.routesByPath.values());\n}\n\nexport function getFileRoutes(registry: RouteRegistry, filePath: string): Route[] {\n const paths = registry.routesByFile.get(filePath) || new Set();\n return Array.from(paths)\n .map(path => registry.routesByPath.get(path)!)\n .filter(Boolean);\n}\n\nfunction applyRouteUpdates(\n registry: RouteRegistry,\n filePath: string,\n updates: { added: Route[]; removed: string[]; changed: Route[] }\n): void {\n const { added, removed, changed } = updates;\n\n // Remove old routes\n removed.forEach(path => {\n registry.routesByPath.delete(path);\n registry.pathToFile.delete(path);\n });\n\n // Add/update routes\n [...added, ...changed].forEach(route => {\n registry.routesByPath.set(route.path, route);\n registry.pathToFile.set(route.path, filePath);\n });\n\n // Update file -> paths mapping\n const allPathsForFile = new Set([\n ...added.map(r => r.path),\n ...changed.map(r => r.path),\n ...Array.from(registry.routesByFile.get(filePath) || []).filter(p => !removed.includes(p)),\n ]);\n\n if (allPathsForFile.size > 0) {\n registry.routesByFile.set(filePath, allPathsForFile);\n } else {\n registry.routesByFile.delete(filePath);\n }\n}\n\nfunction routesEqual(route1: Route, route2: Route): boolean {\n if (route1.path !== route2.path) return false;\n\n const methods1 = Object.keys(route1)\n .filter(k => k !== 'path')\n .sort();\n const methods2 = Object.keys(route2)\n .filter(k => k !== 'path')\n .sort();\n\n if (methods1.length !== methods2.length) return false;\n\n return methods1.every(method => {\n const handler1 = route1[method as keyof Route];\n const handler2 = route2[method as keyof Route];\n\n // Compare handler signatures/structure rather than function references\n return typeof handler1 === typeof handler2;\n });\n}\n","import type { Route, HttpMethod, RouteMethodOptions, Matcher } from '@blaize-types/router';\n\nexport function addRouteToMatcher(route: Route, matcher: Matcher): void {\n Object.entries(route).forEach(([method, methodOptions]) => {\n if (method === 'path' || !methodOptions) return;\n matcher.add(route.path, method as HttpMethod, methodOptions as RouteMethodOptions);\n });\n}\n\nexport function removeRouteFromMatcher(path: string, matcher: Matcher): void {\n // Use matcher's remove method if available, otherwise fallback to clear/rebuild\n if ('remove' in matcher && typeof matcher.remove === 'function') {\n matcher.remove(path);\n } else {\n // This requires rebuilding the matcher - could be optimized\n console.warn('Matcher does not support selective removal, consider adding remove() method');\n }\n}\n\nexport function updateRouteInMatcher(route: Route, matcher: Matcher): void {\n removeRouteFromMatcher(route.path, matcher);\n addRouteToMatcher(route, matcher);\n}\n\nexport function rebuildMatcherWithRoutes(routes: Route[], matcher: Matcher): void {\n if ('clear' in matcher && typeof matcher.clear === 'function') {\n matcher.clear();\n }\n\n routes.forEach(route => addRouteToMatcher(route, matcher));\n}\n","import { NotFoundError } from '../errors/not-found-error';\nimport { clearFileCache } from './discovery/cache';\nimport { loadInitialRoutesParallel } from './discovery/parallel';\nimport { withPerformanceTracking } from './discovery/profiler';\nimport { watchRoutes } from './discovery/watchers';\nimport { executeHandler } from './handlers';\nimport { createMatcher } from './matching';\nimport {\n createRouteRegistry,\n updateRoutesFromFile,\n getAllRoutesFromRegistry,\n} from './registry/fast-registry';\nimport {\n addRouteToMatcher,\n removeRouteFromMatcher,\n updateRouteInMatcher,\n} from './utils/matching-helpers';\n\nimport type { Context } from '@blaize-types/context';\nimport type { HttpMethod, Route, RouterOptions, Router } from '@blaize-types/router';\n\nconst DEFAULT_ROUTER_OPTIONS = {\n routesDir: './routes',\n basePath: '/',\n watchMode: process.env.NODE_ENV === 'development',\n};\n\n/**\n * Create an optimized router instance with fast hot reload\n */\nexport function createRouter(options: RouterOptions): Router {\n // Merge with default options\n const routerOptions = {\n ...DEFAULT_ROUTER_OPTIONS,\n ...options,\n };\n\n if (options.basePath && !options.basePath.startsWith('/')) {\n console.warn('Base path does nothing');\n }\n\n // Use optimized registry instead of simple array\n const registry = createRouteRegistry();\n const matcher = createMatcher();\n\n // Initialize routes\n let initialized = false;\n let initializationPromise: Promise<void> | null = null;\n let _watchers: Map<string, ReturnType<typeof watchRoutes>> | null = null;\n\n const routeDirectories = new Set<string>([routerOptions.routesDir]);\n\n /**\n * Apply registry changes to matcher efficiently\n */\n function applyMatcherChanges(changes: { added: Route[]; removed: string[]; changed: Route[] }) {\n console.log('\\n🔧 APPLYING MATCHER CHANGES:');\n console.log(` Adding ${changes.added.length} routes`);\n console.log(` Removing ${changes.removed.length} routes`);\n console.log(` Updating ${changes.changed.length} routes`);\n\n // Remove routes first\n changes.removed.forEach(routePath => {\n console.log(` ➖ Removing: ${routePath}`);\n removeRouteFromMatcher(routePath, matcher);\n });\n\n // Add new routes\n changes.added.forEach(route => {\n const methods = Object.keys(route).filter(key => key !== 'path');\n console.log(` ➕ Adding: ${route.path} [${methods.join(', ')}]`);\n addRouteToMatcher(route, matcher);\n });\n\n // Update changed routes\n changes.changed.forEach(route => {\n const methods = Object.keys(route).filter(key => key !== 'path');\n console.log(` 🔄 Updating: ${route.path} [${methods.join(', ')}]`);\n updateRouteInMatcher(route, matcher);\n });\n\n console.log('✅ Matcher changes applied\\n');\n }\n\n /**\n * Add multiple routes with batch processing\n */\n function addRoutesWithSource(routes: Route[], source: string) {\n try {\n // Use registry for batch conflict detection and management\n const changes = updateRoutesFromFile(registry, source, routes);\n\n // Apply all changes to matcher in one operation\n applyMatcherChanges(changes);\n\n return changes;\n } catch (error) {\n console.error(`⚠️ Route conflicts from ${source}:`, error);\n throw error;\n }\n }\n\n /**\n * Optimized route loading with parallel processing\n */\n async function loadRoutesFromDirectory(directory: string, source: string, prefix?: string) {\n try {\n // Use parallel loading for better performance\n const discoveredRoutes = await loadInitialRoutesParallel(directory);\n\n // Apply prefix if provided\n const finalRoutes = discoveredRoutes.map(route =>\n prefix ? { ...route, path: `${prefix}${route.path}` } : route\n );\n\n // Batch add all routes from this directory\n const changes = addRoutesWithSource(finalRoutes, source);\n\n console.log(\n `Loaded ${discoveredRoutes.length} routes from ${source}${prefix ? ` with prefix ${prefix}` : ''} ` +\n `(${changes.added.length} added, ${changes.changed.length} changed, ${changes.removed.length} removed)`\n );\n } catch (error) {\n console.error(`⚠️ Failed to load routes from ${source}:`, error);\n throw error;\n }\n }\n\n /**\n * Initialize the router with parallel route loading\n */\n async function initialize() {\n if (initialized || initializationPromise) {\n return initializationPromise;\n }\n\n initializationPromise = (async () => {\n try {\n // Load routes from all directories in parallel\n await Promise.all(\n Array.from(routeDirectories).map(directory =>\n loadRoutesFromDirectory(directory, directory)\n )\n );\n\n // Set up optimized watching\n if (routerOptions.watchMode) {\n setupOptimizedWatching();\n }\n\n initialized = true;\n } catch (error) {\n console.error('⚠️ Failed to initialize router:', error);\n throw error;\n }\n })();\n\n return initializationPromise;\n }\n\n /**\n * Setup optimized file watching with fast updates\n */\n function setupOptimizedWatching() {\n if (!_watchers) {\n _watchers = new Map();\n }\n\n for (const directory of routeDirectories) {\n if (!_watchers.has(directory)) {\n const watcher = watchRoutes(directory, {\n debounceMs: 16, // ~60fps debouncing\n ignore: ['node_modules', '.git'],\n\n onRouteAdded: (filepath: string, addedRoutes: Route[]) => {\n // Batch process all added routes\n try {\n const changes = updateRoutesFromFile(registry, filepath, addedRoutes);\n applyMatcherChanges(changes);\n } catch (error) {\n console.error(`Error adding routes from ${directory}:`, error);\n }\n },\n\n onRouteChanged: withPerformanceTracking(\n async (filepath: string, changedRoutes: Route[]) => {\n // console.log(`${changedRoutes.length} route(s) changed in ${directory}`);\n\n try {\n console.log(`Processing changes for ${filepath}`);\n // Process all changed routes in one batch operation\n const changes = updateRoutesFromFile(registry, filepath, changedRoutes);\n\n console.log(\n `Changes detected: ${changes.added.length} added, ` +\n `${changes.changed.length} changed, ${changes.removed.length} removed`\n );\n\n // Apply matcher updates efficiently\n applyMatcherChanges(changes);\n\n console.log(\n `Route changes applied: ${changes.added.length} added, ` +\n `${changes.changed.length} changed, ${changes.removed.length} removed`\n );\n } catch (error) {\n console.error(`⚠️ Error updating routes from ${directory}:`, error);\n }\n },\n directory\n ),\n\n onRouteRemoved: (filePath: string, removedRoutes: Route[]) => {\n console.log(`File removed: ${filePath} with ${removedRoutes.length} routes`);\n\n try {\n // Remove all routes from this file\n removedRoutes.forEach(route => {\n removeRouteFromMatcher(route.path, matcher);\n });\n\n // Clear cache for removed file\n clearFileCache(filePath);\n } catch (error) {\n console.error(`⚠️ Error removing routes from ${filePath}:`, error);\n }\n },\n\n onError: (error: Error) => {\n console.error(`⚠️ Route watcher error for ${directory}:`, error);\n },\n });\n\n _watchers.set(directory, watcher);\n }\n }\n }\n\n /**\n * Setup watcher for newly added directory\n */\n function setupWatcherForNewDirectory(directory: string, prefix?: string) {\n if (!_watchers) {\n _watchers = new Map();\n }\n\n const watcher = watchRoutes(directory, {\n debounceMs: 16,\n ignore: ['node_modules', '.git'],\n\n onRouteAdded: (filePath: string, addedRoutes: Route[]) => {\n try {\n // Apply prefix to all routes\n const finalRoutes = addedRoutes.map(route =>\n prefix ? { ...route, path: `${prefix}${route.path}` } : route\n );\n\n // Batch process all added routes\n const changes = updateRoutesFromFile(registry, filePath, finalRoutes);\n applyMatcherChanges(changes);\n } catch (error) {\n console.error(`⚠️ Error adding routes from ${directory}:`, error);\n }\n },\n\n onRouteChanged: withPerformanceTracking(async (filePath: string, changedRoutes: Route[]) => {\n try {\n // Apply prefix to all routes\n const finalRoutes = changedRoutes.map(route =>\n prefix ? { ...route, path: `${prefix}${route.path}` } : route\n );\n\n // Process all changed routes in one batch operation\n const changes = updateRoutesFromFile(registry, filePath, finalRoutes);\n applyMatcherChanges(changes);\n } catch (error) {\n console.error(`⚠️ Error updating routes from ${directory}:`, error);\n }\n }, directory),\n\n onRouteRemoved: (filePath: string, removedRoutes: Route[]) => {\n try {\n removedRoutes.forEach(route => {\n const finalPath = prefix ? `${prefix}${route.path}` : route.path;\n removeRouteFromMatcher(finalPath, matcher);\n });\n clearFileCache(filePath);\n } catch (error) {\n console.error(`Error removing routes from ${filePath}:`, error);\n }\n },\n\n onError: (error: Error) => {\n console.error(`⚠️ Route watcher error for ${directory}:`, error);\n },\n });\n\n _watchers.set(directory, watcher);\n return watcher;\n }\n\n // Initialize router on creation\n initialize().catch(error => {\n console.error('⚠️ Failed to initialize router on creation:', error);\n });\n\n // Public API\n return {\n /**\n * Handle an incoming request\n */\n async handleRequest(ctx: Context) {\n // Ensure router is initialized\n if (!initialized) {\n console.log('🔄 Router not initialized, initializing...');\n await initialize();\n }\n\n const { method, path } = ctx.request;\n console.log(`\\n📥 Handling request: ${method} ${path}`);\n\n // Find matching route\n const match = matcher.match(path, method as HttpMethod);\n\n if (!match) {\n console.log(`❌ No match found for: ${method} ${path}`);\n // Handle 404 Not Found\n throw new NotFoundError('Not found');\n }\n\n console.log(`✅ Route matched: ${method} ${path}`);\n console.log(` Params: ${JSON.stringify(match.params)}`);\n\n // Check for method not allowed\n if (match.methodNotAllowed) {\n // Handle 405 Method Not Allowed\n // TODO: Add support for Method Not Allowed Error\n ctx.response.status(405).json({\n error: '❌ Method Not Allowed',\n allowed: match.allowedMethods,\n });\n\n // Set Allow header with allowed methods\n if (match.allowedMethods && match.allowedMethods.length > 0) {\n ctx.response.header('Allow', match.allowedMethods.join(', '));\n }\n\n return;\n }\n\n // Extract route parameters\n ctx.request.params = match.params;\n\n // Execute the route handler with middleware\n await executeHandler(ctx, match.route!, match.params);\n },\n\n /**\n * Get all registered routes (using optimized registry)\n */\n getRoutes() {\n return getAllRoutesFromRegistry(registry);\n },\n\n /**\n * Add a route programmatically\n */\n addRoute(route: Route) {\n const changes = updateRoutesFromFile(registry, 'programmatic', [route]);\n applyMatcherChanges(changes);\n },\n\n /**\n * Add multiple routes programmatically with batch processing\n */\n addRoutes(routes: Route[]) {\n const changes = updateRoutesFromFile(registry, 'programmatic', routes);\n applyMatcherChanges(changes);\n return changes;\n },\n\n /**\n * Add a route directory (for plugins) with optimized loading\n */\n async addRouteDirectory(directory: string, options: { prefix?: string } = {}) {\n if (routeDirectories.has(directory)) {\n console.warn(`Route directory ${directory} already registered`);\n return;\n }\n\n routeDirectories.add(directory);\n\n // If already initialized, load routes immediately\n if (initialized) {\n await loadRoutesFromDirectory(directory, directory, options.prefix);\n\n // Set up watching for this directory if in watch mode\n if (routerOptions.watchMode) {\n setupWatcherForNewDirectory(directory, options.prefix);\n }\n }\n },\n\n /**\n * Get route conflicts (using registry)\n */\n getRouteConflicts() {\n // Registry handles conflict detection internally\n // This could be enhanced to expose more detailed conflict info\n const conflicts: Array<{ path: string; sources: string[] }> = [];\n // Implementation would depend on registry's conflict tracking\n return conflicts;\n },\n\n /**\n * Close watchers and cleanup (useful for testing)\n */\n async close() {\n if (_watchers) {\n for (const watcher of _watchers.values()) {\n await watcher.close();\n }\n _watchers.clear();\n }\n },\n };\n}\n","export * from './client';\nexport * from './context';\nexport * from './errors';\nexport * from './server';\nexport * from './middleware';\nexport * from './router';\nexport * from './plugins';\nexport * from './upload';\n","/**\n * UnauthorizedError class for authentication failures\n *\n * This error is thrown when authentication is required or has failed.\n * It provides context about authentication requirements and failure reasons.\n */\n\nimport { ErrorType, BlaizeError } from '@blaize-types/errors';\n\nimport { getCurrentCorrelationId } from './correlation';\n\nimport type { UnauthorizedErrorDetails } from '@blaize-types/errors';\n\n/**\n * Error thrown when authentication is required or has failed\n *\n * Automatically sets HTTP status to 401 and provides authentication context.\n *\n * @example Basic usage:\n * ```typescript\n * throw new UnauthorizedError('Authentication required');\n * ```\n *\n * @example With authentication details:\n * ```typescript\n * throw new UnauthorizedError('Token expired', {\n * reason: 'expired_token',\n * authScheme: 'Bearer',\n * loginUrl: '/auth/login'\n * });\n * ```\n */\nexport class UnauthorizedError extends BlaizeError<UnauthorizedErrorDetails> {\n /**\n * Creates a new UnauthorizedError instance\n *\n * @param title - Human-readable error message\n * @param details - Optional authentication context\n * @param correlationId - Optional correlation ID (uses current context if not provided)\n */\n constructor(\n title: string,\n details: UnauthorizedErrorDetails | undefined = undefined,\n correlationId: string | undefined = undefined\n ) {\n super(\n ErrorType.UNAUTHORIZED,\n title,\n 401, // HTTP 401 Unauthorized\n correlationId ?? getCurrentCorrelationId(),\n details\n );\n }\n}\n","/**\n * ForbiddenError class for authorization failures\n *\n * This error is thrown when a user lacks permission to access a resource.\n * It provides context about required permissions and access control.\n */\n\nimport { BlaizeError, ErrorType } from '@blaize-types/errors';\n\nimport { getCurrentCorrelationId } from './correlation';\n\nimport type { ForbiddenErrorDetails } from '@blaize-types/errors';\n\n/**\n * Error thrown when user lacks permission to access a resource\n *\n * Automatically sets HTTP status to 403 and provides permission context.\n *\n * @example Basic usage:\n * ```typescript\n * throw new ForbiddenError('Access denied');\n * ```\n *\n * @example With permission details:\n * ```typescript\n * throw new ForbiddenError('Insufficient permissions', {\n * requiredPermission: 'admin:users:delete',\n * userPermissions: ['admin:users:read'],\n * resource: 'user-123',\n * action: 'delete'\n * });\n * ```\n */\nexport class ForbiddenError extends BlaizeError<ForbiddenErrorDetails> {\n /**\n * Creates a new ForbiddenError instance\n *\n * @param title - Human-readable error message\n * @param details - Optional permission context\n * @param correlationId - Optional correlation ID (uses current context if not provided)\n */\n constructor(\n title: string,\n details: ForbiddenErrorDetails | undefined = undefined,\n correlationId: string | undefined = undefined\n ) {\n super(\n ErrorType.FORBIDDEN,\n title,\n 403, // HTTP 403 Forbidden\n correlationId ?? getCurrentCorrelationId(),\n details\n );\n }\n}\n","/**\n * ConflictError class for resource conflicts\n *\n * This error is thrown when a resource conflict occurs, such as duplicate keys,\n * version mismatches, or concurrent modifications.\n */\n\nimport { BlaizeError, ErrorType } from '@blaize-types/errors';\n\nimport { getCurrentCorrelationId } from './correlation';\n\nimport type { ConflictErrorDetails } from '@blaize-types/errors';\n\n/**\n * Error thrown when a resource conflict occurs\n *\n * Automatically sets HTTP status to 409 and provides conflict context.\n *\n * @example Basic usage:\n * ```typescript\n * throw new ConflictError('Email already exists');\n * ```\n *\n * @example With conflict details:\n * ```typescript\n * throw new ConflictError('Version conflict', {\n * conflictType: 'version_mismatch',\n * currentVersion: '2',\n * expectedVersion: '1',\n * resolution: 'Fetch the latest version and retry'\n * });\n * ```\n */\nexport class ConflictError extends BlaizeError<ConflictErrorDetails> {\n /**\n * Creates a new ConflictError instance\n *\n * @param title - Human-readable error message\n * @param details - Optional conflict context\n * @param correlationId - Optional correlation ID (uses current context if not provided)\n */\n constructor(\n title: string,\n details: ConflictErrorDetails | undefined = undefined,\n correlationId: string | undefined = undefined\n ) {\n super(\n ErrorType.CONFLICT,\n title,\n 409, // HTTP 409 Conflict\n correlationId ?? getCurrentCorrelationId(),\n details\n );\n }\n}\n","/**\n * RateLimitError class for rate limiting violations\n *\n * This error is thrown when rate limits are exceeded.\n * It provides context about the rate limit and when requests can resume.\n */\n\nimport { BlaizeError, ErrorType } from '@blaize-types/errors';\n\nimport { getCurrentCorrelationId } from './correlation';\n\nimport type { RateLimitErrorDetails } from '@blaize-types/errors';\n\n/**\n * Error thrown when rate limits are exceeded\n *\n * Automatically sets HTTP status to 429 and provides rate limit context.\n *\n * @example Basic usage:\n * ```typescript\n * throw new RateLimitError('Too many requests');\n * ```\n *\n * @example With rate limit details:\n * ```typescript\n * throw new RateLimitError('Rate limit exceeded', {\n * limit: 100,\n * remaining: 0,\n * retryAfter: 3600,\n * window: 'hour',\n * identifier: 'user-123'\n * });\n * ```\n */\nexport class RateLimitError extends BlaizeError<RateLimitErrorDetails> {\n /**\n * Creates a new RateLimitError instance\n *\n * @param title - Human-readable error message\n * @param details - Optional rate limit context\n * @param correlationId - Optional correlation ID (uses current context if not provided)\n */\n constructor(\n title: string,\n details: RateLimitErrorDetails | undefined = undefined,\n correlationId: string | undefined = undefined\n ) {\n super(\n ErrorType.RATE_LIMITED,\n title,\n 429, // HTTP 429 Too Many Requests\n correlationId ?? getCurrentCorrelationId(),\n details\n );\n }\n}\n","import { getCurrentCorrelationId } from './correlation';\nimport { BlaizeError, ErrorType } from '../../../blaize-types/src/errors';\n\nexport class RequestTimeoutError extends BlaizeError {\n constructor(title: string, details?: unknown, correlationId?: string) {\n super(\n ErrorType.UPLOAD_TIMEOUT,\n title,\n 408,\n correlationId ?? getCurrentCorrelationId(),\n details\n );\n }\n}\n","import { getCurrentCorrelationId } from './correlation';\nimport { BlaizeError, ErrorType } from '../../../blaize-types/src/errors';\n\nexport class UnprocessableEntityError extends BlaizeError {\n constructor(title: string, details?: unknown, correlationId?: string) {\n super(\n ErrorType.UNPROCESSABLE_ENTITY,\n title,\n 422,\n correlationId ?? getCurrentCorrelationId(),\n details\n );\n }\n}\n"],"mappings":";;;;;;;;;6qBAAA,IAAAA,EAAAC,EAAA,CAAAC,GAAAC,KAAA,cAOAA,GAAO,QAAU,CAEf,QAAS,CACP,kBAAmB,EACrB,CACF,ICZA,IAAAC,GAAAC,EAAA,CAAAC,GAAAC,KAAA,cA8BA,IAAIC,GAAM,CAAC,EACXD,GAAO,QAAUC,GAGjB,IAAIC,GAAoB,CAAC,EAWzBD,GAAI,OAAS,SAASE,EAAOC,EAAUC,EAAS,CAC9C,GAAG,OAAOD,GAAa,SACrB,MAAM,IAAI,UAAU,8BAA8B,EAEpD,GAAGC,IAAY,QAAa,OAAOA,GAAY,SAC7C,MAAM,IAAI,UAAU,6BAA6B,EAGnD,IAAIC,EAAS,GAEb,GAAG,EAAEH,aAAiB,YAEpBG,EAASC,GAAsBJ,EAAOC,CAAQ,MACzC,CACL,IAAII,EAAI,EACJC,EAAOL,EAAS,OAChBM,EAAQN,EAAS,OAAO,CAAC,EACzBO,EAAS,CAAC,CAAC,EACf,IAAIH,EAAI,EAAGA,EAAIL,EAAM,OAAQ,EAAEK,EAAG,CAChC,QAAQI,EAAI,EAAGC,EAAQV,EAAMK,CAAC,EAAGI,EAAID,EAAO,OAAQ,EAAEC,EACpDC,GAASF,EAAOC,CAAC,GAAK,EACtBD,EAAOC,CAAC,EAAIC,EAAQJ,EACpBI,EAASA,EAAQJ,EAAQ,EAG3B,KAAMI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,IACAE,GAAiBC,GAAwB,EACzCF,CACF,CACF,CACF,EjDiBAG,KACAC,KkDzEAC,KACAC,KAEO,IAAMC,GAAN,cAAkCC,EAAY,CACnD,YAAYC,EAAeC,EAAmBC,EAAwB,CACpE,uBAEEF,EACA,IACAE,GAAiBC,GAAwB,EACzCF,CACF,CACF,CACF,ElD8DAG,KmD3EAC,KACAC,KAEO,IAAMC,GAAN,cAAuCC,EAAY,CACxD,YAAYC,EAAeC,EAAmBC,EAAwB,CACpE,6BAEEF,EACA,IACAE,GAAiBC,GAAwB,EACzCF,CACF,CACF,CACF,EnDoCO,IAAMG,GAAU,QAGVC,GAAY,CAAE,aAAAC,EAAa,EAC3BC,GAAY,CACvB,kBAAAC,GACA,eAAAC,GACA,gBAAAC,GACA,mBAAAC,GACA,iBAAAC,GACA,gBAAAC,GACA,eAAAC,EACF,EACaC,GAAgB,CAAE,iBAAAT,GAAkB,QAAAU,EAAQ,EAC5CC,GAAa,CAAE,aAAAX,EAAa,EAgBnCY,GAAS,CAEb,aAAAZ,GACA,iBAAAA,GACA,aAAAA,GAGA,OAAQD,GACR,OAAQE,GACR,WAAYQ,GACZ,QAASE,GAGT,QAAAb,EACF","names":["require_forge","__commonJSMin","exports","module","require_baseN","__commonJSMin","exports","module","api","_reverseAlphabets","input","alphabet","maxline","output","_encodeWithByteBuffer","i","base","first","digits","j","carry","regex","table","bytes","value","k","require_util","__commonJSMin","exports","module","forge","baseN","util","callback","handler","event","msg","copy","callbacks","now","attr","div","oldSetImmediate","x","_checkBitsParam","n","ByteStringBuffer","b","arr","i","_MAX_CONSTRUCTED_STRING_LENGTH","d","bytes","str","buffer","rval","max","count","c","len","DataBuffer","options","isArrayBuffer","isArrayBufferView","amount","growSize","src","dst","encoding","view","input","s","s1","s2","s3","t","hex","_base64","_base64Idx","_base58","maxline","line","output","chr1","chr2","chr3","enc1","enc2","enc3","enc4","offset","out","j","k","api","raw","start","flg","_setStorageObject","id","obj","error","_getStorageObject","_setItem","key","data","_getItem","_removeItem","empty","prop","_clearItems","_callStorageFunction","func","args","location","type","done","exception","idx","ex","format","re","match","part","argi","parts","last","code","number","decimals","dec_point","thousands_sep","size","ip","num","blanks","e","zeros","zeroGroups","zeroMaxGroup","group","blobUrl","st","et","sample","samples","numWorkers","avg","map","err","results","reduce","workers","worker","overlaps","r1","overlap","r2","require_cipher","__commonJSMin","exports","module","forge","algorithm","key","api","name","BlockCipher","options","opts","input","pad","output","require_cipherModes","__commonJSMin","exports","module","forge","modes","options","input","output","finish","i","padding","len","count","transformIV","inputLength","partialBytes","inc32","iv","additionalData","ivLength","from64To32","overflow","rval","lengths","tag","x","y","z_i","v_i","x_i","out","lsb","z","idx","ah","h","bits","multiplier","perInt","size","m","tmp","shft","mid","half","j","m_i","m_j","c","blockSize","ints","blocks","block","num","require_aes","__commonJSMin","exports","module","forge","key","iv","output","mode","cipher","_createCipher","name","init","initialize","self","inBlock","outBlock","_updateBlock","options","tmp","i","len","encryptOp","_expandKey","decrypt","registerAlgorithm","factory","Nb","sbox","isbox","rcon","mix","imix","xtime","e","ei","e2","e4","e8","sx","sx2","me","ime","n","w","temp","iNk","Nk","Nr1","end","m0","m1","m2","m3","wnew","wi","input","Nr","sub","a","b","c","d","a2","b2","c2","round","algorithm","start","require_oids","__commonJSMin","exports","module","forge","oids","_IN","id","name","_I_","require_asn1","__commonJSMin","exports","module","forge","asn1","tagClass","type","constructed","value","options","tmp","i","obj","copy","obj1","obj2","equal","b","b2","length","longForm","_checkBufferLength","bytes","remaining","n","error","_getValueLength","longFormBytes","byteCount","_fromDer","depth","start","b1","bitStringContents","savedRead","savedRemaining","unused","subOptions","composed","used","tc","asn1Options","useBitStringContents","len","lenBytes","oid","values","last","valueBytes","utc","date","year","MM","DD","hh","mm","ss","c","end","hhoffset","mmoffset","offset","gentime","YYYY","fff","isUTC","rval","format","x","v","capture","errors","j","_nonLatinRegex","level","indentation","indent","subvalues","sub","e","require_md","__commonJSMin","exports","module","forge","require_hmac","__commonJSMin","exports","module","forge","hmac","_key","_md","_ipadding","_opadding","ctx","md","key","tmp","i","keylen","bytes","inner","require_md5","__commonJSMin","exports","module","forge","md5","_initialized","_init","_state","_input","_w","md","int32s","msg","encoding","len","i","_update","finalBlock","remaining","overflow","_padding","bits","carry","s2","rval","_g","_r","_k","s","w","bytes","t","a","b","c","d","f","r","require_pem","__commonJSMin","exports","module","forge","pem","msg","options","rval","header","foldHeader","i","str","rMessage","rHeader","rCRLF","match","type","lines","li","line","nl","next","values","vi","ltrim","insertSpace","$1","length","candidate","insert","require_des","__commonJSMin","exports","module","forge","key","iv","output","mode","cipher","_createCipher","name","self","inBlock","outBlock","_updateBlock","options","_createKeys","registerAlgorithm","factory","spfunction1","spfunction2","spfunction3","spfunction4","spfunction5","spfunction6","spfunction7","spfunction8","pc2bytes0","pc2bytes1","pc2bytes2","pc2bytes3","pc2bytes4","pc2bytes5","pc2bytes6","pc2bytes7","pc2bytes8","pc2bytes9","pc2bytes10","pc2bytes11","pc2bytes12","pc2bytes13","iterations","keys","shifts","n","tmp","j","left","right","i","lefttmp","righttmp","input","decrypt","looping","endloop","loopinc","right1","right2","algorithm","start","require_pbkdf2","__commonJSMin","exports","module","forge","pkcs5","crypto","p","s","c","dkLen","md","callback","err","key","hLen","len","r","prf","dk","xor","u_c","u_c1","i","j","outer","inner","require_sha256","__commonJSMin","exports","module","forge","sha256","_initialized","_init","_state","_input","_w","md","int32s","msg","encoding","len","i","_update","finalBlock","remaining","overflow","_padding","next","carry","bits","s2","rval","_k","s","w","bytes","t1","t2","s0","s1","ch","maj","a","b","c","d","e","f","g","h","require_prng","__commonJSMin","exports","module","forge","_crypto","prng","plugin","ctx","md","pools","i","count","callback","cipher","increment","formatKey","formatSeed","b","generate","err","_reseed","bytes","_reseedSync","_seed","needed","_2powK","k","seedBytes","defaultSeedFile","getRandomValues","globalScope","arr","entropy","e","hi","lo","next","seed","n","x","worker","listener","data","require_random","__commonJSMin","exports","module","forge","jQuery","prng_aes","_prng_aes_output","_prng_aes_buffer","key","tmp","seed","spawnPrng","ctx","count","callback","_ctx","getRandomValues","globalScope","_crypto","arr","_navBytes","e","require_rc2","__commonJSMin","exports","module","forge","piTable","s","rol","word","bits","ror","key","effKeyBits","L","T","T1","T8","TM","i","createCipher","encrypt","_finish","_input","_output","_iv","mixRound","mashRound","j","K","R","runPlan","plan","val","ptr","ctr","cipher","iv","output","input","pad","rval","padding","len","count","require_jsbn","__commonJSMin","exports","module","forge","dbits","canary","j_lm","BigInteger","a","b","c","nbi","am1","i","x","w","j","n","v","am2","xl","xh","l","h","m","am3","BI_FP","BI_RM","BI_RC","rr","vv","int2char","intAt","s","bnpCopyTo","r","bnpFromInt","nbv","bnpFromString","k","mi","sh","bnpClamp","bnToString","km","d","p","bnNegate","bnAbs","bnCompareTo","nbits","t","bnBitLength","bnpDLShiftTo","bnpDRShiftTo","bnpLShiftTo","bs","cbs","bm","ds","bnpRShiftTo","bnpSubTo","bnpMultiplyTo","y","bnpSquareTo","bnpDivRemTo","q","pm","pt","ts","ms","nsh","ys","y0","yt","d1","d2","e","qd","bnMod","Classic","cConvert","cRevert","cReduce","cMulTo","cSqrTo","bnpInvDigit","Montgomery","montConvert","montRevert","montReduce","u0","montSqrTo","montMulTo","bnpIsEven","bnpExp","z","r2","g","bnModPowInt","bnClone","bnIntValue","bnByteValue","bnShortValue","bnpChunkSize","bnSigNum","bnpToRadix","cs","bnpFromRadix","bnpFromNumber","op_or","bnToByteArray","bnEquals","bnMin","bnMax","bnpBitwiseTo","op","f","op_and","bnAnd","bnOr","op_xor","bnXor","op_andnot","bnAndNot","bnNot","bnShiftLeft","bnShiftRight","lbit","bnGetLowestSetBit","cbit","bnBitCount","bnTestBit","bnpChangeBit","bnSetBit","bnClearBit","bnFlipBit","bnpAddTo","bnAdd","bnSubtract","bnMultiply","bnDivide","bnRemainder","bnDivideAndRemainder","bnpDMultiply","bnpDAddOffset","NullExp","nNop","nMulTo","nSqrTo","bnPow","bnpMultiplyLowerTo","bnpMultiplyUpperTo","Barrett","barrettConvert","barrettRevert","barrettReduce","barrettSqrTo","barrettMulTo","bnModPow","k1","g2","is1","bnGCD","bnpModInt","bnModInverse","ac","u","lowprimes","lplim","bnIsProbablePrime","bnpMillerRabin","n1","prng","bnGetPrng","require_sha1","__commonJSMin","exports","module","forge","sha1","_initialized","_init","_state","_input","_w","md","int32s","msg","encoding","len","i","_update","finalBlock","remaining","overflow","_padding","next","carry","bits","s2","rval","s","w","bytes","t","a","b","c","d","e","f","require_pkcs1","__commonJSMin","exports","module","forge","pkcs1","key","message","options","label","seed","md","mgf1Md","keyLength","maxLength","error","lHash","PS","PS_length","i","DB","dbMask","rsa_mgf1","maskedDB","seedMask","maskedSeed","em","y","db","lHashPrime","in_ps","index","j","code","is_0","error_mask","maskLength","hash","t","count","c","require_prime","__commonJSMin","exports","module","forge","prime","BigInteger","GCD_30_DELTA","THIRTY","op_or","x","bits","options","callback","algorithm","prng","rng","b","i","primeincFindPrime","primeincFindPrimeWithWorkers","primeincFindPrimeWithoutWorkers","num","generateRandom","deltaIdx","mrTests","getMillerRabinTests","maxBlockTime","_primeinc","start","numWorkers","workLoad","range","workerScript","err","cores","generate","workers","running","workerMessage","found","e","data","hex","bits1","require_rsa","__commonJSMin","exports","module","forge","BigInteger","_crypto","asn1","util","pki","GCD_30_DELTA","privateKeyValidator","rsaPrivateKeyValidator","rsaPublicKeyValidator","publicKeyValidator","digestInfoValidator","emsaPkcs1v15encode","md","oid","error","oidBytes","digestInfo","digestAlgorithm","digest","_modPow","x","key","pub","xp","xq","y","m","bt","eb","k","_encodePkcs1_v1_5","yhex","ed","zeros","ml","xhex","_decodePkcs1_v1_5","bits","e","options","prng","rng","b","i","algorithm","rval","state","n","THIRTY","deltaIdx","op_or","t1","t2","total","bits1","_getMillerRabinTests","d","callback","_detectNodeCrypto","err","priv","_detectSubtleCrypto","_intToUint8Array","pair","pkcs8","privateKey","_detectSubtleMsCrypto","genOp","exportOp","keypair","_generateKeyPair","data","scheme","schemeOptions","signature","obj","capture","errors","p","q","dP","dQ","qInv","rsaKey","_bnToBytes","padNum","padByte","numZeros","padBytes","em","first","zero","opts","generate","getPrime","num","finish","tmp","hex","bytes","fn","buffer","require_pbe","__commonJSMin","exports","module","forge","BigInteger","asn1","pki","oids","encryptedPrivateKeyValidator","PBES2AlgorithmsValidator","pkcs12PbeParamsValidator","obj","password","options","salt","count","countBytes","dkLen","encryptionAlgorithm","encryptedData","ivLen","encOid","cipherFn","error","prfAlgorithm","md","prfAlgorithmToMessageDigest","dk","iv","cipher","params","createPbkdf2Params","saltBytes","rval","capture","errors","oid","encrypted","epki","maxline","msg","pem","rsaKey","algorithm","key","id","iter","j","l","v","result","passBuf","p","s","D","Slen","S","Plen","P","I","c","i","buf","round","B","k","Inew","chunk","x","prfOidToMessageDigest","dIvLen","digests","hash","length","bytes","prfOid","factory","require_pkcs7asn1","__commonJSMin","exports","module","forge","asn1","p7v","contentInfoValidator","encryptedContentInfoValidator","signerValidator","require_mgf1","__commonJSMin","exports","module","forge","mgf1","md","mgf","seed","maskLen","t","len","i","c","require_mgf","__commonJSMin","exports","module","forge","require_pss","__commonJSMin","exports","module","forge","pss","options","hash","mgf","hLen","salt_","sLen","prng","pssobj","md","modBits","i","emBits","emLen","mHash","salt","m_","h","ps","db","maskLen","dbMask","maskedDB","mask","em","checkLen","h_","require_x509","__commonJSMin","exports","module","forge","asn1","pki","oids","_shortNames","publicKeyValidator","x509CertificateValidator","rsassaPssParameterValidator","certificationRequestInfoValidator","certificationRequestValidator","rdn","md","rval","set","attr","obj","si","i","attributes","seq","type","values","vi","ei","_getAttribute","options","_readSignatureParameters","oid","fillDefaults","params","capture","errors","error","_createSignatureDigest","_verifySignature","cert","scheme","hash","mgf","pem","computeHash","strict","msg","maxline","key","bytes","digest","hex","csr","sn","_fillMissingFields","attrs","uniqueId","exts","_fillMissingExtensionFields","ext","algorithmOid","child","issuer","subject","tbsCertificate","parent","s","iattr","sattr","n","ski","serial","validity","imd","ibytes","smd","sbytes","extseq","e","ev","b2","b3","value","gn","altName","cri","_dnToAsn1","valueTagClass","unused","keyIdentifier","authorityCertIssuer","serialNumber","subSeq","fullNameGeneralNames","_signatureParametersToAsn1","parts","_CRIAttributesToAsn1","valueConstructed","jan_1_1950","jan_1_2050","_dateToAsn1","date","notBefore","notAfter","tbs","dn","certs","caStore","getBySubject","ensureSubjectHasHash","tmp","match","der1","der2","certList","result","chain","validityCheckDate","first","depth","selfSigned","parents","verified","se","bcExt","keyUsageExt","pathLen","vfd","ret","require_pkcs12","__commonJSMin","exports","module","forge","asn1","pki","p12","contentInfoValidator","pfxValidator","safeBagValidator","attributeValidator","certBagValidator","_getBagsByAttribute","safeContents","attrName","attrValue","bagType","result","j","bag","obj","strict","password","capture","errors","error","pfx","filter","rval","localKeyId","friendlyName","data","_decodePkcs7Data","md","macKeyBytes","macAlgorithm","macSalt","macIterations","macKey","mac","macValue","_decodeAuthenticatedSafe","value","i","authSafe","contentInfo","_decryptSafeContents","_decodeSafeContents","oid","cipher","encryptedContentAsn1","encrypted","res","safeBag","_decodeBagAttributes","validator","decoder","bagAsn1","certAsn1","attributes","decodedAttrs","key","cert","options","bagAttrs","pairedCert","sha1","attrs","contents","chain","certSafeBags","certBagAttrs","certSafeBag","certSafeContents","certCI","keyBag","pkAsn1","keySafeContents","keyCI","safe","macData","count","require_pki","__commonJSMin","exports","module","forge","asn1","pki","pem","msg","error","obj","key","maxline","require_tls","__commonJSMin","exports","module","forge","prf_TLS1","secret","label","seed","length","rval","idx","slen","s1","s2","ai","hmac","md5itr","sha1itr","md5bytes","i","sha1bytes","hmac_sha1","key","seqNum","record","b","deflate","c","s","bytes","inflate","readVector","lenBytes","len","writeVector","v","tls","twoBytes","cs","ignore","msg","client","remaining","exts","ext","snl","snType","tmp","msgRandom","cRandom","sRandom","sessionId","SCC","SCE","session","version","CCC","CCE","CKE","cert","asn1","certs","ex","SKE","SCR","privateKey","sp","CCV","SHD","msgBytes","verify","error","depth","ret","SER","callback","signature","SFI","CFI","vd","vdl","prf","SAD","CAD","alert","type","hsTable","payload","SHE","CHE","__","R0","R1","R2","R3","R4","ctTable","H0","H1","H2","H3","H4","H5","H6","H7","H8","H9","random","tls10","km","createMode","mode","state","d","utc","options","cipherSuites","cSuites","compressionMethods","cMethods","extensions","serverName","snList","extLength","hint","certList","der","certBuffer","certTypes","cAs","dn","byteBuffer","payloadLength","plaintextLength","paddingLength","records","data","rec","_certErrorToAlertDesc","_alertDescToCertError","desc","chain","vfd","err","cache","capacity","caStore","entity","sessionCache","cn","dpth","cts","fatal","clearFail","_update","aligned","handlers","_readRecordHeader","compatibleVersion","_readRecord","require_aesCipherSuites","__commonJSMin","exports","module","forge","tls","sp","initConnectionState","state","c","client","decrypt_aes_cbc_sha1","encrypt_aes_cbc_sha1","record","s","rval","mac","iv","cipher","encrypt_aes_cbc_sha1_padding","blockSize","input","decrypt","padding","decrypt_aes_cbc_sha1_padding","output","len","paddingLength","i","macLen","mac2","compareMacs","key","mac1","hmac","require_sha512","__commonJSMin","exports","module","forge","sha512","sha384","algorithm","_initialized","_init","_states","_state","_h","_input","_w","wi","digestLength","md","int32s","i","msg","encoding","len","_update","finalBlock","remaining","overflow","_padding","next","carry","bits","h","rval","hlen","_k","s","w","bytes","t1_hi","t1_lo","t2_hi","t2_lo","s0_hi","s0_lo","s1_hi","s1_lo","ch_hi","ch_lo","maj_hi","maj_lo","a_hi","a_lo","b_hi","b_lo","c_hi","c_lo","d_hi","d_lo","e_hi","e_lo","f_hi","f_lo","g_hi","g_lo","h_hi","h_lo","hi","lo","w2","w7","w15","w16","require_asn1_validator","__commonJSMin","exports","forge","asn1","require_ed25519","__commonJSMin","exports","module","forge","asn1Validator","publicKeyValidator","privateKeyValidator","BigInteger","ByteBuffer","NativeBuffer","ed25519","options","seed","messageToNativeBuffer","pk","sk","i","crypto_sign_keypair","obj","capture","errors","valid","error","oid","ed25519Oid","privateKey","privateKeyBytes","publicKeyBytes","msg","keyPair","signedMsg","crypto_sign","sig","publicKey","sm","m","crypto_sign_open","message","encoding","buffer","gf0","gf","gf1","D","D2","X","Y","L","I","sha512","msgLen","md","hash","out","p","d","scalarbase","pack","n","j","x","smlen","r","reduce","h","modL","mlen","t","q","unpackneg","scalarmult","add","crypto_verify_32","carry","k","b","c","e","f","g","Z","M","A","cswap","sel25519","tx","ty","zi","inv25519","pack25519","par25519","o","car25519","chk","num","den","den2","den4","den6","set25519","unpack25519","S","pow2523","neq25519","a","xi","y","yi","vn","s","v","init","t0","t1","t2","t3","t4","t5","t6","t7","t8","t9","t10","t11","t12","t13","t14","t15","t16","t17","t18","t19","t20","t21","t22","t23","t24","t25","t26","t27","t28","t29","t30","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","b10","b11","b12","b13","b14","b15","require_kem","__commonJSMin","exports","module","forge","BigInteger","kdf","options","prng","kem","publicKey","keyLength","byteLength","r","zeros","encapsulation","key","privateKey","md","digestLength","_createKDF","counterStart","x","length","k","c","i","hash","require_log","__commonJSMin","exports","module","forge","sLevelInfo","sLoggers","sConsoleLogger","i","level","message","messageLevelIndex","logger","loggerLevelIndex","args","levels","category","msg","logFunction","rval","aValidLevel","lock","levelHandlers","f","handler","query","require_md_all","__commonJSMin","exports","module","require_pkcs7","__commonJSMin","exports","module","forge","asn1","p7","pem","msg","error","obj","maxline","pemObj","capture","errors","contentType","_fromAsn1","certs","i","crls","signedData","signer","issuer","serialNumber","cert","key","digestAlgorithm","authenticatedAttributes","messageDigest","attr","options","content","mds","addDigestAlgorithmIds","addSignerInfos","crl","oid","bytes","signingTime","attrsAsn1","ai","_attributeToAsn1","_signersToAsn1","_decryptContent","_recipientsFromAsn1","_recipientsToAsn1","_encryptedContentToAsn1","sAttr","r","rAttr","match","j","recipient","privKey","cipher","keyLen","ivLen","ciphFn","ciph","_recipientFromAsn1","_recipientToAsn1","infos","ret","recipients","_signerToAsn1","rval","signers","value","jan_1_1950","jan_1_2050","date","timestamp","ec","validator","require_ssh","__commonJSMin","exports","module","forge","ssh","privateKey","passphrase","comment","algorithm","encryptionAlgorithm","ppk","pubbuffer","_addStringToBuffer","_addBigIntegerToBuffer","pub","length","privbuffer","priv","encLen","padding","_sha1","aeskey","cipher","encrypted","mackey","macbuffer","hmac","key","type","buffer","options","md","digest","hex","val","hexVal","bytes","sha","num","i","require_lib","__commonJSMin","exports","module","require_selfsigned","__commonJSMin","exports","forge","toPositiveHex","hexString","mostSiginficativeHexAsInt","getAlgorithm","key","attrs","options","done","generatePem","keyPair","cert","notAfter","fingerprint","pem","p7","clientkeys","clientcert","clientAttrs","i","clientp7","caStore","vfd","depth","chain","ex","keySize","err","isBodyParseError","error","ErrorType","ErrorSeverity","BlaizeError","init_errors","__esmMin","type","title","status","correlationId","details","base","generateCorrelationId","timestamp","random","getCurrentCorrelationId","stored","correlationStorage","import_node_async_hooks","init_correlation","__esmMin","internal_server_error_exports","__export","InternalServerError","init_internal_server_error","__esmMin","init_errors","init_correlation","BlaizeError","title","details","correlationId","getCurrentCorrelationId","validation_error_exports","__export","ValidationError","init_validation_error","__esmMin","init_errors","init_correlation","BlaizeError","title","details","correlationId","getCurrentCorrelationId","payload_too_large_error_exports","__export","PayloadTooLargeError","init_payload_too_large_error","__esmMin","init_correlation","init_errors","BlaizeError","title","details","correlationId","getCurrentCorrelationId","unsupported_media_type_error_exports","__export","UnsupportedMediaTypeError","init_unsupported_media_type_error","__esmMin","init_correlation","init_errors","BlaizeError","title","details","correlationId","getCurrentCorrelationId","index_exports","__export","Blaize","BlaizeError","ConflictError","ErrorSeverity","ErrorType","ForbiddenError","InternalServerError","MiddlewareAPI","NotFoundError","PayloadTooLargeError","PluginsAPI","RateLimitError","RequestTimeoutError","RouterAPI","ServerAPI","UnauthorizedError","UnprocessableEntityError","UnsupportedMediaTypeError","VERSION","ValidationError","compose","createDeleteRoute","createGetRoute","createHeadRoute","create","createOptionsRoute","createPatchRoute","createPostRoute","createPutRoute","isBodyParseError","__toCommonJS","execute","middleware","ctx","next","result","error","compose","middlewareStack","_","next","ctx","finalHandler","called","dispatch","middleware","execute","create","handlerOrOptions","name","handler","skip","debug","middleware","create","name","version","setup","defaultOptions","userOptions","mergedOptions","plugin","app","result","import_node_url","config","setRuntimeConfig","newConfig","getRoutesDir","config","path","parseRoutePath","filePath","basePath","forwardSlashFilePath","forwardSlashBasePath","normalizedBasePath","relativePath","segments","params","routeSegments","segment","paramName","routePath","getCallerFilePath","originalPrepareStackTrace","_","stack","callerFrame","fileName","getRoutePath","callerPath","routesDir","getRoutesDir","parsedRoute","parseRoutePath","createGetRoute","config","validateMethodConfig","path","createPostRoute","createPutRoute","createDeleteRoute","createPatchRoute","createHeadRoute","createOptionsRoute","method","validateSchema","schema","params","query","body","response","import_node_async_hooks","import_node_events","fs","http","http2","fs","path","selfsigned","generateDevCertificates","certDir","keyPath","certPath","pems","ResponseSentError","message","ResponseSentHeaderError","ResponseSentContentError","ParseUrlError","import_node_async_hooks","contextStorage","runWithContext","context","callback","contextStorage","import_node_crypto","import_node_fs","import_node_os","import_node_path","import_node_stream","BOUNDARY_REGEX","CONTENT_DISPOSITION_REGEX","CONTENT_TYPE_REGEX","MULTIPART_REGEX","extractBoundary","contentType","match","boundary","parseContentDisposition","headers","parseContentType","isMultipartContent","DEFAULT_OPTIONS","createParserState","boundary","options","processChunk","state","chunk","newBuffer","currentState","nextState","processCurrentStage","processBoundary","processHeaders","processContent","InternalServerError","boundaryIndex","hasFoundValidBoundary","buffer","headerEnd","headers","disposition","parseContentDisposition","ValidationError","mimetype","parseContentType","isFile","PayloadTooLargeError","UnsupportedMediaTypeError","nextBoundaryIndex","contentChunk","isComplete","safeLength","contentEnd","updatedState","processContentChunk","finalizeCurrentPart","newContentLength","maxSize","payloadErrorDetals","processFileChunk","writeToStream","initializeFileProcessing","streamController","stream","controller","tempPath","writeStream","cleanupTask","unlink","error","finalizeFile","finalizeField","resetCurrentPart","closeStream","file","updatedFiles","addToCollection","value","updatedFields","collection","key","newCollection","existing","finalize","fields","values","files","fileList","cleanup","task","resolve","reject","parseMultipartRequest","request","contentType","extractBoundary","CONTENT_TYPE_HEADER","DEFAULT_BODY_LIMITS","parseRequestUrl","req","originalUrl","host","fullUrl","url","path","query","value","key","error","ParseUrlError","isHttp2Request","getProtocol","encrypted","forwardedProto","createContext","res","options","method","isHttp2","protocol","params","state","responseState","ctx","createRequestObject","createResponseObject","parseBodyIfNeeded","info","createRequestHeaderGetter","createRequestHeadersGetter","name","headerGetter","names","acc","createStatusSetter","createHeaderSetter","createHeadersSetter","createContentTypeSetter","createJsonResponder","createTextResponder","createHtmlResponder","createRedirectResponder","createStreamResponder","code","ResponseSentError","ResponseSentHeaderError","headers","type","ResponseSentContentError","body","status","readable","err","shouldSkipParsing","contentType","contentLength","limits","parseJsonBody","parseFormUrlEncodedBody","parseTextBody","isMultipartContent","parseMultipartBody","errorType","setBodyError","readRequestBody","json","parseUrlEncodedData","formData","multipartLimits","multipartData","parseMultipartRequest","message","bodyError","resolve","reject","chunks","chunk","init_errors","init_correlation","NotFoundError","BlaizeError","title","details","correlationId","getCurrentCorrelationId","init_errors","init_correlation","init_internal_server_error","isHandledError","error","BlaizeError","formatErrorResponse","correlationId","generateCorrelationId","originalMessage","wrappedError","InternalServerError","extractOrGenerateCorrelationId","headerGetter","setErrorResponseHeaders","headerSetter","createErrorBoundary","options","debug","ctx","next","error","correlationId","extractOrGenerateCorrelationId","errorResponse","formatErrorResponse","setErrorResponseHeaders","createRequestHandler","serverInstance","req","res","context","createContext","allMiddleware","createErrorBoundary","handler","compose","runWithContext","NotFoundError","error","prepareCertificates","http2Options","keyFile","certFile","isDevMode","certificatesMissing","generateDevCertificates","createServerInstance","isHttp2","certOptions","http2ServerOptions","err","listenOnPort","server","port","host","resolve","reject","url","initializePlugins","serverInstance","plugin","startServer","serverOptions","requestHandler","createRequestHandler","error","isShuttingDown","stopServer","serverInstance","options","server","events","timeout","_","reject","error","closePromise","resolve","err","timeoutPromise","registerSignalHandlers","stopFn","sigintHandler","sigtermHandler","import_zod","middlewareSchema","data","pluginSchema","http2Schema","serverOptionsSchema","validateServerOptions","options","error","formattedError","createPluginLifecycleManager","options","continueOnError","debug","onError","log","message","args","handleError","plugin","phase","error","errorMessage","server","pluginsToTerminate","httpServer","pluginsToNotify","PluginValidationError","pluginName","message","RESERVED_NAMES","VALID_NAME_PATTERN","VALID_VERSION_PATTERN","validatePlugin","plugin","options","requireVersion","validateNameFormat","checkReservedNames","PluginValidationError","p","lifecycleMethods","method","crypto","fs","import_node_module","path","dynamicImport","filePath","cacheBuster","importPath","module","error","errorMessage","loadRouteModule","basePath","parsedRoute","parseRoutePath","routes","route","exportName","exportValue","potentialRoute","isValidRoute","obj","method","import_meta","fileRouteCache","processChangedFile","filePath","routesDir","updateCache","lastModified","cachedEntry","invalidateModuleCache","routes","loadRouteModule","hash","hashRoutes","hasRouteContentChanged","newRoutes","newHash","clearFileCache","routeData","route","key","method","methodDef","handlerString","dataString","absolutePath","resolvedPath","resolveError","errorMessage","require","error","os","fs","path","findRouteFiles","routesDir","options","absoluteDir","error","routeFiles","ignore","scanDirectory","dir","entries","entry","fullPath","isRouteFile","filename","processFilesInParallel","filePaths","processor","concurrency","chunks","chunkArray","results","chunk","successfulResults","filePath","result","loadInitialRoutesParallel","routesDir","files","findRouteFiles","processChangedFile","array","chunkSize","i","profilerState","trackReloadPerformance","filePath","startTime","duration","emoji","withPerformanceTracking","fn","filePath","args","startTime","result","trackReloadPerformance","error","path","import_fs","import_promises","import_events","sysPath","import_promises","import_node_stream","import_node_path","EntryTypes","defaultOptions","_entryInfo","RECURSIVE_ERROR_CODE","NORMAL_FLOW_ERRORS","ALL_TYPES","DIR_TYPES","FILE_TYPES","isNormalFlowError","error","wantBigintFsStats","emptyFn","normalizeFilter","filter","fl","entry","trItems","item","f","ReaddirpStream","options","opts","root","type","statMethod","path","presolve","batch","par","fil","depth","slice","dirent","awaited","entryType","parent","files","basename","fullPath","pjoin","prelative","err","stats","full","entryRealPath","entryRealPathStats","len","psep","recursiveError","readdirp","import_fs","import_promises","sysPath","import_os","STR_DATA","STR_END","STR_CLOSE","EMPTY_FN","pl","isWindows","isMacos","isLinux","isFreeBSD","isIBMi","osType","EVENTS","EV","THROTTLE_MODE_WATCH","statMethods","KEY_LISTENERS","KEY_ERR","KEY_RAW","HANDLER_KEYS","binaryExtensions","isBinaryPath","filePath","foreach","val","fn","addAndConvert","main","prop","item","container","clearItem","cont","key","set","delFromSet","isEmptySet","FsWatchInstances","createFsWatchInstance","path","options","listener","errHandler","emitRaw","handleEvent","rawEvent","evPath","fsWatchBroadcast","fs_watch","error","fullPath","listenerType","val1","val2","val3","setFsWatchListener","handlers","rawEmitter","watcher","broadcastErr","FsWatchFileInstances","setFsWatchFileListener","copts","curr","prev","currmtime","NodeFsHandler","fsW","opts","directory","basename","absolutePath","EMPTY_FN","closer","enableBin","file","stats","initialAdd","dirname","parent","prevStats","newStats","at","mt","entry","full","dir","linkPath","fsrealpath","wh","target","depth","throttler","previous","current","stream","STR_DATA","resolve","reject","STR_END","wasThrottled","realpath","parentDir","tracked","oDepth","dirPath","priorWh","ready","follow","absPath","targetPath","SLASH","SLASH_SLASH","ONE_DOT","TWO_DOTS","STRING_TYPE","BACK_SLASH_RE","DOUBLE_SLASH_RE","DOT_RE","REPLACER_RE","arrify","item","isMatcherObject","matcher","createPattern","string","relative","normalizePath","path","prepend","matchPatterns","patterns","testString","stats","index","pattern","anymatch","matchers","unifyPaths","paths_","paths","p","normalizePathToUnix","toUnix","str","normalizeIgnored","cwd","getAbsolutePath","EMPTY_SET","DirEntry","dir","removeWatcher","items","EMPTY_FN","STAT_METHOD_F","STAT_METHOD_L","WatchHelper","follow","fsw","watchPath","parts","entry","resolvedPath","FSWatcher","_opts","awf","DEF_AWF","opts","isIBMi","envPoll","envLower","envInterval","readyCalls","EVENTS","args","NodeFsHandler","ignored","_origAdd","_internal","res","results","closers","closerList","closer","promise","stream","dirent","watchList","event","isWindows","pw","awfEmit","err","fullPath","error","code","actionType","timeout","action","actionPath","timeoutObject","clear","count","thr","threshold","pollInterval","timeoutHandler","now","writes","awaitWriteFinishFn","prevStat","statcb","curStat","list","stat","directory","isDirectory","nested","parent","wasTracked","relPath","eventName","root","options","readdirp","STR_CLOSE","STR_END","watch","watcher","watchRoutes","routesDir","options","debounceMs","debouncedCallbacks","createDebouncedCallback","fn","filePath","args","existingTimeout","timeoutId","routesByPath","loadInitialRoutes","files","findRouteFiles","loadAndNotify","error","handleError","existingRoutes","newRoutes","processChangedFile","hasRouteContentChanged","normalizedPath","handleRemoved","routes","watcher","watch","timeout","allRoutes","import_zod","import_zod","validateBody","body","schema","import_zod","validateParams","params","schema","import_zod","validateQuery","query","schema","import_zod","validateResponse","response","schema","init_internal_server_error","init_validation_error","createRequestValidator","schema","debug","ctx","next","validateParams","error","fieldErrors","extractZodFieldErrors","errorCount","sum","fe","ValidationError","validateQuery","validateBody","createResponseValidator","responseSchema","originalJson","body","status","validatedBody","validateResponse","InternalServerError","fieldErrorMap","issue","fieldPath","field","messages","executeHandler","ctx","routeOptions","params","middleware","createRequestValidator","createResponseValidator","compose","result","extractParams","path","pattern","paramNames","match","params","compilePathPattern","patternString","_","paramName","createMatcher","routes","path","method","routeOptions","pattern","paramNames","compilePathPattern","newRoute","insertIndex","route","i","pathname","params","extractParams","createRouteRegistry","updateRoutesFromFile","registry","filePath","newRoutes","oldPaths","newPaths","r","added","removed","p","changed","route","existingRoute","routesEqual","applyRouteUpdates","getAllRoutesFromRegistry","registry","applyRouteUpdates","registry","filePath","updates","added","removed","changed","path","route","allPathsForFile","r","p","routesEqual","route1","route2","methods1","k","methods2","method","handler1","handler2","addRouteToMatcher","route","matcher","method","methodOptions","removeRouteFromMatcher","path","updateRouteInMatcher","DEFAULT_ROUTER_OPTIONS","createRouter","options","routerOptions","registry","createRouteRegistry","matcher","createMatcher","initialized","initializationPromise","_watchers","routeDirectories","applyMatcherChanges","changes","routePath","removeRouteFromMatcher","route","methods","key","addRouteToMatcher","updateRouteInMatcher","addRoutesWithSource","routes","source","updateRoutesFromFile","error","loadRoutesFromDirectory","directory","prefix","discoveredRoutes","loadInitialRoutesParallel","finalRoutes","initialize","setupOptimizedWatching","watcher","watchRoutes","filepath","addedRoutes","withPerformanceTracking","changedRoutes","filePath","removedRoutes","clearFileCache","setupWatcherForNewDirectory","finalPath","ctx","method","path","match","NotFoundError","executeHandler","getAllRoutesFromRegistry","DEFAULT_OPTIONS","createServerOptions","options","baseOptions","setRuntimeConfig","createListenMethod","serverInstance","validatedOptions","initialMiddleware","initialPlugins","initializeComponents","startServer","setupServerLifecycle","mw","p","signalHandlers","registerSignalHandlers","createCloseMethod","stopOptions","stopServer","createUseMethod","middleware","middlewareArray","createRegisterMethod","plugin","validatePlugin","create","mergedOptions","validateServerOptions","error","port","host","plugins","contextStorage","router","createRouter","pluginManager","createPluginLifecycleManager","events","EventEmitter","init_errors","init_validation_error","init_errors","init_correlation","UnauthorizedError","BlaizeError","title","details","correlationId","getCurrentCorrelationId","init_errors","init_correlation","ForbiddenError","BlaizeError","title","details","correlationId","getCurrentCorrelationId","init_errors","init_correlation","ConflictError","BlaizeError","title","details","correlationId","getCurrentCorrelationId","init_errors","init_correlation","RateLimitError","BlaizeError","title","details","correlationId","getCurrentCorrelationId","init_internal_server_error","init_payload_too_large_error","init_correlation","init_errors","RequestTimeoutError","BlaizeError","title","details","correlationId","getCurrentCorrelationId","init_unsupported_media_type_error","init_correlation","init_errors","UnprocessableEntityError","BlaizeError","title","details","correlationId","getCurrentCorrelationId","VERSION","ServerAPI","create","RouterAPI","createDeleteRoute","createGetRoute","createHeadRoute","createOptionsRoute","createPatchRoute","createPostRoute","createPutRoute","MiddlewareAPI","compose","PluginsAPI","Blaize"]}
|