//#region src/gateway/security/preauth-connection-budget.ts
/**
* Pre-authentication connection budget per IP address.
*
* Limits the number of concurrent unauthenticated connections from a single
* IP to prevent connection-flood DoS attacks. Once a connection authenticates
* successfully, its slot is released.
*/
const DEFAULT_MAX_PREAUTH_CONNECTIONS_PER_IP = 32;
const UNKNOWN_CLIENT_IP_BUDGET_KEY = "__xopc_unknown_client_ip__";
function getMaxPreauthConnectionsPerIp(env = process.env) {
	const configured = env.XOPC_MAX_PREAUTH_CONNECTIONS_PER_IP;
	if (!configured) return DEFAULT_MAX_PREAUTH_CONNECTIONS_PER_IP;
	const parsed = Number(configured);
	if (!Number.isFinite(parsed) || parsed < 1) return DEFAULT_MAX_PREAUTH_CONNECTIONS_PER_IP;
	return Math.max(1, Math.floor(parsed));
}
function createPreauthConnectionBudget(limit = getMaxPreauthConnectionsPerIp()) {
	const counts = /* @__PURE__ */ new Map();
	function normalizeBudgetKey(clientIp) {
		return clientIp?.trim() || UNKNOWN_CLIENT_IP_BUDGET_KEY;
	}
	return {
		acquire(clientIp) {
			const ip = normalizeBudgetKey(clientIp);
			const next = (counts.get(ip) ?? 0) + 1;
			if (next > limit) return false;
			counts.set(ip, next);
			return true;
		},
		release(clientIp) {
			const ip = normalizeBudgetKey(clientIp);
			const current = counts.get(ip);
			if (current === void 0) return;
			if (current <= 1) {
				counts.delete(ip);
				return;
			}
			counts.set(ip, current - 1);
		},
		size() {
			return counts.size;
		}
	};
}
//#endregion
export { createPreauthConnectionBudget, getMaxPreauthConnectionsPerIp };

//# sourceMappingURL=preauth-connection-budget.js.map