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-core.ts

395 lines · 13.4 KB · TypeScript
/**
 * GitHub @-mention detection and enforcement shared by every posting path.
 *
 * Mentions notify people, so posting helpers refuse bodies and titles that
 * contain mentions outside code unless the caller allows each one with
 * `allowedMentions`. Errors and results report counts only. They never
 * include the mentioned handles.
 */

export const MENTION_GUARD_ERROR_CODE = "GITHUB_MENTION_BLOCKED"

/** GitHub mention: start or non-word char, then @handle or @org/team. */
const MENTION_PATTERN =
  /(^|[^A-Za-z0-9_])@([A-Za-z0-9](?:-?[A-Za-z0-9]){0,38})(?![A-Za-z0-9])(?:\/([A-Za-z0-9](?:[A-Za-z0-9_-]*[A-Za-z0-9])?))?/g

const MUTATING_METHODS = new Set(["POST", "PATCH", "PUT"])

/** REST body fields that GitHub renders as Markdown (or shows as a title). */
const REST_TEXT_FIELDS = ["body", "title"] as const

/** GraphQL variable keys that never carry user-visible Markdown. */
const GRAPHQL_SKIP_KEY_PATTERN = /(^id$|^ids$|Ids?$|_ids?$|^contents$|^clientMutationId$|^expectedHeadOid$)/

export class GitHubMentionBlockedError extends Error {
  readonly code = MENTION_GUARD_ERROR_CODE
  /** Number of disallowed mentions found across the checked fields. */
  readonly mentionCount: number
  /** Names of the checked fields that contain disallowed mentions. */
  readonly fields: string[]
  /** True when the caller passed a non-empty `allowedMentions` list. */
  readonly usedAllowList: boolean

  constructor(options: { mentionCount: number; fields: string[]; usedAllowList: boolean }) {
    super(buildMentionErrorMessage(options))
    this.name = "GitHubMentionBlockedError"
    this.mentionCount = options.mentionCount
    this.fields = options.fields
    this.usedAllowList = options.usedAllowList
  }
}

export function buildMentionErrorMessage(options: {
  mentionCount: number
  fields: string[]
  usedAllowList: boolean
}): string {
  const count = options.mentionCount
  const noun = count === 1 ? "GitHub @-mention" : "GitHub @-mentions"
  const scope = options.usedAllowList
    ? count === 1
      ? " that is not in allowedMentions"
      : " that are not in allowedMentions"
    : ""
  const where = options.fields.length > 0 ? " in " + options.fields.join(", ") : ""
  return (
    "GitHub mention guard refused this post: found " +
    count +
    " " +
    noun +
    scope +
    where +
    " outside code. Mentions notify people, so posts refuse them by default. " +
    "Remove them, wrap them in backticks, or pass allowedMentions with the exact handles " +
    "(user or org/team) you intend to notify."
  )
}

/**
 * Normalize an allow list: trim, drop a leading @, lowercase. Throws when the
 * option is not an array of strings.
 */
export function normalizeAllowedMentions(allowedMentions: unknown): Set<string> {
  if (allowedMentions === undefined || allowedMentions === null) return new Set()
  if (!Array.isArray(allowedMentions)) {
    throw new TypeError("allowedMentions must be an array of GitHub handles (strings).")
  }
  const normalized = new Set<string>()
  for (const entry of allowedMentions) {
    if (typeof entry !== "string") {
      throw new TypeError("allowedMentions must be an array of GitHub handles (strings).")
    }
    const handle = entry.trim().replace(/^@+/, "").toLowerCase()
    if (handle) normalized.add(handle)
  }
  return normalized
}

/**
 * Replace fenced and indented code blocks with blank lines and inline code
 * spans with spaces, so only prose remains. Line structure is preserved.
 */
