{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "secret-paste-guard",
  "title": "Secret Paste Guard",
  "description": "Wraps a text field and scans its value for known key formats (AWS, GitHub, Stripe, Slack, OpenAI, Anthropic, Google, JWTs, private keys) plus long high-entropy strings, offering Redact (keeps the last 4) or Keep.",
  "dependencies": [
    "lucide-react"
  ],
  "files": [
    {
      "path": "registry/default/secret-paste-guard/secret-paste-guard.tsx",
      "content": "\"use client\"\r\n\r\n// Bollard UI — secret-paste-guard · MIT licence · https://bollard-ui.vercel.app/components/secret-paste-guard\r\n\r\nimport * as React from \"react\"\r\nimport { KeyRound } from \"lucide-react\"\r\n\r\nimport { cn } from \"@/lib/utils\"\r\n\r\nexport interface SecretMatch {\r\n  /** Human name, e.g. \"Stripe live secret key\". */\r\n  label: string\r\n  /** The matched text. */\r\n  value: string\r\n  start: number\r\n  end: number\r\n  /** True for the generic high-entropy rule, which is a guess rather than a known format. */\r\n  heuristic: boolean\r\n}\r\n\r\nconst RULES: [string, RegExp][] = [\r\n  [\"Private key\", /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----[\\s\\S]*?(?:-----END (?:[A-Z0-9]+ )*PRIVATE KEY-----|$)/g],\r\n  [\"AWS access key\", /\\b(?:AKIA|ASIA)[0-9A-Z]{16}\\b/g],\r\n  [\"GitHub token\", /\\bgh[pousr]_[A-Za-z0-9]{36,}\\b/g],\r\n  [\"GitHub fine-grained token\", /\\bgithub_pat_[A-Za-z0-9_]{22,}/g],\r\n  [\"Stripe live secret key\", /\\bsk_live_[A-Za-z0-9]{16,}/g],\r\n  [\"Stripe restricted key\", /\\brk_live_[A-Za-z0-9]{16,}/g],\r\n  [\"Slack token\", /\\bxox[abprs]-[A-Za-z0-9-]{10,}/g],\r\n  [\"Anthropic API key\", /\\bsk-ant-[A-Za-z0-9_-]{20,}/g],\r\n  [\"OpenAI API key\", /\\bsk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{20,}/g],\r\n  [\"Google API key\", /\\bAIza[0-9A-Za-z_-]{35}/g],\r\n  [\"JSON Web Token\", /\\beyJ[A-Za-z0-9_-]{8,}\\.eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{10,}/g],\r\n]\r\n\r\n/** Shannon entropy in bits per character. Random base64 sits near 5-6; English words near 3-4. */\r\nexport function shannonEntropy(text: string) {\r\n  const counts = new Map<string, number>()\r\n  for (const ch of text) counts.set(ch, (counts.get(ch) ?? 0) + 1)\r\n  let bits = 0\r\n  for (const n of counts.values()) bits -= (n / text.length) * Math.log2(n / text.length)\r\n  return bits\r\n}\r\n\r\n/**\r\n * Finds likely secrets in text: known token formats first, then long\r\n * mixed-case-and-digit strings with high Shannon entropy. Matches never overlap.\r\n */\r\nexport function detectSecrets(text: string): SecretMatch[] {\r\n  const found: SecretMatch[] = []\r\n  const overlaps = (start: number, end: number) => found.some((m) => start < m.end && end > m.start)\r\n  for (const [label, pattern] of RULES) {\r\n    for (const m of text.matchAll(pattern)) {\r\n      const end = m.index + m[0].length\r\n      if (!overlaps(m.index, end)) found.push({ label, value: m[0], start: m.index, end, heuristic: false })\r\n    }\r\n  }\r\n  const urls = Array.from(text.matchAll(/https?:\\/\\/\\S+/g), (m) => [m.index, m.index + m[0].length])\r\n  for (const m of text.matchAll(/[A-Za-z0-9+/=_-]{32,}/g)) {\r\n    const token = m[0]\r\n    const end = m.index + token.length\r\n    // A URL path like /assets/SomeLongName isn't a secret, but a token in its query string can be.\r\n    const isPath = token.includes(\"/\") && urls.some(([s, e]) => m.index >= s && end <= e)\r\n    const mixed = /[a-z]/.test(token) && /[A-Z]/.test(token) && /\\d/.test(token)\r\n    if (mixed && !isPath && shannonEntropy(token) >= 4.2 && !overlaps(m.index, end))\r\n      found.push({ label: \"High-entropy string\", value: token, start: m.index, end, heuristic: true })\r\n  }\r\n  return found.sort((a, b) => a.start - b.start)\r\n}\r\n\r\n/** \"•••\" plus the last 4 characters, so people can still tell which key it was. */\r\nexport function redactSecret(match: SecretMatch) {\r\n  return match.label === \"Private key\" ? \"••• [private key removed]\" : `•••${match.value.slice(-4)}`\r\n}\r\n\r\nexport interface SecretPasteGuardProps extends Omit<React.ComponentProps<\"div\">, \"onChange\"> {\r\n  /** The field's value. The guard scans it whether it was typed or pasted. */\r\n  value: string\r\n  /** Called with the redacted text when the user chooses Redact. */\r\n  onValueChange: (value: string) => void\r\n  /** Your input, textarea or chat box, controlled by the same value. */\r\n  children: React.ReactNode\r\n  /** Notified whenever the set of unresolved secrets changes, e.g. to hold a Send button. */\r\n  onDetect?: (matches: SecretMatch[]) => void\r\n  /** Label of the button that replaces every secret with its last 4 characters. */\r\n  redactLabel?: string\r\n  /** Label of the button that dismisses the warning for these values. */\r\n  keepLabel?: string\r\n}\r\n\r\nconst preview = (m: SecretMatch) =>\r\n  m.label === \"Private key\" ? \"BEGIN … PRIVATE KEY\" : `${m.value.slice(0, Math.min(8, Math.floor(m.value.length / 4)))}…${m.value.slice(-4)}`\r\n\r\n/**\r\n * Wraps any text field and warns when its content looks like a credential\r\n * (cloud, Git, payment and AI keys, JWTs, private keys, or random-looking\r\n * strings) before it is sent or saved. One tap redacts, keeping the last 4.\r\n */\r\nexport function SecretPasteGuard({\r\n  value,\r\n  onValueChange,\r\n  children,\r\n  onDetect,\r\n  redactLabel = \"Redact\",\r\n  keepLabel = \"Keep\",\r\n  className,\r\n  onPasteCapture,\r\n  onKeyDownCapture,\r\n  ...props\r\n}: SecretPasteGuardProps) {\r\n  const [kept, setKept] = React.useState<ReadonlySet<string>>(() => new Set())\r\n  const [pasted, setPasted] = React.useState(false)\r\n  const rootRef = React.useRef<HTMLDivElement>(null)\r\n  const lastSignature = React.useRef<string>(undefined)\r\n  const matches = React.useMemo(() => detectSecrets(value).filter((m) => !kept.has(m.value)), [value, kept])\r\n\r\n  // Report only when the set of secrets changes, not on every keystroke.\r\n  React.useEffect(() => {\r\n    const signature = matches.map((m) => m.value).join(\"\\n\")\r\n    if (signature === lastSignature.current) return\r\n    lastSignature.current = signature\r\n    onDetect?.(matches)\r\n  })\r\n\r\n  // The warning (and the button just pressed) unmounts on resolve, so put the caret back in the field.\r\n  const refocusField = () =>\r\n    requestAnimationFrame(() => rootRef.current?.querySelector<HTMLElement>(\"textarea, input, [contenteditable=true]\")?.focus())\r\n\r\n  const redact = () => {\r\n    let next = value\r\n    for (const m of [...matches].reverse()) next = next.slice(0, m.start) + redactSecret(m) + next.slice(m.end)\r\n    onValueChange(next)\r\n    refocusField()\r\n  }\r\n  const keep = () => {\r\n    setKept((prev) => new Set([...prev, ...matches.map((m) => m.value)]))\r\n    refocusField()\r\n  }\r\n\r\n  const button =\r\n    \"inline-flex h-8 items-center rounded-md px-3 text-sm font-medium outline-none transition-colors focus-visible:ring-[3px] focus-visible:ring-ring/50\"\r\n  const allHeuristic = matches.every((m) => m.heuristic)\r\n\r\n  return (\r\n    <div\r\n      ref={rootRef}\r\n      data-slot=\"secret-paste-guard\"\r\n      className={cn(\"w-full\", className)}\r\n      onPasteCapture={(event) => {\r\n        onPasteCapture?.(event)\r\n        setPasted(true)\r\n      }}\r\n      onKeyDownCapture={(event) => {\r\n        onKeyDownCapture?.(event)\r\n        if (!event.metaKey && !event.ctrlKey) setPasted(false)\r\n      }}\r\n      {...props}\r\n    >\r\n      {children}\r\n      <div aria-live=\"polite\">\r\n        {matches.length > 0 && (\r\n          <div className=\"mt-1.5 rounded-lg border border-amber-300 bg-amber-50 px-3 py-2.5 text-sm dark:border-amber-800 dark:bg-amber-950/40\">\r\n            <div className=\"flex items-start gap-2\">\r\n              <KeyRound className=\"mt-0.5 size-4 shrink-0 text-amber-700 dark:text-amber-400\" aria-hidden />\r\n              <div className=\"min-w-0 flex-1 space-y-1.5\">\r\n                <p className=\"font-medium text-amber-900 dark:text-amber-100\">\r\n                  {pasted ? \"You pasted\" : \"This contains\"}{\" \"}\r\n                  {allHeuristic ? \"something that looks like a secret\" : matches.length === 1 ? \"a secret\" : `${matches.length} secrets`}\r\n                </p>\r\n                <ul className=\"space-y-0.5\">\r\n                  {matches.map((m) => (\r\n                    <li key={`${m.start}-${m.value}`} className=\"flex flex-wrap items-baseline gap-x-2 text-xs text-amber-900/80 dark:text-amber-100/80\">\r\n                      <span>{m.label}</span>\r\n                      <code className=\"rounded bg-background/70 px-1 font-mono break-all\">{preview(m)}</code>\r\n                      {m.heuristic && <span className=\"opacity-70\">{shannonEntropy(m.value).toFixed(1)} bits/char</span>}\r\n                    </li>\r\n                  ))}\r\n                </ul>\r\n                <div className=\"flex gap-2 pt-0.5\">\r\n                  <button type=\"button\" onClick={redact} className={cn(button, \"bg-primary text-primary-foreground hover:bg-primary/90\")}>\r\n                    {redactLabel}\r\n                  </button>\r\n                  <button type=\"button\" onClick={keep} className={cn(button, \"border bg-background hover:bg-accent\")}>\r\n                    {keepLabel}\r\n                  </button>\r\n                </div>\r\n              </div>\r\n            </div>\r\n          </div>\r\n        )}\r\n      </div>\r\n    </div>\r\n  )\r\n}\r\n",
      "type": "registry:ui",
      "target": "@ui/secret-paste-guard.tsx"
    }
  ],
  "meta": {
    "stops": "Helps catch an API key pasted into a chat",
    "mistakes": [
      "users paste api keys",
      "secret leaked in message",
      "token pasted by mistake",
      "jwt pasted in support chat",
      "private key in form"
    ],
    "aliases": [
      "api key",
      "token",
      "jwt",
      "secret",
      "redact",
      "support chat",
      "paste",
      "credentials"
    ],
    "flows": [
      "messaging",
      "devtools"
    ],
    "fields": [
      "secret"
    ],
    "summary": "Spots API keys, tokens and private keys as they're pasted or typed into a field and offers one-tap Redact before they're sent.",
    "server": "Scan again server-side before storing or forwarding text, and redact secrets from logs, analytics and error reports.",
    "catches": [
      "Known formats: private key blocks, AWS access keys, GitHub tokens, Stripe live/restricted keys, Slack, OpenAI, Anthropic and Google API keys, JWTs",
      "Long mixed-case-and-digit strings with high Shannon entropy (marked as a guess)",
      "Typed and pasted text alike",
      "URL paths are not mistaken for secrets, but tokens in query strings can be"
    ],
    "limits": [
      "Pattern and entropy based: new or unusual formats are missed, and random IDs can be flagged",
      "Scans in the browser only; it does not stop a submit, so a user can Keep and send",
      "onDetect receives the matched text, so never log or send those matches as-is"
    ],
    "a11y": [
      "Warning renders in a polite live region",
      "Redact and Keep are labelled buttons",
      "After either choice, focus returns to the wrapped field"
    ],
    "usage": "import { SecretPasteGuard } from \"@/components/ui/secret-paste-guard\"",
    "runtimeDependencies": [
      "lucide-react"
    ],
    "zeroRuntimeDependencies": false
  },
  "docs": "https://bollard-ui.vercel.app/components/secret-paste-guard",
  "categories": [
    "Sharing, sending and paying"
  ],
  "type": "registry:ui"
}
