Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kentcdodds/github

GitHub REST, GraphQL, and pull request helpers for Kody agents.

FollowFork

Files

mention-guard.node.test.ts

206 lines · 7.8 KB · TypeScript
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'

import {
	GitHubMentionBlockedError,
	assertNoDisallowedMentions,
	collectGraphqlMentionFields,
	collectRestMentionFields,
	countDisallowedMentions,
	findGitHubMentions,
	stripMarkdownCode,
} from './mention-guard-core.ts'
import checkMentions from './mention-guard.ts'
import { request } from './core.ts'

const handle = 'example-handle'

describe('findGitHubMentions', () => {
	it('finds user mentions at start, after spaces, and after punctuation', () => {
		assert.equal(findGitHubMentions(`@${handle} hi`).length, 1)
		assert.equal(findGitHubMentions(`hi @${handle}.`).length, 1)
		assert.equal(findGitHubMentions(`(cc @a, @b-c)\n@d`).length, 3)
	})

	it('finds org/team mentions as one mention', () => {
		assert.deepEqual(findGitHubMentions('ping @Some-Org/core_team please'), ['some-org/core_team'])
	})

	it('ignores email addresses and word-prefixed @', () => {
		assert.equal(findGitHubMentions('mail foo@bar.com or a_@b').length, 0)
	})

	it('follows handle rules: alphanumeric, single hyphens, max 39 chars', () => {
		assert.equal(findGitHubMentions('@-nope').length, 0)
		assert.equal(findGitHubMentions('@' + 'a'.repeat(39)).length, 1)
		assert.equal(findGitHubMentions('@' + 'a'.repeat(40)).length, 0)
		assert.deepEqual(findGitHubMentions('@ab--cd'), ['ab'])
		assert.deepEqual(findGitHubMentions('@ab-'), ['ab'])
	})

	it('ignores mentions in inline code spans', () => {
		assert.equal(findGitHubMentions('use `@scope/pkg` and ``x @y` z``').length, 0)
		assert.equal(findGitHubMentions('unclosed ` @real').length, 1)
		assert.equal(findGitHubMentions('escaped \\`@real\\`').length, 1)
	})

	it('ignores mentions in fenced code blocks (backticks and tildes)', () => {
		const body = ['before', '```js', '@inside', '```', '~~~~', '@also', '~~~~', 'after @outside'].join('\n')
		assert.deepEqual(findGitHubMentions(body), ['outside'])
	})

	it('treats an unclosed fence as code to the end', () => {
		assert.equal(findGitHubMentions('```\n@inside\nmore').length, 0)
	})

	it('ignores mentions in indented code blocks but not in lists or lazy lines', () => {
		assert.equal(findGitHubMentions('para\n\n    @inside\n\n    @inside2\n\ndone').length, 0)
		assert.equal(findGitHubMentions('para\n    @lazy-continuation').length, 1)
		assert.equal(findGitHubMentions('- item\n\n    @nested-list-content').length, 1)
	})

	it('stripMarkdownCode keeps line count', () => {
		const body = 'a\n```\nb\n```\nc'
		assert.equal(stripMarkdownCode(body).split('\n').length, 5)
	})
})

describe('countDisallowedMentions and allow list', () => {
	it('allows listed handles case-insensitively with or without @', () => {
		assert.equal(countDisallowedMentions('@Alice and @bob', ['alice', '@BOB']), 0)
		assert.equal(countDisallowedMentions('@Alice and @bob and @carol', ['ALICE']), 2)
	})

	it('matches team handles as org/team only', () => {
		assert.equal(countDisallowedMentions('@org/team', ['org/team']), 0)
		assert.equal(countDisallowedMentions('@org/team', ['org']), 1)
		assert.equal(countDisallowedMentions('@Org/Team', ['@org/TEAM']), 0)
	})

	it('rejects a non-array allow list', () => {
		assert.throws(() => countDisallowedMentions('@a', 'a' as unknown as string[]), TypeError)
	})
})

