clove/isATracker
src/lib/server/rules/unsupportedTlds.ts
/* src/lib/server/rules/unsupportedTlds.ts
* MIT — (c) Doughmination System®
*/
import { readFileSync } from 'node:fs';
import { loads } from 'jpcl-lang';
import { getConfig } from '../config.ts';
import { createLogger } from '../logger.ts';
import { readHttpHostname, readRecordTarget } from './recordTargets.ts';
import type { Rule, Violation } from './types.ts';
const logger = createLogger('unsupportedTlds');
export function getUnsupportedTlds(): Set<string> {
try {
const file = loads(readFileSync(getConfig().unsupportedTldsPath, 'utf8'));
const list: unknown = file.tlds;
if (!Array.isArray(list)) {
throw new Error('expected a "tlds" array of top-level domains');
}
const tlds = new Set<string>();
for (const entry of list) {
if (typeof entry === 'string') {
const tld = entry.trim().toLowerCase().replace(/^\./, '');
if (/^[a-z0-9-]+$/.test(tld)) {
tlds.add(tld);
}
}
}
return tlds;
} catch (error) {
logger.warn('Could not read the unsupported TLD list', error);
return new Set();
}
}
export function hasUnsupportedTld(hostname: string, tlds: ReadonlySet<string>): boolean {
const host = hostname.toLowerCase().replace(/\.$/, '');
const lastDot = host.lastIndexOf('.');
return tlds.has(host.slice(lastDot + 1));
}
export const unsupportedUrlTldRule: Rule = {
id: 'unsupportedUrlTld',
title: 'URL target has an unsupported TLD',
severity: 2,
actionType: 'requestChanges',
actionLabel: 'Request Changes',
findLine(file) {
const lineIndex = file.content.split('\n').findIndex((line) => /"\s*url\s*"\s*:/i.test(line));
return lineIndex === -1 ? null : lineIndex + 1;
},
async evaluate(context) {
const tlds = getUnsupportedTlds();
const violations: Violation[] = [];
for (const file of context.files) {
const target = readRecordTarget(file.json, 'URL');
const hostname = target === null ? null : readHttpHostname(target);
if (hostname !== null && hasUnsupportedTld(hostname, tlds)) {
violations.push({
ruleId: 'unsupportedUrlTld',
filePath: file.path,
reason: `URL points at a host with an unsupported TLD (${hostname}).`
});
}
}
return violations;
}
};