Dough Git

clove/isATracker

src/lib/server/rules/rules.test.ts

back to src/lib/server/rules

/* src/lib/server/rules/rules.test.ts
 * MIT — (c) Doughmination System®
 */

import assert from 'node:assert/strict';
import { describe, test } from 'node:test';

import { getCommentableLines } from '../github/diff.ts';
import { cnameUrlRule } from './cnameUrl.ts';
import { findNoReplyEmail, findOwnerEmailLine } from './noReplyEmail.ts';
import { findNsRecords } from './nsRecords.ts';
import { ownerUsernameMismatchRule } from './ownerUsernameMismatch.ts';
import { findCnameLine, findUnsupportedCname } from './unsupportedCname.ts';
import { unsupportedUrlTldRule } from './unsupportedTlds.ts';
import { findVercelLinks, redirectsToVercelLogin } from './vercelLogin.ts';
import {
	findVercelTxt,
	vercelFileFor,
	vercelFileNameRule,
	vercelTxtRecordRule
} from './vercelVerification.ts';
import type { DomainFile, RuleContext } from './types.ts';

describe('findNsRecords', () => {
	test('finds NS records under "records"', () => {
		const json = {
			records: {
				NS: ['ns1.example.com', 'ns2.example.com']
			}
		};

		assert.deepEqual(findNsRecords(json), ['ns1.example.com', 'ns2.example.com']);
	});

	test('finds NS records under the older "record" key', () => {
		const json = {
			record: {
				ns: ['ns1.example.com']
			}
		};

		assert.deepEqual(findNsRecords(json), ['ns1.example.com']);
	});

	test('ignores ordinary record types', () => {
		const json = {
			records: {
				A: ['1.2.3.4'],
				CNAME: 'example.com',
				TXT: 'ns1.example.com'
			}
		};

		assert.deepEqual(findNsRecords(json), []);
	});

	test('ignores an empty NS list and broken JSON', () => {
		assert.deepEqual(findNsRecords({ records: { NS: [] } }), []);
		assert.deepEqual(findNsRecords(null), []);
		assert.deepEqual(findNsRecords('NS'), []);
	});
});

describe('findNoReplyEmail', () => {
	test('matches both no-reply forms', () => {
		const plain = { owner: { email: '[email protected]' } };
		const numbered = { owner: { email: '[email protected]' } };

		assert.equal(findNoReplyEmail(plain), '[email protected]');
		assert.equal(findNoReplyEmail(numbered), '[email protected]');
	});

	test('ignores personal addresses, missing emails and look-alike domains', () => {
		assert.equal(findNoReplyEmail({ owner: { email: '[email protected]' } }), null);
		assert.equal(findNoReplyEmail({ owner: { username: 'clove' } }), null);
		assert.equal(
			findNoReplyEmail({ owner: { email: '[email protected]' } }),
			null
		);
	});

	test('only reads owner.email, not other fields', () => {
		const json = {
			owner: { username: 'clove' },
			description: 'mail me at [email protected]'
		};

		assert.equal(findNoReplyEmail(json), null);
	});
});

describe('findUnsupportedCname', () => {
	const unsupported = ['vercel.app', 'pages.dev'];

	test('matches a listed host and its subdomains, ignoring case and a trailing dot', () => {
		assert.equal(
			findUnsupportedCname({ records: { CNAME: 'vercel.app' } }, unsupported),
			'vercel.app'
		);
		assert.equal(
			findUnsupportedCname({ record: { cname: 'Me.Pages.Dev.' } }, unsupported),
			'Me.Pages.Dev.'
		);
	});

	test('ignores supported hosts, look-alikes and missing CNAMEs', () => {
		assert.equal(findUnsupportedCname({ records: { CNAME: 'me.github.io' } }, unsupported), null);
		assert.equal(findUnsupportedCname({ records: { CNAME: 'notvercel.app' } }, unsupported), null);
		assert.equal(findUnsupportedCname({ records: { A: ['1.2.3.4'] } }, unsupported), null);
		assert.equal(findUnsupportedCname({ records: { CNAME: 'vercel.app' } }, []), null);
	});

	test('list entries written as ".tld" match that whole TLD', () => {
		const tlds = ['.tk', '.blob.core.windows.net', '*.workers.dev'];

		assert.equal(findUnsupportedCname({ records: { CNAME: 'site.tk' } }, tlds), 'site.tk');
		assert.equal(
			findUnsupportedCname({ records: { CNAME: 'a.blob.core.windows.net' } }, tlds),
			'a.blob.core.windows.net'
		);
		assert.equal(
			findUnsupportedCname({ records: { CNAME: 'me.workers.dev' } }, tlds),
			'me.workers.dev'
		);
		assert.equal(findUnsupportedCname({ records: { CNAME: 'site.tkx' } }, tlds), null);
	});

	test('finds the CNAME line', () => {
		assert.equal(findCnameLine('{\n  "records": {\n    "CNAME": "x.vercel.app"\n  }\n}'), 3);
	});
});

