smartproxy/ts/common/port80-adapter.ts

111 lines
3.2 KiB
TypeScript

import * as plugins from '../plugins.js';
import type {
IForwardConfig as ILegacyForwardConfig,
IDomainOptions
} from './types.js';
import type {
IForwardConfig
} from '../forwarding/config/forwarding-types.js';
/**
* Converts a forwarding configuration target to the legacy format
* for Port80Handler
*/
export function convertToLegacyForwardConfig(
forwardConfig: IForwardConfig
): ILegacyForwardConfig {
// Determine host from the target configuration
const host = Array.isArray(forwardConfig.target.host)
? forwardConfig.target.host[0] // Use the first host in the array
: forwardConfig.target.host;
// Extract port number, handling different port formats
let port: number;
if (typeof forwardConfig.target.port === 'function') {
// Use a default port for function-based ports in adapter context
port = 80;
} else if (forwardConfig.target.port === 'preserve') {
// For 'preserve', use the default port 80 in this adapter context
port = 80;
} else {
port = forwardConfig.target.port;
}
return {
ip: host,
port: port
};
}
/**
* Creates Port80Handler domain options from a domain name and forwarding config
*/
export function createPort80HandlerOptions(
domain: string,
forwardConfig: IForwardConfig
): IDomainOptions {
// Determine if we should redirect HTTP to HTTPS
let sslRedirect = false;
if (forwardConfig.http?.redirectToHttps) {
sslRedirect = true;
}
// Determine if ACME maintenance should be enabled
// Enable by default for termination types, unless explicitly disabled
const requiresTls =
forwardConfig.type === 'https-terminate-to-http' ||
forwardConfig.type === 'https-terminate-to-https';
const acmeMaintenance =
requiresTls &&
forwardConfig.acme?.enabled !== false;
// Set up forwarding configuration
const options: IDomainOptions = {
domainName: domain,
sslRedirect,
acmeMaintenance
};
// Add ACME challenge forwarding if configured
if (forwardConfig.acme?.forwardChallenges) {
options.acmeForward = {
ip: Array.isArray(forwardConfig.acme.forwardChallenges.host)
? forwardConfig.acme.forwardChallenges.host[0]
: forwardConfig.acme.forwardChallenges.host,
port: forwardConfig.acme.forwardChallenges.port
};
}
// Add HTTP forwarding if this is an HTTP-only config or if HTTP is enabled
const supportsHttp =
forwardConfig.type === 'http-only' ||
(forwardConfig.http?.enabled !== false &&
(forwardConfig.type === 'https-terminate-to-http' ||
forwardConfig.type === 'https-terminate-to-https'));
if (supportsHttp) {
// Determine port value handling different formats
let port: number;
if (typeof forwardConfig.target.port === 'function') {
// Use a default port for function-based ports
port = 80;
} else if (forwardConfig.target.port === 'preserve') {
// For 'preserve', use 80 in this adapter context
port = 80;
} else {
port = forwardConfig.target.port;
}
options.forward = {
ip: Array.isArray(forwardConfig.target.host)
? forwardConfig.target.host[0]
: forwardConfig.target.host,
port: port
};
}
return options;
}