Files
smartnftables/ts/nft.manager.nat.ts
2026-03-26 10:32:05 +00:00

77 lines
2.4 KiB
TypeScript

import type { SmartNftables } from './nft.manager.js';
import type { INftDnatRule, INftSnatRule, INftMasqueradeRule, TNftProtocol } from './nft.types.js';
import { buildDnatRules, buildSnatRule, buildMasqueradeRule } from './nft.rulebuilder.nat.js';
/**
* Manages NAT (DNAT/SNAT/masquerade) rules.
*/
export class NatManager {
constructor(private parent: SmartNftables) {}
/**
* Add a port forwarding rule (DNAT + optional masquerade).
*/
public async addPortForwarding(groupId: string, rule: INftDnatRule): Promise<void> {
const commands = buildDnatRules(this.parent.tableName, this.parent.family, rule);
await this.parent.applyRuleGroup(`nat:${groupId}`, commands);
}
/**
* Remove a previously added port forwarding group.
*/
public async removePortForwarding(groupId: string): Promise<void> {
await this.parent.removeRuleGroup(`nat:${groupId}`);
}
/**
* Add SNAT (source NAT) rule.
*/
public async addSnat(groupId: string, rule: INftSnatRule): Promise<void> {
const commands = buildSnatRule(this.parent.tableName, this.parent.family, rule);
await this.parent.applyRuleGroup(`nat:snat:${groupId}`, commands);
}
/**
* Add masquerade rule for outgoing traffic.
*/
public async addMasquerade(groupId: string, rule: INftMasqueradeRule): Promise<void> {
const commands = buildMasqueradeRule(this.parent.tableName, this.parent.family, rule);
await this.parent.applyRuleGroup(`nat:masq:${groupId}`, commands);
}
/**
* Add port forwarding for a range of ports.
* Maps sourceStart..sourceStart+count to targetStart..targetStart+count.
*/
public async addPortRange(
groupId: string,
sourceStart: number,
sourceEnd: number,
targetHost: string,
targetStart: number,
protocol?: TNftProtocol,
): Promise<void> {
const allCommands: string[] = [];
const count = sourceEnd - sourceStart;
for (let i = 0; i <= count; i++) {
const commands = buildDnatRules(this.parent.tableName, this.parent.family, {
sourcePort: sourceStart + i,
targetHost,
targetPort: targetStart + i,
protocol,
});
allCommands.push(...commands);
}
await this.parent.applyRuleGroup(`nat:range:${groupId}`, allCommands);
}
/**
* Remove a port range forwarding group.
*/
public async removePortRange(groupId: string): Promise<void> {
await this.parent.removeRuleGroup(`nat:range:${groupId}`);
}
}