describe('review line placement', () => {
	const content = [
		'{',
		'  "owner": {',
		'    "username": "clove",',
		'    "email": "[email protected]"',
		'  },',
		'  "records": {}',
		'}'
	].join('\n');

	test('finds the owner.email line', () => {
		assert.equal(findOwnerEmailLine(content, '[email protected]'), 4);
	});

	test('a new file makes every line commentable', () => {
		const patch = '@@ -0,0 +1,3 @@\n+{\n+  "a": 1\n+}\n\\ No newline at end of file';

		assert.deepEqual([...getCommentableLines(patch)], [1, 2, 3]);
	});

	test('a modified file exposes context and added lines only', () => {
		const patch = '@@ -10,3 +10,3 @@\n context\n-removed\n+added\n context';

		assert.deepEqual([...getCommentableLines(patch)], [10, 11, 12]);
		assert.equal(getCommentableLines(undefined).size, 0);
	});
});

describe('findVercelLinks', () => {
	const template = [
		'<!-- This should be a LINK (e.g. https://abc.vercel.app, https://abc.github.io) -->',
		'',
		'<!-- WEBSITE_PREVIEW_START -->',
		'https://my-site.vercel.app/',
		'<!-- WEBSITE_PREVIEW_END -->',
		'',
		'Also see https://other.vercel.app'
	].join('\n');

	test('reads only the preview section, ignoring the example in comments', () => {
		assert.deepEqual(findVercelLinks(template), ['https://my-site.vercel.app/']);
	});

	test('falls back to the whole body when the markers are gone', () => {
		assert.deepEqual(findVercelLinks('Preview: https://a.vercel.app and https://b.github.io'), [
			'https://a.vercel.app'
		]);
	});
});

describe('redirectsToVercelLogin', () => {
	const realFetch = globalThis.fetch;

	function fakeRedirects(locations: Record<string, string>): string[] {
		const requested: string[] = [];

		globalThis.fetch = (async (input: string | URL | Request) => {
			const url = String(input);
			const location = locations[url];

			requested.push(url);

			return new Response(null, {
				status: location ? 302 : 200,
				headers: location ? { location } : {}
			});
		}) as typeof fetch;

		return requested;
	}

	test('follows the Vercel Authentication chain to the login page', async () => {
		fakeRedirects({
			'https://locked.vercel.app/': 'https://vercel.com/sso-api?url=x',
			'https://vercel.com/sso-api?url=x': '/login?next=%2Fsso-api'
		});

		assert.equal(await redirectsToVercelLogin('https://locked.vercel.app/'), true);
		globalThis.fetch = realFetch;
	});

	test('a public preview is not flagged', async () => {
		fakeRedirects({});

		assert.equal(await redirectsToVercelLogin('https://open.vercel.app/'), false);
		globalThis.fetch = realFetch;
	});

	test('never follows a redirect off Vercel', async () => {
		const requested = fakeRedirects({
			'https://sneaky.vercel.app/': 'http://127.0.0.1:3101/login'
		});

		assert.equal(await redirectsToVercelLogin('https://sneaky.vercel.app/'), false);
		assert.deepEqual(requested, ['https://sneaky.vercel.app/']);
		globalThis.fetch = realFetch;
	});
});

function contextFor(repo: string, files: Partial<DomainFile>[]): RuleContext {
	return {
		pullRequest: { repo } as RuleContext['pullRequest'],
		files: files.map((file) => ({
			path: 'domains/x.json',
			status: 'added',
			patch: undefined,
			content: '',
			json: null,
			...file
		})),
		getEligibility: async () => ({
			eligible: true,
			explanation: ''
		})
	};
}