describe('assertNoDisallowedMentions error', () => {
	it('names the count and allowedMentions but never the handle', () => {
		const error = (() => {
			try {
				assertNoDisallowedMentions([{ name: 'body', value: `hi @${handle} and @${handle}-two` }])
			} catch (caught) {
				return caught
			}
			return null
		})()
		assert.ok(error instanceof GitHubMentionBlockedError)
		assert.equal(error.mentionCount, 2)
		assert.equal(error.code, 'GITHUB_MENTION_BLOCKED')
		assert.match(error.message, /found 2 GitHub @-mentions/)
		assert.match(error.message, /allowedMentions/)
		assert.ok(!error.message.toLowerCase().includes(handle))
		assert.ok(!JSON.stringify({ ...error, message: error.message }).toLowerCase().includes(handle))
		assert.ok(!error.message.includes('\u2014'))
	})

	it('reports only disallowed count when an allow list is used', () => {
		assert.throws(
			() => assertNoDisallowedMentions([{ name: 'body', value: '@a @b @c' }], ['a']),
			(error: unknown) =>
				error instanceof GitHubMentionBlockedError &&
				error.mentionCount === 2 &&
				/found 2 GitHub @-mentions that are not in allowedMentions/.test(error.message) &&
				!/@a\b|@b\b|@c\b/.test(error.message.replace('@-mention', '')),
		)
	})

	it('uses singular wording for one mention', () => {
		assert.throws(
			() => assertNoDisallowedMentions([{ name: 'title', value: 'fix for @a' }]),
			/found 1 GitHub @-mention in title outside code/,
		)
	})
})

describe('collectRestMentionFields', () => {
	it('ignores GET and DELETE', () => {
		assert.deepEqual(collectRestMentionFields({ method: 'GET', path: '/x', body: { body: '@a' } }), [])
		assert.deepEqual(collectRestMentionFields({ method: 'DELETE', path: '/x', body: { body: '@a' } }), [])
	})

	it('collects body, title, review comments, and dismissal message', () => {
		const fields = collectRestMentionFields({
			method: 'post',
			path: '/repos/o/r/pulls/1/reviews',
			body: { body: 'b', title: 't', comments: [{ path: 'x', body: 'c' }] },
		})
		assert.deepEqual(fields.map((field) => field.name), ['body', 'title', 'comments[].body'])
		const dismissal = collectRestMentionFields({
			method: 'PUT',
			path: 'https://api.github.com/repos/o/r/pulls/1/reviews/2/dismissals',
			body: JSON.stringify({ message: 'm' }),
		})
		assert.deepEqual(dismissal.map((field) => field.name), ['message'])
	})

	it('routes /graphql passthrough bodies through the GraphQL collector', () => {
		const fields = collectRestMentionFields({
			method: 'POST',
			path: '/graphql',
			body: { query: 'mutation($b: String!) { addComment(input: {subjectId: "X", body: $b}) { clientMutationId } }', variables: { b: '@a' } },
		})
		assert.equal(fields.some((field) => field.value === '@a'), true)
	})
})

describe('collectGraphqlMentionFields', () => {
	it('skips queries and ignores directives', () => {
		assert.deepEqual(collectGraphqlMentionFields({ query: 'query { viewer { login @include(if: true) } }' }), [])
	})

	it('checks mutation literals and variables but not ids', () => {
		const fields = collectGraphqlMentionFields({
			query: 'mutation { addComment(input: {subjectId: "abc", body: "hi @a"}) { clientMutationId } }',
			variables: { input: { subjectId: '@id-like', body: 'x' } },
		})
		const values = fields.map((field) => field.value)
		assert.ok(values.includes('hi @a'))
		assert.ok(values.includes('x'))
		assert.ok(!values.includes('@id-like'))
	})
})

describe('request enforcement', () => {
	it('throws before any network call and passes when allowed', async () => {
		let calls = 0
		;(globalThis as { __kodyFetch?: unknown }).__kodyFetch = async () => {
			calls += 1
			return new Response('{"id":1}', { status: 201, headers: { 'content-type': 'application/json' } })
		}
		await assert.rejects(
			request({ path: '/repos/o/r/issues/1/comments', body: { body: 'thanks @a' } }),
			GitHubMentionBlockedError,
		)
		await assert.rejects(
			request({ method: 'PATCH', path: '/repos/o/r/pulls/1', body: { title: '@a fix', body: 'ok' } }),
			GitHubMentionBlockedError,
		)
		assert.equal(calls, 0)
		const ok = await request({
			path: '/repos/o/r/issues/1/comments',
			body: { body: 'thanks @A, see `@scope/pkg` and me@example.com' },
			allowedMentions: ['a'],
		})
		assert.equal(ok.status, 201)
		const read = await request({ path: '/repos/o/r/issues/1', query: { q: '@a' } })
		assert.equal(read.ok, true)
		assert.equal(calls, 2)
	})
})

describe('mention-guard export', () => {
	it('returns counts and field names only', () => {
		const result = checkMentions({ title: 'x', body: 'hi @a and `@b`' })
		assert.deepEqual(result, { ok: false, mentionCount: 1, totalMentionCount: 1, fields: ['body'] })
		assert.equal(checkMentions({ body: 'hi @a', allowedMentions: ['a'] }).ok, true)
	})
})