export function stripMarkdownCode(markdown: string): string {
  const lines = markdown.replace(/\r\n?/g, "\n").split("\n")
  const out: string[] = []
  let fence: { char: string; length: number } | null = null
  let previousBlank = true
  let previousIndentedCode = false
  let inList = false

  for (const line of lines) {
    if (fence) {
      const close = line.match(/^ {0,3}(`{3,}|~{3,})\s*$/)
      if (close && close[1]![0] === fence.char && close[1]!.length >= fence.length) {
        fence = null
      }
      out.push("")
      previousBlank = false
      previousIndentedCode = false
      continue
    }

    const open = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/)
    if (open && !(open[1]![0] === "`" && open[2]!.includes("`"))) {
      fence = { char: open[1]![0]!, length: open[1]!.length }
      out.push("")
      previousBlank = false
      previousIndentedCode = false
      continue
    }

    const blank = line.trim().length === 0
    const indented = /^(?: {4}|\t| {1,3}\t)/.test(line)
    if (!blank && indented && !inList && (previousBlank || previousIndentedCode)) {
      out.push("")
      previousBlank = false
      previousIndentedCode = true
      continue
    }

    if (!blank) {
      if (/^ {0,3}(?:[-*+]|\d{1,9}[.)])(?:\s|$)/.test(line)) {
        inList = true
      } else if (!indented && previousBlank) {
        inList = false
      }
    }

    // A blank line keeps an indented code block open.
    if (!(blank && previousIndentedCode)) previousIndentedCode = false
    previousBlank = blank
    out.push(line)
  }

  return stripInlineCode(out.join("\n"))
}

function stripInlineCode(text: string): string {
  let result = ""
  let index = 0
  while (index < text.length) {
    const char = text[index]
    if (char === "\\" && text[index + 1] === "`") {
      result += "\\`"
      index += 2
      continue
    }
    if (char !== "`") {
      result += char
      index += 1
      continue
    }
    let runEnd = index
    while (text[runEnd] === "`") runEnd += 1
    const runLength = runEnd - index
    const closeIndex = findClosingBacktickRun(text, runEnd, runLength)
    if (closeIndex === -1) {
      result += text.slice(index, runEnd)
      index = runEnd
      continue
    }
    const span = text.slice(index, closeIndex + runLength)
    result += span.replace(/[^\n]/g, " ")
    index = closeIndex + runLength
  }
  return result
}

function findClosingBacktickRun(text: string, from: number, length: number): number {
  let index = from
  while (index < text.length) {
    if (text[index] !== "`") {
      // Code spans do not cross a blank line (paragraph break).
      if (text[index] === "\n" && /^\n[ \t]*(\n|$)/.test(text.slice(index))) return -1
      index += 1
      continue
    }
    let runEnd = index
    while (text[runEnd] === "`") runEnd += 1
    if (runEnd - index === length) return index
    index = runEnd
  }
  return -1
}

/**
 * Return the normalized handles (lowercase, no @) mentioned outside code.
 * Internal use only: never put these values in errors or logs.
 */
export function findGitHubMentions(markdown: string): string[] {
  if (typeof markdown !== "string" || !markdown.includes("@")) return []
  const prose = stripMarkdownCode(markdown)
  const mentions: string[] = []
  for (const match of prose.matchAll(MENTION_PATTERN)) {
    const user = match[2]!.toLowerCase()
    const team = match[3]?.toLowerCase()
    mentions.push(team ? user + "/" + team : user)
  }
  return mentions
}

/** Count mentions outside code that are not on the allow list. */
export function countDisallowedMentions(markdown: string, allowedMentions?: unknown): number {
  const allowed = normalizeAllowedMentions(allowedMentions)
  return findGitHubMentions(markdown).filter((handle) => !allowed.has(handle)).length
}

export interface MentionCheckField {
  name: string
  value: unknown
}

export interface MentionCheckResult {
  ok: boolean
  /** Disallowed mentions across all checked fields. */
  mentionCount: number
  /** All mentions outside code, allowed or not. */
  totalMentionCount: number
  /** Field names that contain disallowed mentions. */
  fields: string[]
}

/** Check named text fields. Results carry counts and field names only. */
export function checkMentionFields(fields: MentionCheckField[], allowedMentions?: unknown): MentionCheckResult {
  const allowed = normalizeAllowedMentions(allowedMentions)
  let mentionCount = 0
  let totalMentionCount = 0
  const flagged: string[] = []
  for (const field of fields) {
    if (typeof field.value !== "string") continue
    const mentions = findGitHubMentions(field.value)
    totalMentionCount += mentions.length
    const disallowed = mentions.filter((handle) => !allowed.has(handle)).length
    if (disallowed > 0) {
      mentionCount += disallowed
      if (!flagged.includes(field.name)) flagged.push(field.name)
    }
  }
  return { ok: mentionCount === 0, mentionCount, totalMentionCount, fields: flagged }
}

/** Throw GitHubMentionBlockedError when any field has a disallowed mention. */
export function assertNoDisallowedMentions(fields: MentionCheckField[], allowedMentions?: unknown): void {
  const result = checkMentionFields(fields, allowedMentions)
  if (!result.ok) {
    throw new GitHubMentionBlockedError({
      mentionCount: result.mentionCount,
      fields: result.fields,
      usedAllowList: normalizeAllowedMentions(allowedMentions).size > 0,
    })
  }
}

/**
 * Collect the user-visible text fields a REST request would post.
 *
 * Covers every mutating (POST, PATCH, PUT) call: top-level `body` and
 * `title` (issues, PRs, comments, reviews, releases, discussions, edits),
 * inline review `comments[].body`, and review dismissal `message`. Requests to
 * `/graphql` go through the GraphQL collector instead.
 */
export function collectRestMentionFields(options: {
  method: string
  path: string
  body: unknown
}): MentionCheckField[] {
  const method = options.method.toUpperCase()
  if (!MUTATING_METHODS.has(method)) return []
  const pathname = toPathname(options.path)
  let body = options.body
  if (typeof body === "string") {
    try {
      body = JSON.parse(body)
    } catch {
      return [{ name: "body", value: body }]
    }
  }
  if (pathname === "/graphql") {
    if (!body || typeof body !== "object") return []
    const payload = body as { query?: unknown; variables?: unknown }
    return collectGraphqlMentionFields({
      query: typeof payload.query === "string" ? payload.query : "",
      variables: payload.variables,
    })
  }
  if (!body || typeof body !== "object" || Array.isArray(body)) return []
  const record = body as Record<string, unknown>
  const fields: MentionCheckField[] = []
  for (const key of REST_TEXT_FIELDS) {
    if (typeof record[key] === "string") fields.push({ name: key, value: record[key] })
  }
  if (Array.isArray(record.comments)) {
    record.comments.forEach((comment) => {
      if (comment && typeof comment === "object" && typeof (comment as { body?: unknown }).body === "string") {
        fields.push({ name: "comments[].body", value: (comment as { body: string }).body })
      }
    })
  }
  if (/\/dismissals\/?$/.test(pathname) && typeof record.message === "string") {
    fields.push({ name: "message", value: record.message })
  }
  return fields
}

/**
 * Collect text a GraphQL mutation would post: every string literal in the
 * document plus string variables (any depth), skipping id-like and file
 * content keys. Queries (non-mutations) return no fields.
 */
export function collectGraphqlMentionFields(options: { query: string; variables?: unknown }): MentionCheckField[] {
  const { strings, stripped } = extractGraphqlStrings(options.query)
  if (!/(^|[\s{}])mutation\b/.test(stripped)) return []
  const fields: MentionCheckField[] = strings.map((value) => ({ name: "query", value }))
  collectVariableStrings(options.variables, "variables", fields, 0)
  return fields
}

function collectVariableStrings(value: unknown, name: string, fields: MentionCheckField[], depth: number) {
  if (depth > 20) return
  if (typeof value === "string") {
    fields.push({ name, value })
    return
  }
  if (Array.isArray(value)) {
    for (const item of value) collectVariableStrings(item, name, fields, depth + 1)
    return
  }
  if (value && typeof value === "object") {
    for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
      if (GRAPHQL_SKIP_KEY_PATTERN.test(key)) continue
      collectVariableStrings(child, "variables." + key, fields, depth + 1)
    }
  }
}

/** Pull string literals out of a GraphQL document and drop comments. */
function extractGraphqlStrings(document: string): { strings: string[]; stripped: string } {
  const strings: string[] = []
  let stripped = ""
  let index = 0
  while (index < document.length) {
    const char = document[index]
    if (char === "#") {
      while (index < document.length && document[index] !== "\n") index += 1
      continue
    }
    if (document.startsWith('"""', index)) {
      const end = document.indexOf('"""', index + 3)
      const stop = end === -1 ? document.length : end
      strings.push(document.slice(index + 3, stop))
      stripped += " "
      index = end === -1 ? document.length : end + 3
      continue
    }
    if (char === '"') {
      let value = ""
      index += 1
      while (index < document.length && document[index] !== '"' && document[index] !== "\n") {
        if (document[index] === "\\" && index + 1 < document.length) {
          const next = document[index + 1]!
          value += next === "n" ? "\n" : next
          index += 2
          continue
        }
        value += document[index]
        index += 1
      }
      index += 1
      strings.push(value)
      stripped += " "
      continue
    }
    stripped += char
    index += 1
  }
  return { strings, stripped }
}

function toPathname(path: string): string {
  let pathname = path
  if (pathname.startsWith("https://api.github.com")) pathname = pathname.slice("https://api.github.com".length)
  const queryIndex = pathname.search(/[?#]/)
  if (queryIndex !== -1) pathname = pathname.slice(0, queryIndex)
  if (!pathname.startsWith("/")) pathname = "/" + pathname
  return pathname.replace(/\/+$/, "") || "/"
}