describe('Vercel verification records', () => {
	test('works out the _vercel file from any file of the registration', () => {
		const dev = 'is-a-dev/register';
		const bot = 'free-domains/is-a.bot';

		assert.equal(
			vercelFileFor('domains/_vercel.www.alice.json', dev),
			'domains/_vercel.alice.json'
		);
		assert.equal(
			vercelFileFor('domains/_vercel.alice.is-a.dev.json', dev),
			'domains/_vercel.alice.json'
		);
		assert.equal(
			vercelFileFor('domains/_vercel.alice.is-a.bot.json', bot),
			'domains/_vercel.alice.json'
		);
		assert.equal(vercelFileFor('domains/www.alice.json', dev), 'domains/_vercel.alice.json');
		assert.equal(vercelFileFor('domains/alice.json', dev), 'domains/_vercel.alice.json');
	});

	test('flags misnamed _vercel files only', async () => {
		const violations = await vercelFileNameRule.evaluate(
			contextFor('is-a-dev/register', [
				{ path: 'domains/_vercel.www.alice.json' },
				{ path: 'domains/_vercel.bob.json' },
				{ path: 'domains/www.carol.json' }
			])
		);

		assert.deepEqual(
			violations.map((violation) => violation.filePath),
			['domains/_vercel.www.alice.json']
		);
	});

	test('finds Vercel tokens in TXT strings and lists', () => {
		const token = 'vc-domain-verify=alice.is-a.dev,abc123';

		assert.deepEqual(findVercelTxt({ records: { TXT: token } }), [token]);
		assert.deepEqual(findVercelTxt({ records: { TXT: ['v=spf1 -all', token] } }), [token]);
		assert.deepEqual(findVercelTxt({ records: { TXT: 'v=spf1 -all' } }), []);
		assert.deepEqual(findVercelTxt(null), []);
	});

	test('flags a Vercel TXT in a domain file, but not in its _vercel file', async () => {
		const json = { records: { TXT: 'vc-domain-verify=alice.is-a.dev,abc123' } };

		const violations = await vercelTxtRecordRule.evaluate(
			contextFor('is-a-dev/register', [
				{
					path: 'domains/alice.json',
					json
				},
				{
					path: 'domains/_vercel.alice.json',
					json
				}
			])
		);

		assert.deepEqual(
			violations.map((violation) => violation.filePath),
			['domains/alice.json']
		);
		assert.ok(violations[0].reason.includes('domains/_vercel.alice.json'));
	});
});

describe('CNAME URLs and unsupported TLDs', () => {
	test('flags both web schemes in CNAME values, including malformed URLs', async () => {
		const violations = await cnameUrlRule.evaluate(
			contextFor('free-domains/is-a.bot', [
				{
					path: 'domains/http.json',
					json: { records: { CNAME: 'http://example.com/path' } }
				},
				{
					path: 'domains/https.json',
					json: { record: { cname: ' HTTPS:// ' } }
				},
				{
					path: 'domains/hostname.json',
					json: { records: { CNAME: 'example.com' } }
				}
			])
		);

		assert.deepEqual(
			violations.map((violation) => violation.filePath),
			['domains/http.json', 'domains/https.json']
		);
	});

	test('uses the final hostname label for both record types', async () => {
		const tlds = new Set(['tk']);

		assert.equal(
			findUnsupportedCname({ records: { CNAME: 'Me.Example.TK.' } }, [], tlds),
			'Me.Example.TK.'
		);
		assert.equal(
			findUnsupportedCname({ records: { CNAME: 'site.tk.example.com' } }, [], tlds),
			null
		);

		const violations = await unsupportedUrlTldRule.evaluate(
			contextFor('is-a-dev/register', [
				{
					path: 'domains/blocked.json',
					json: { record: { url: 'https://site.TK.:443/path' } }
				},
				{
					path: 'domains/allowed.json',
					json: { records: { URL: 'https://[email protected]/path.tk?target=site.tk' } }
				},
				{
					path: 'domains/malformed.json',
					json: { records: { URL: 'https://' } }
				}
			])
		);

		assert.equal(violations.length, 1);
		assert.equal(violations[0].filePath, 'domains/blocked.json');
		assert.equal(violations[0].ruleId, 'unsupportedUrlTld');
	});
});

describe('registration owner mismatch', () => {
	test('flags edits and renames with another owner', async () => {
		const anotherOwner = {
			owner: { username: 'alice' }
		};
		const context = contextFor('is-a-dev/register', [
			{
				path: 'domains/edited.json',
				status: 'modified',
				json: anotherOwner
			},
			{
				path: 'domains/renamed.json',
				status: 'renamed',
				json: anotherOwner
			},
			{
				path: 'domains/new.json',
				json: anotherOwner
			},
			{
				path: 'domains/own.json',
				status: 'modified',
				json: { owner: { username: ' CLove ' } }
			},
			{
				path: 'domains/no-owner.json',
				status: 'modified',
				json: { owner: {} }
			}
		]);
		context.pullRequest.author = 'clove';

		const violations = await ownerUsernameMismatchRule.evaluate(context);

		assert.deepEqual(
			violations.map((violation) => violation.filePath),
			['domains/edited.json', 'domains/renamed.json']
		);
		assert.ok(violations.every((violation) => violation.reason.includes('alice')));
	});
});