react-smart-copy 1.20.0 → 1.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secrets.cjs","names":["copyFailure","asTextField","insertText"],"sources":["../src/secrets/checks.ts","../src/secrets/rules.ts","../src/secrets/types.ts","../src/secrets/scan.ts","../src/secrets/redact.ts","../src/secrets/paste.ts"],"sourcesContent":["/** Checks that tell real secrets from look-alikes: checksums, structure and randomness. */\n\n/** The Luhn checksum of card numbers. `digits` holds only digits. */\nexport function luhn(digits: string): boolean {\n let sum = 0;\n for (let index = 0; index < digits.length; index += 1) {\n let digit = digits.charCodeAt(digits.length - 1 - index) - 48;\n if (index % 2 === 1) {\n digit *= 2;\n if (digit > 9) digit -= 9;\n }\n sum += digit;\n }\n return sum % 10 === 0;\n}\n\n/** Card brands by their number ranges (IIN) and lengths. */\nconst BRANDS: readonly { readonly prefix: RegExp; readonly lengths: readonly number[] }[] = [\n { prefix: /^4/, lengths: [13, 16, 19] }, // Visa\n { prefix: /^(?:5[1-5]|222[1-9]|22[3-9]\\d|2[3-6]\\d\\d|27[01]\\d|2720)/, lengths: [16] }, // Mastercard\n { prefix: /^3[47]/, lengths: [15] }, // American Express\n { prefix: /^(?:6011|65|64[4-9])/, lengths: [16, 17, 18, 19] }, // Discover\n { prefix: /^35(?:2[89]|[3-8]\\d)/, lengths: [16, 17, 18, 19] }, // JCB\n { prefix: /^3(?:0[0-5]|[689])/, lengths: [14, 15, 16, 17, 18, 19] }, // Diners Club\n { prefix: /^62/, lengths: [16, 17, 18, 19] }, // UnionPay\n];\n\n/**\n * Whether `candidate` is a card number: a known brand's range and length, a valid Luhn\n * checksum, and separators (spaces or dashes) used the way cards print them: none, or one\n * kind in groups of 4 (Amex: 4-6-5).\n */\nexport function isCardNumber(candidate: string): boolean {\n const digits = candidate.replace(/[ -]/g, '');\n const separators = new Set(candidate.replace(/\\d/g, ''));\n if (separators.size > 1) return false;\n if (separators.size === 1) {\n const groups = candidate.split(/[ -]/).map((group) => group.length);\n const fours = groups.slice(0, -1).every((length) => length === 4) && (groups[groups.length - 1] as number) <= 4;\n const amex = groups.join('-') === '4-6-5';\n if (!fours && !amex) return false;\n }\n if (/^(\\d)\\1+$/.test(digits)) return false;\n return BRANDS.some((brand) => brand.prefix.test(digits) && brand.lengths.includes(digits.length)) && luhn(digits);\n}\n\n/** IBAN lengths by country (ISO 13616 registry), for the countries that use one. */\nconst IBAN_LENGTHS: Readonly<Record<string, number>> = {\n AD: 24, AE: 23, AL: 28, AT: 20, AZ: 28, BA: 20, BE: 16, BG: 22, BH: 22, BR: 29, BY: 28, CH: 21, CR: 22, CY: 28, CZ: 24,\n DE: 22, DK: 18, DO: 28, EE: 20, EG: 29, ES: 24, FI: 18, FO: 18, FR: 27, GB: 22, GE: 22, GI: 23, GL: 18, GR: 27, GT: 28,\n HR: 21, HU: 28, IE: 22, IL: 23, IQ: 23, IS: 26, IT: 27, JO: 30, KW: 30, KZ: 20, LB: 28, LC: 32, LI: 21, LT: 20, LU: 20,\n LV: 21, MC: 27, MD: 24, ME: 22, MK: 19, MR: 27, MT: 31, MU: 30, NL: 18, NO: 15, PK: 24, PL: 28, PS: 29, PT: 25, QA: 29,\n RO: 24, RS: 22, SA: 24, SC: 31, SE: 24, SI: 19, SK: 24, SM: 27, ST: 25, SV: 28, TL: 23, TN: 24, TR: 26, UA: 29, VA: 22,\n VG: 24, XK: 20,\n};\n\n/** Whether `candidate` (spaces allowed) is an IBAN: its country's length and a valid mod-97 checksum. */\nexport function isIban(candidate: string): boolean {\n const iban = candidate.replace(/ /g, '');\n if (IBAN_LENGTHS[iban.slice(0, 2)] !== iban.length) return false;\n const rearranged = iban.slice(4) + iban.slice(0, 4);\n let remainder = 0;\n for (const char of rearranged) {\n const code = char.charCodeAt(0);\n // Letters count as two digits (A = 10 ... Z = 35); digits as themselves.\n const value = code >= 65 ? code - 55 : code - 48;\n remainder = (value > 9 ? remainder * 100 + value : remainder * 10 + value) % 97;\n }\n return remainder === 1;\n}\n\n/** Shannon entropy of `text`, in bits per character. */\nexport function entropy(text: string): number {\n const counts = new Map<string, number>();\n for (const char of text) counts.set(char, (counts.get(char) ?? 0) + 1);\n let bits = 0;\n for (const count of counts.values()) {\n const p = count / text.length;\n bits -= p * Math.log2(p);\n }\n return bits;\n}\n\n/** Values that stand in for a secret in examples and templates, never a secret themselves. */\nconst PLACEHOLDER =\n /^(?:x+|\\*+|\\.+|-+|_+|#+|0+|<[^>]*>|\\[[^\\]]*\\]|\\$\\{[^}]*\\}|\\{\\{[^}]*\\}\\}|%[^%]*%|\\$[A-Z_][A-Z0-9_]*|your[_-]?[\\w-]*|my[_-][\\w-]*|change[_-]?me|example[\\w-]*|sample[\\w-]*|dummy[\\w-]*|fake[\\w-]*|placeholder[\\w-]*|redacted|null|none|undefined)$/i;\n\n/** A reference to another value, not a value: `process.env.TOKEN`, `config.api.key`. */\nconst REFERENCE = /^[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)+$/;\n\n/** Whether `value` looks like a real secret: random enough, and not a placeholder or a reference. */\nexport function looksSecret(value: string, minEntropy: number): boolean {\n return !PLACEHOLDER.test(value) && !REFERENCE.test(value) && entropy(value) >= minEntropy;\n}\n\n/** Whether the first part of a JWT decodes to a JSON header with an algorithm. */\nexport function isJwtHeader(part: string): boolean {\n if (typeof atob !== 'function') return true;\n try {\n const base64 = part.replace(/-/g, '+').replace(/_/g, '/');\n const header: unknown = JSON.parse(atob(base64 + '='.repeat((4 - (base64.length % 4)) % 4)));\n return typeof header === 'object' && header !== null && typeof (header as { alg?: unknown }).alg === 'string';\n } catch {\n return false;\n }\n}\n","import { isCardNumber, isIban, isJwtHeader, looksSecret } from './checks';\nimport type { SecretConfidence, SecretKind } from './types';\n\n/** A rule's verdict on a candidate: how sure it is, and how much of the candidate is the secret. */\nexport interface Verdict {\n readonly confidence: SecretConfidence;\n /** Characters of the candidate that are the secret (a card number followed by more digits). */\n readonly length: number;\n /** The kind, when one pattern finds two (an AWS secret key, or a generic secret). */\n readonly kind?: SecretKind;\n}\n\n/**\n * One way to find a kind of secret. Every pattern is global and linear: bounded repeats,\n * no nested quantifiers, no lookbehind (older Safari). Group `group` is the secret, and it\n * ends the match: whatever follows is only looked ahead at, so the secret's start is the\n * match's end minus its length. The scan goes on right after each secret found.\n */\nexport interface Rule {\n readonly kind: SecretKind;\n readonly pattern: RegExp;\n readonly group: number;\n /** Characters of the secret a preview may show at the start: its known prefix. */\n readonly keep: number | ((secret: string) => number);\n /** Whether a preview may show the last 4 characters (never for passwords). */\n readonly tail: boolean;\n readonly check: (secret: string, match: RegExpMatchArray) => Verdict | null;\n /**\n * When `check` turns a match down, look again from the character after its start: a short\n * candidate (a card, an IBAN) can run into the next one. Other rules go on after the match.\n */\n readonly retry?: boolean;\n}\n\nconst high = (secret: string): Verdict => ({ confidence: 'high', length: secret.length });\nconst medium = (secret: string): Verdict => ({ confidence: 'medium', length: secret.length });\n\n/** Start of a token: the start of the text, or a character that can't be part of one. */\nconst B = '(^|[^A-Za-z0-9_])';\n/** After a token: nothing that could continue it. */\nconst E = '(?![A-Za-z0-9_])';\n\nconst token = (kind: SecretKind, body: string, keep: Rule['keep'], options: { readonly end?: string; readonly flags?: string; readonly confidence?: SecretConfidence } = {}): Rule => ({\n kind,\n pattern: new RegExp(`${B}(${body})${options.end ?? E}`, `g${options.flags ?? ''}`),\n group: 2,\n keep,\n tail: true,\n check: options.confidence === 'medium' ? medium : high,\n});\n\n/** A name, an assignment (`=`, `:`, `=>`, `:=`) and a value: `API_KEY=\"...\"`, `\"password\": \"...\"`. */\nconst ASSIGNMENT = /(^|[^A-Za-z0-9_])([\"']?([A-Za-z_][A-Za-z0-9_.-]{0,63})[\"']?\\s{0,8}(?:=>|:=|[:=])\\s{0,8}[\"'`]?)([^\\s\"'`,;()[\\]{}<>]{8,200})/g;\n\n/** Names that hold secrets, at the end of the name: `password`, `GITHUB_TOKEN`, `db.apiKey`. */\nconst SECRET_NAME = /(?:pass(?:word|wd|phrase)?|pwd|secret|token|api[_.-]?key|access[_.-]?key|private[_.-]?key|auth[_.-]?key|credentials?|client[_.-]?secret|signing[_.-]?key)$/i;\n\n/**\n * A card number, grouped as cards print it or not. The last group is tried without itself\n * too: what follows a card is often more digits (`4242 4242 4242 4242 12/26`, a date).\n */\nfunction card(candidate: string): Verdict | null {\n if (isCardNumber(candidate)) return { confidence: /[ -]/.test(candidate) ? 'high' : 'medium', length: candidate.length };\n const cut = candidate.search(/[ -]\\d{1,4}$/);\n return cut !== -1 && isCardNumber(candidate.slice(0, cut)) ? { confidence: 'high', length: cut } : null;\n}\n\n/** An IBAN, cut to its country's length: what follows (a BIC, a word) is not part of it. */\nfunction iban(candidate: string): Verdict | null {\n let letters = 0;\n for (let index = 0; index < candidate.length; index += 1) {\n if (candidate[index] !== ' ') letters += 1;\n // Each possible length is tried as the end: the checksum and country length decide.\n if (letters >= 15 && (index + 1 === candidate.length || candidate[index + 1] === ' ') && isIban(candidate.slice(0, index + 1))) {\n return { confidence: 'high', length: index + 1 };\n }\n }\n return null;\n}\n\n/** Rules in priority order: when findings overlap, the earlier rule's finding is kept. */\nexport const RULES: readonly Rule[] = [\n token('aws-access-key-id', '(?:AKIA|ASIA|ABIA|ACCA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|APKA)[A-Z2-7]{16}', 4),\n token('github-token', '(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}|github_pat_[A-Za-z0-9]{22}_[A-Za-z0-9]{59}', (secret) => secret.indexOf('_') + (secret.startsWith('github_pat_') ? 5 : 1)),\n token('gitlab-token', 'glpat-[A-Za-z0-9_-]{20,64}', 6, { end: '(?![A-Za-z0-9_-])' }),\n token('slack-webhook', 'https://hooks\\\\.slack\\\\.com/services/[A-Z0-9]{8,12}/[A-Z0-9]{8,12}/[A-Za-z0-9]{24}', 33),\n token('slack-token', 'xox[abposr]-[A-Za-z0-9-]{10,250}', 5, { end: '(?![A-Za-z0-9-])' }),\n token('stripe-key', '(?:sk|rk)_live_[A-Za-z0-9]{24,247}', 8),\n token('google-api-key', 'AIza[A-Za-z0-9_-]{35}', 4, { end: '(?![A-Za-z0-9_-])' }),\n token('npm-token', 'npm_[A-Za-z0-9]{36}', 4),\n token('pypi-token', 'pypi-AgEIcHlwaS5vcmc[A-Za-z0-9_-]{50,1000}', 5, { end: '(?![A-Za-z0-9_-])' }),\n token('sendgrid-key', 'SG\\\\.[A-Za-z0-9_-]{22}\\\\.[A-Za-z0-9_-]{43}', 3, { end: '(?![A-Za-z0-9_-])' }),\n {\n kind: 'jwt',\n pattern: /(^|[^A-Za-z0-9_-])(eyJ[A-Za-z0-9_-]{8,4000}\\.eyJ[A-Za-z0-9_-]{8,16000}\\.[A-Za-z0-9_-]{16,4000})(?![A-Za-z0-9_-])/g,\n group: 2,\n keep: 3,\n tail: true,\n check: (secret) => (isJwtHeader(secret.slice(0, secret.indexOf('.'))) ? high(secret) : null),\n },\n {\n kind: 'azure-storage-key',\n pattern: /(^|[;\\s\"'])(AccountKey\\s{0,4}=\\s{0,4})([A-Za-z0-9+/]{86}==)/gi,\n group: 3,\n keep: 0,\n tail: false,\n check: high,\n },\n {\n kind: 'url-credentials',\n // `scheme://user:password@`: the password, up to the `@`.\n pattern: /((?:^|[^A-Za-z0-9+.-])[A-Za-z][A-Za-z0-9+.-]{1,30}:\\/\\/[^\\s:/?#@]{0,256}:)([^\\s/?#@]{1,256})(?=@)/g,\n group: 2,\n keep: 0,\n tail: false,\n check: (secret) => (looksSecret(secret, 0) ? high(secret) : null),\n },\n {\n kind: 'connection-string',\n // `;Password=...` in an ADO.NET or ODBC connection string.\n pattern: /(;\\s{0,4}(?:password|pwd)\\s{0,4}=\\s{0,4})([^;'\"\\s]{1,256})/gi,\n group: 2,\n keep: 0,\n tail: false,\n check: (secret) => (looksSecret(secret, 0) ? high(secret) : null),\n },\n token('twilio-key', 'SK[0-9a-fA-F]{32}', 2, { confidence: 'medium' }),\n {\n kind: 'card-number',\n // Grouped 4-6-5 (American Express), in fours (with a short group after), or not grouped.\n pattern: /(^|[^0-9A-Za-z])(\\d{4}[ -]\\d{6}[ -]\\d{5}|\\d{4}(?:[ -]\\d{4}){2,3}(?:[ -]\\d{1,4})?|\\d{13,19})(?![0-9])/g,\n group: 2,\n keep: 0,\n tail: true,\n check: card,\n retry: true,\n },\n {\n kind: 'iban',\n pattern: /(^|[^A-Za-z0-9])([A-Z]{2}\\d{2}(?: ?[A-Z0-9]){11,40})(?![A-Za-z0-9])/g,\n group: 2,\n keep: 2,\n tail: true,\n check: iban,\n retry: true,\n },\n {\n kind: 'generic-secret',\n pattern: ASSIGNMENT,\n group: 4,\n keep: 0,\n tail: false,\n check: (secret, match) => {\n const name = match[3] as string;\n // An AWS secret key: 40 characters of base64, named for both.\n if (/^[A-Za-z0-9/+]{40}$/.test(secret) && /aws/i.test(name) && /secret/i.test(name)) {\n return { kind: 'aws-secret-access-key', confidence: 'medium', length: secret.length };\n }\n return SECRET_NAME.test(name) && looksSecret(secret, 3) ? medium(secret) : null;\n },\n },\n];\n\n/** `-----BEGIN ... PRIVATE KEY-----`, through its `END` line (or the end of the text, when cut off). */\nexport const PRIVATE_KEY = /-----BEGIN (?:[A-Z0-9]{1,16} ){0,3}PRIVATE KEY(?: BLOCK)?-----/g;\n","/**\n * Kinds of secrets {@link scanSecrets} finds.\n *\n * - Keys and tokens of services, by their documented formats: `private-key` (PEM and\n * OpenSSH), `aws-access-key-id`, `aws-secret-access-key`, `github-token`, `gitlab-token`,\n * `slack-token`, `slack-webhook`, `stripe-key` (live keys), `google-api-key`,\n * `npm-token`, `pypi-token`, `sendgrid-key`, `twilio-key`, `azure-storage-key`, `jwt`.\n * - Credentials inside other text: `url-credentials` (the password in\n * `postgres://user:password@host`), `connection-string` (`Password=` in a connection string).\n * - Financial data, by checksum: `card-number` (Luhn and card brand), `iban` (mod-97 and length).\n * - `generic-secret`: a random-looking value assigned to a name such as `password`, `token`\n * or `api_key` (`API_KEY=\"...\"`, `\"password\": \"...\"`).\n */\nexport type SecretKind =\n | 'private-key'\n | 'aws-access-key-id'\n | 'aws-secret-access-key'\n | 'github-token'\n | 'gitlab-token'\n | 'slack-token'\n | 'slack-webhook'\n | 'stripe-key'\n | 'google-api-key'\n | 'npm-token'\n | 'pypi-token'\n | 'sendgrid-key'\n | 'twilio-key'\n | 'azure-storage-key'\n | 'jwt'\n | 'url-credentials'\n | 'connection-string'\n | 'card-number'\n | 'iban'\n | 'generic-secret';\n\n/** People-facing names of the kinds, for messages and redaction marks. */\nexport const SECRET_LABELS: Readonly<Record<SecretKind, string>> = Object.freeze({\n 'private-key': 'private key',\n 'aws-access-key-id': 'AWS access key ID',\n 'aws-secret-access-key': 'AWS secret access key',\n 'github-token': 'GitHub token',\n 'gitlab-token': 'GitLab token',\n 'slack-token': 'Slack token',\n 'slack-webhook': 'Slack webhook URL',\n 'stripe-key': 'Stripe live key',\n 'google-api-key': 'Google API key',\n 'npm-token': 'npm token',\n 'pypi-token': 'PyPI token',\n 'sendgrid-key': 'SendGrid API key',\n 'twilio-key': 'Twilio API key',\n 'azure-storage-key': 'Azure storage key',\n jwt: 'JSON Web Token',\n 'url-credentials': 'password in a URL',\n 'connection-string': 'password in a connection string',\n 'card-number': 'card number',\n iban: 'IBAN',\n 'generic-secret': 'secret',\n});\n\n/** Every kind, in a stable order. */\nexport const SECRET_KINDS: readonly SecretKind[] = Object.freeze(Object.keys(SECRET_LABELS) as SecretKind[]);\n\n/**\n * How sure a finding is.\n *\n * - `high`: the documented format of a service, a valid checksum (cards, IBANs), or a\n * structure that only credentials have (a PEM private key, a password in a URL).\n * - `medium`: the shape fits, but other data has it too: an AWS secret key next to its name,\n * a Twilio key, a value assigned to a secret-sounding name.\n */\nexport type SecretConfidence = 'high' | 'medium';\n\nexport interface SecretFinding {\n readonly kind: SecretKind;\n /** {@link SECRET_LABELS} for the kind. */\n readonly label: string;\n readonly confidence: SecretConfidence;\n /** Where the secret is in the scanned text: `text.slice(start, end)` is the secret. */\n readonly start: number;\n readonly end: number;\n /**\n * A preview safe to show and log: at most a known prefix and the last 4 characters\n * (`ghp_` and `a1B2` around an ellipsis; the last 4 digits of a card). Findings never hold the secret.\n */\n readonly masked: string;\n}\n","import { copyFailure } from '../core/errors';\nimport { PRIVATE_KEY, RULES } from './rules';\nimport { SECRET_KINDS, SECRET_LABELS, type SecretConfidence, type SecretFinding, type SecretKind } from './types';\n\n/** Longest text scanned, in characters. Default 1,000,000; the rest is not scanned (`truncated`). */\nexport const DEFAULT_SECRET_SCAN_LENGTH = 1_000_000;\n\nexport interface ScanSecretsOptions {\n /** Kinds to look for. Default: every kind. */\n readonly kinds?: readonly SecretKind[];\n /** Least confidence reported. Default `'medium'`: everything. `'high'` leaves out guesses. */\n readonly minConfidence?: SecretConfidence;\n /** Longest text scanned, in characters. Default {@link DEFAULT_SECRET_SCAN_LENGTH}. */\n readonly maxLength?: number;\n}\n\nexport interface SecretScan {\n /** In the order they appear; findings never overlap. */\n readonly findings: readonly SecretFinding[];\n /** The text was longer than `maxLength`: only its start was scanned. */\n readonly truncated: boolean;\n}\n\n/** A preview of `secret` safe to show: a known prefix and, where allowed, the last 4 characters. */\nfunction mask(kind: SecretKind, secret: string, keep: number, tail: boolean): string {\n if (kind === 'private-key') return '-----BEGIN \\u2026 PRIVATE KEY-----';\n const compact = kind === 'card-number' || kind === 'iban' ? secret.replace(/[ -]/g, '') : secret;\n if (kind === 'card-number') return `\\u2022\\u2022\\u2022\\u2022 ${compact.slice(-4)}`;\n if (!tail) return '\\u2022'.repeat(8);\n // Short secrets show no more than their prefix: their last characters would give too much away.\n return compact.length - keep < 12 ? `${compact.slice(0, keep)}\\u2026` : `${compact.slice(0, keep)}\\u2026${compact.slice(-4)}`;\n}\n\ninterface Candidate extends SecretFinding {\n readonly priority: number;\n}\n\nfunction finding(kind: SecretKind, confidence: SecretConfidence, start: number, secret: string, keep: number, tail: boolean, priority: number): Candidate {\n return { kind, label: SECRET_LABELS[kind], confidence, start, end: start + secret.length, masked: mask(kind, secret, keep, tail), priority };\n}\n\n/** Private keys: from their `BEGIN` line to their `END` line, or to the end of the text when it is cut off. */\nfunction privateKeys(text: string): Candidate[] {\n const found: Candidate[] = [];\n for (const match of text.matchAll(PRIVATE_KEY)) {\n const start = match.index;\n const endLine = /-----END [A-Z0-9 ]{0,80}-----/g;\n endLine.lastIndex = start + match[0].length;\n const end = endLine.exec(text);\n const stop = end === null ? text.length : end.index + end[0].length;\n found.push(finding('private-key', 'high', start, text.slice(start, stop), 0, false, -1));\n }\n return found;\n}\n\n/**\n * Finds secrets in `text`: keys and tokens of services by their documented formats, private\n * keys, passwords in URLs and connection strings, card numbers and IBANs by their checksums,\n * and random-looking values assigned to names such as `password` or `api_key`.\n *\n * Findings say where each secret is and what kind it is, with a masked preview; they never\n * hold the secret. Every pattern runs in linear time, so any text is safe to scan. Works\n * anywhere, including servers.\n *\n * @example\n * const { findings } = scanSecrets(pastedText);\n * if (findings.length > 0) warn(`This contains a ${findings[0].label}.`);\n *\n * @throws {CopyFailure} `invalid-payload` for an unknown kind or a negative `maxLength`.\n */\nexport function scanSecrets(text: string, options: ScanSecretsOptions = {}): SecretScan {\n const kinds = new Set(options.kinds ?? SECRET_KINDS);\n for (const kind of kinds) {\n if (!SECRET_KINDS.includes(kind)) throw copyFailure('invalid-payload', `Unknown secret kind: ${kind}.`);\n }\n const maxLength = options.maxLength ?? DEFAULT_SECRET_SCAN_LENGTH;\n if (!(maxLength >= 0)) throw copyFailure('invalid-payload', 'maxLength must be a number of at least 0.');\n const scanned = text.length > maxLength ? text.slice(0, maxLength) : text;\n const highOnly = options.minConfidence === 'high';\n\n const candidates: Candidate[] = kinds.has('private-key') ? privateKeys(scanned) : [];\n RULES.forEach((rule, priority) => {\n // One pattern can find two kinds (an AWS secret key, or a generic secret): both are checked below.\n if (!kinds.has(rule.kind) && !(rule.kind === 'generic-secret' && kinds.has('aws-secret-access-key'))) return;\n // Patterns are shared: the scan is synchronous, so resetting `lastIndex` is enough.\n const pattern = rule.pattern;\n pattern.lastIndex = 0;\n for (let match = pattern.exec(scanned); match !== null; match = pattern.exec(scanned)) {\n const secret = match[rule.group] as string;\n const start = match.index + match[0].length - secret.length;\n const verdict = rule.check(secret, match);\n const kind = verdict?.kind ?? rule.kind;\n if (verdict === null || !kinds.has(kind)) {\n if (rule.retry === true) pattern.lastIndex = start + 1;\n continue;\n }\n const value = secret.slice(0, verdict.length);\n const keep = typeof rule.keep === 'number' ? rule.keep : rule.keep(value);\n candidates.push(finding(kind, verdict.confidence, start, value, keep, rule.tail, priority));\n // What the match read past the secret (more digits after a card) is looked at again.\n pattern.lastIndex = start + verdict.length;\n }\n });\n\n // Overlapping findings: the earliest wins, then the most specific rule. A rule finds at most\n // one secret at a position, so no two candidates tie.\n candidates.sort((a, b) => a.start - b.start || a.priority - b.priority);\n const findings: SecretFinding[] = [];\n let reached = 0;\n for (const candidate of candidates) {\n if ((highOnly && candidate.confidence !== 'high') || candidate.start < reached) continue;\n const { kind, label, confidence, start, end, masked } = candidate;\n findings.push({ kind, label, confidence, start, end, masked });\n reached = end;\n }\n return { findings, truncated: scanned.length < text.length };\n}\n","import type { CopyInterceptTransform } from '../core/copy-interceptor';\nimport { scanSecrets, type ScanSecretsOptions } from './scan';\nimport type { SecretFinding } from './types';\n\nexport interface RedactSecretsOptions extends ScanSecretsOptions {\n /** What replaces each secret. Default: `[redacted <label>]`, as in `[redacted GitHub token]`. */\n readonly replace?: (finding: SecretFinding) => string;\n}\n\nexport interface RedactedText {\n /** The text with each secret replaced. */\n readonly text: string;\n /** What was replaced, at its place in the original text. */\n readonly findings: readonly SecretFinding[];\n /** The text was longer than `maxLength`: the rest was neither scanned nor kept. */\n readonly truncated: boolean;\n}\n\nconst defaultReplace = (finding: SecretFinding): string => `[redacted ${finding.label}]`;\n\n/**\n * `text` with every secret {@link scanSecrets} finds replaced, by default with\n * `[redacted <label>]`. Text past `maxLength` is dropped, never passed on unscanned.\n *\n * @example\n * redactSecrets('token: ghp_...').text; // 'token: [redacted GitHub token]'\n */\nexport function redactSecrets(text: string, options: RedactSecretsOptions = {}): RedactedText {\n const { findings, truncated } = scanSecrets(text, options);\n const replace = options.replace ?? defaultReplace;\n let out = '';\n let at = 0;\n for (const finding of findings) {\n out += text.slice(at, finding.start) + replace(finding);\n at = finding.end;\n }\n const end = truncated ? (options.maxLength as number) : text.length;\n return { text: out + text.slice(at, end), findings, truncated };\n}\n\n/**\n * A transform for `useCopyInterceptor` and `registerCopyInterceptor`: when what people copy\n * from your page (logs, settings, a support console) holds secrets, the clipboard gets the\n * text with them redacted; other copies are left to the browser. The redacted copy is\n * plain text: formatting around a secret could carry it too.\n *\n * @example\n * useCopyInterceptor(logViewerRef, { transform: secretRedactor() });\n */\nexport function secretRedactor(options: RedactSecretsOptions = {}): CopyInterceptTransform {\n return (selection) => {\n const redacted = redactSecrets(selection.text, options);\n return redacted.findings.length === 0 && !redacted.truncated ? null : redacted.text;\n };\n}\n","import { asTextField, insertText } from '../core/text-field';\nimport { redactSecrets, type RedactSecretsOptions } from './redact';\nimport type { SecretFinding } from './types';\n\n/** What {@link pasteWithoutSecrets} did. */\nexport type SecretPasteOutcome =\n /** No secrets (or nothing to read): the browser pasted as usual. */\n | 'clean'\n /** The paste was inserted with its secrets redacted. */\n | 'redacted'\n /** The paste was stopped: nothing was inserted. */\n | 'blocked';\n\nexport interface PasteWithoutSecretsOptions extends RedactSecretsOptions {\n /**\n * `'redact'` (default) inserts the paste with its secrets replaced, into a `<textarea>` or\n * text `<input>`, with undo intact. `'block'` inserts nothing. Where text can't be inserted\n * (another element), a paste with secrets is blocked.\n */\n readonly action?: 'redact' | 'block';\n /** Called when a paste held secrets, with what was found and what was done. */\n readonly onSecrets?: (findings: readonly SecretFinding[], outcome: Exclude<SecretPasteOutcome, 'clean'>) => void;\n}\n\n/** Structural paste event: a DOM `ClipboardEvent` and React's `onPaste` event both fit. */\nexport interface SecretPasteEvent {\n readonly clipboardData: { getData(format: string): string } | null;\n readonly currentTarget: EventTarget | null;\n readonly target: EventTarget | null;\n readonly defaultPrevented: boolean;\n preventDefault(): void;\n}\n\n/**\n * A paste handler that keeps secrets out of a field: chat boxes, comments, tickets and\n * forms where an API key or a password pasted by mistake would be seen or stored. A paste\n * without secrets is left to the browser.\n *\n * @example\n * <textarea onPaste={(event) => pasteWithoutSecrets(event, { onSecrets: (found) => toast(`Removed a ${found[0].label}.`) })} />\n */\nexport function pasteWithoutSecrets(event: SecretPasteEvent, options: PasteWithoutSecretsOptions = {}): SecretPasteOutcome {\n if (event.defaultPrevented || event.clipboardData === null) return 'clean';\n const text = event.clipboardData.getData('text/plain');\n if (text === '') return 'clean';\n const redacted = redactSecrets(text, options);\n if (redacted.findings.length === 0 && !redacted.truncated) return 'clean';\n event.preventDefault();\n const field = asTextField(event.currentTarget) ?? asTextField(event.target);\n const outcome = options.action !== 'block' && field !== null && insertText(field, redacted.text) ? 'redacted' : 'blocked';\n options.onSecrets?.(redacted.findings, outcome);\n return outcome;\n}\n"],"mappings":";;;;;;;AAGA,SAAgB,KAAK,QAAyB;CAC5C,IAAI,MAAM;CACV,KAAK,IAAI,QAAQ,GAAG,QAAQ,OAAO,QAAQ,SAAS,GAAG;EACrD,IAAI,QAAQ,OAAO,WAAW,OAAO,SAAS,IAAI,KAAK,IAAI;EAC3D,IAAI,QAAQ,MAAM,GAAG;GACnB,SAAS;GACT,IAAI,QAAQ,GAAG,SAAS;EAC1B;EACA,OAAO;CACT;CACA,OAAO,MAAM,OAAO;AACtB;;AAGA,MAAM,SAAsF;CAC1F;EAAE,QAAQ;EAAM,SAAS;GAAC;GAAI;GAAI;EAAE;CAAE;CACtC;EAAE,QAAQ;EAA2D,SAAS,CAAC,EAAE;CAAE;CACnF;EAAE,QAAQ;EAAU,SAAS,CAAC,EAAE;CAAE;CAClC;EAAE,QAAQ;EAAwB,SAAS;GAAC;GAAI;GAAI;GAAI;EAAE;CAAE;CAC5D;EAAE,QAAQ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AC,SAAS,WAAW,OAAO;CAClE,MAAM,eAAe;CACrB,MAAM,QAAQC,mBAAAA,YAAY,MAAM,aAAa,KAAKA,mBAAAA,YAAY,MAAM,MAAM;CAC1E,MAAM,UAAU,QAAQ,WAAW,WAAW,UAAU,QAAQC,mBAAAA,WAAW,OAAO,SAAS,IAAI,IAAI,aAAa;CAChH,QAAQ,YAAY,SAAS,UAAU,OAAO;CAC9C,OAAO;AACT"}
@@ -0,0 +1,152 @@
1
+
2
+ import { c as CopyInterceptTransform } from "./chunks/copy-interceptor-CZWzGOkL.cjs";
3
+ //#region src/secrets/types.d.ts
4
+ /**
5
+ * Kinds of secrets {@link scanSecrets} finds.
6
+ *
7
+ * - Keys and tokens of services, by their documented formats: `private-key` (PEM and
8
+ * OpenSSH), `aws-access-key-id`, `aws-secret-access-key`, `github-token`, `gitlab-token`,
9
+ * `slack-token`, `slack-webhook`, `stripe-key` (live keys), `google-api-key`,
10
+ * `npm-token`, `pypi-token`, `sendgrid-key`, `twilio-key`, `azure-storage-key`, `jwt`.
11
+ * - Credentials inside other text: `url-credentials` (the password in
12
+ * `postgres://user:password@host`), `connection-string` (`Password=` in a connection string).
13
+ * - Financial data, by checksum: `card-number` (Luhn and card brand), `iban` (mod-97 and length).
14
+ * - `generic-secret`: a random-looking value assigned to a name such as `password`, `token`
15
+ * or `api_key` (`API_KEY="..."`, `"password": "..."`).
16
+ */
17
+ type SecretKind = 'private-key' | 'aws-access-key-id' | 'aws-secret-access-key' | 'github-token' | 'gitlab-token' | 'slack-token' | 'slack-webhook' | 'stripe-key' | 'google-api-key' | 'npm-token' | 'pypi-token' | 'sendgrid-key' | 'twilio-key' | 'azure-storage-key' | 'jwt' | 'url-credentials' | 'connection-string' | 'card-number' | 'iban' | 'generic-secret';
18
+ /** People-facing names of the kinds, for messages and redaction marks. */
19
+ export declare const SECRET_LABELS: Readonly<Record<SecretKind, string>>;
20
+ /** Every kind, in a stable order. */
21
+ export declare const SECRET_KINDS: readonly SecretKind[];
22
+ /**
23
+ * How sure a finding is.
24
+ *
25
+ * - `high`: the documented format of a service, a valid checksum (cards, IBANs), or a
26
+ * structure that only credentials have (a PEM private key, a password in a URL).
27
+ * - `medium`: the shape fits, but other data has it too: an AWS secret key next to its name,
28
+ * a Twilio key, a value assigned to a secret-sounding name.
29
+ */
30
+ type SecretConfidence = 'high' | 'medium';
31
+ interface SecretFinding {
32
+ readonly kind: SecretKind;
33
+ /** {@link SECRET_LABELS} for the kind. */
34
+ readonly label: string;
35
+ readonly confidence: SecretConfidence;
36
+ /** Where the secret is in the scanned text: `text.slice(start, end)` is the secret. */
37
+ readonly start: number;
38
+ readonly end: number;
39
+ /**
40
+ * A preview safe to show and log: at most a known prefix and the last 4 characters
41
+ * (`ghp_` and `a1B2` around an ellipsis; the last 4 digits of a card). Findings never hold the secret.
42
+ */
43
+ readonly masked: string;
44
+ }
45
+ //#endregion
46
+ //#region src/secrets/scan.d.ts
47
+ /** Longest text scanned, in characters. Default 1,000,000; the rest is not scanned (`truncated`). */
48
+ export declare const DEFAULT_SECRET_SCAN_LENGTH = 1000000;
49
+ interface ScanSecretsOptions {
50
+ /** Kinds to look for. Default: every kind. */
51
+ readonly kinds?: readonly SecretKind[];
52
+ /** Least confidence reported. Default `'medium'`: everything. `'high'` leaves out guesses. */
53
+ readonly minConfidence?: SecretConfidence;
54
+ /** Longest text scanned, in characters. Default {@link DEFAULT_SECRET_SCAN_LENGTH}. */
55
+ readonly maxLength?: number;
56
+ }
57
+ interface SecretScan {
58
+ /** In the order they appear; findings never overlap. */
59
+ readonly findings: readonly SecretFinding[];
60
+ /** The text was longer than `maxLength`: only its start was scanned. */
61
+ readonly truncated: boolean;
62
+ }
63
+ /**
64
+ * Finds secrets in `text`: keys and tokens of services by their documented formats, private
65
+ * keys, passwords in URLs and connection strings, card numbers and IBANs by their checksums,
66
+ * and random-looking values assigned to names such as `password` or `api_key`.
67
+ *
68
+ * Findings say where each secret is and what kind it is, with a masked preview; they never
69
+ * hold the secret. Every pattern runs in linear time, so any text is safe to scan. Works
70
+ * anywhere, including servers.
71
+ *
72
+ * @example
73
+ * const { findings } = scanSecrets(pastedText);
74
+ * if (findings.length > 0) warn(`This contains a ${findings[0].label}.`);
75
+ *
76
+ * @throws {CopyFailure} `invalid-payload` for an unknown kind or a negative `maxLength`.
77
+ */
78
+ export declare function scanSecrets(text: string, options?: ScanSecretsOptions): SecretScan;
79
+ //#endregion
80
+ //#region src/secrets/redact.d.ts
81
+ interface RedactSecretsOptions extends ScanSecretsOptions {
82
+ /** What replaces each secret. Default: `[redacted <label>]`, as in `[redacted GitHub token]`. */
83
+ readonly replace?: (finding: SecretFinding) => string;
84
+ }
85
+ interface RedactedText {
86
+ /** The text with each secret replaced. */
87
+ readonly text: string;
88
+ /** What was replaced, at its place in the original text. */
89
+ readonly findings: readonly SecretFinding[];
90
+ /** The text was longer than `maxLength`: the rest was neither scanned nor kept. */
91
+ readonly truncated: boolean;
92
+ }
93
+ /**
94
+ * `text` with every secret {@link scanSecrets} finds replaced, by default with
95
+ * `[redacted <label>]`. Text past `maxLength` is dropped, never passed on unscanned.
96
+ *
97
+ * @example
98
+ * redactSecrets('token: ghp_...').text; // 'token: [redacted GitHub token]'
99
+ */
100
+ export declare function redactSecrets(text: string, options?: RedactSecretsOptions): RedactedText;
101
+ /**
102
+ * A transform for `useCopyInterceptor` and `registerCopyInterceptor`: when what people copy
103
+ * from your page (logs, settings, a support console) holds secrets, the clipboard gets the
104
+ * text with them redacted; other copies are left to the browser. The redacted copy is
105
+ * plain text: formatting around a secret could carry it too.
106
+ *
107
+ * @example
108
+ * useCopyInterceptor(logViewerRef, { transform: secretRedactor() });
109
+ */
110
+ export declare function secretRedactor(options?: RedactSecretsOptions): CopyInterceptTransform;
111
+ //#endregion
112
+ //#region src/secrets/paste.d.ts
113
+ /** What {@link pasteWithoutSecrets} did. */
114
+ type SecretPasteOutcome =
115
+ /** No secrets (or nothing to read): the browser pasted as usual. */
116
+ 'clean' |
117
+ /** The paste was inserted with its secrets redacted. */
118
+ 'redacted' |
119
+ /** The paste was stopped: nothing was inserted. */
120
+ 'blocked';
121
+ interface PasteWithoutSecretsOptions extends RedactSecretsOptions {
122
+ /**
123
+ * `'redact'` (default) inserts the paste with its secrets replaced, into a `<textarea>` or
124
+ * text `<input>`, with undo intact. `'block'` inserts nothing. Where text can't be inserted
125
+ * (another element), a paste with secrets is blocked.
126
+ */
127
+ readonly action?: 'redact' | 'block';
128
+ /** Called when a paste held secrets, with what was found and what was done. */
129
+ readonly onSecrets?: (findings: readonly SecretFinding[], outcome: Exclude<SecretPasteOutcome, 'clean'>) => void;
130
+ }
131
+ /** Structural paste event: a DOM `ClipboardEvent` and React's `onPaste` event both fit. */
132
+ interface SecretPasteEvent {
133
+ readonly clipboardData: {
134
+ getData(format: string): string;
135
+ } | null;
136
+ readonly currentTarget: EventTarget | null;
137
+ readonly target: EventTarget | null;
138
+ readonly defaultPrevented: boolean;
139
+ preventDefault(): void;
140
+ }
141
+ /**
142
+ * A paste handler that keeps secrets out of a field: chat boxes, comments, tickets and
143
+ * forms where an API key or a password pasted by mistake would be seen or stored. A paste
144
+ * without secrets is left to the browser.
145
+ *
146
+ * @example
147
+ * <textarea onPaste={(event) => pasteWithoutSecrets(event, { onSecrets: (found) => toast(`Removed a ${found[0].label}.`) })} />
148
+ */
149
+ export declare function pasteWithoutSecrets(event: SecretPasteEvent, options?: PasteWithoutSecretsOptions): SecretPasteOutcome;
150
+ //#endregion
151
+ export type { PasteWithoutSecretsOptions, RedactSecretsOptions, RedactedText, ScanSecretsOptions, SecretConfidence, SecretFinding, SecretKind, SecretPasteEvent, SecretPasteOutcome, SecretScan };
152
+ //# sourceMappingURL=secrets.d.cts.map
@@ -0,0 +1,152 @@
1
+
2
+ import { c as CopyInterceptTransform } from "./chunks/copy-interceptor-C6NABy1l.js";
3
+ //#region src/secrets/types.d.ts
4
+ /**
5
+ * Kinds of secrets {@link scanSecrets} finds.
6
+ *
7
+ * - Keys and tokens of services, by their documented formats: `private-key` (PEM and
8
+ * OpenSSH), `aws-access-key-id`, `aws-secret-access-key`, `github-token`, `gitlab-token`,
9
+ * `slack-token`, `slack-webhook`, `stripe-key` (live keys), `google-api-key`,
10
+ * `npm-token`, `pypi-token`, `sendgrid-key`, `twilio-key`, `azure-storage-key`, `jwt`.
11
+ * - Credentials inside other text: `url-credentials` (the password in
12
+ * `postgres://user:password@host`), `connection-string` (`Password=` in a connection string).
13
+ * - Financial data, by checksum: `card-number` (Luhn and card brand), `iban` (mod-97 and length).
14
+ * - `generic-secret`: a random-looking value assigned to a name such as `password`, `token`
15
+ * or `api_key` (`API_KEY="..."`, `"password": "..."`).
16
+ */
17
+ type SecretKind = 'private-key' | 'aws-access-key-id' | 'aws-secret-access-key' | 'github-token' | 'gitlab-token' | 'slack-token' | 'slack-webhook' | 'stripe-key' | 'google-api-key' | 'npm-token' | 'pypi-token' | 'sendgrid-key' | 'twilio-key' | 'azure-storage-key' | 'jwt' | 'url-credentials' | 'connection-string' | 'card-number' | 'iban' | 'generic-secret';
18
+ /** People-facing names of the kinds, for messages and redaction marks. */
19
+ export declare const SECRET_LABELS: Readonly<Record<SecretKind, string>>;
20
+ /** Every kind, in a stable order. */
21
+ export declare const SECRET_KINDS: readonly SecretKind[];
22
+ /**
23
+ * How sure a finding is.
24
+ *
25
+ * - `high`: the documented format of a service, a valid checksum (cards, IBANs), or a
26
+ * structure that only credentials have (a PEM private key, a password in a URL).
27
+ * - `medium`: the shape fits, but other data has it too: an AWS secret key next to its name,
28
+ * a Twilio key, a value assigned to a secret-sounding name.
29
+ */
30
+ type SecretConfidence = 'high' | 'medium';
31
+ interface SecretFinding {
32
+ readonly kind: SecretKind;
33
+ /** {@link SECRET_LABELS} for the kind. */
34
+ readonly label: string;
35
+ readonly confidence: SecretConfidence;
36
+ /** Where the secret is in the scanned text: `text.slice(start, end)` is the secret. */
37
+ readonly start: number;
38
+ readonly end: number;
39
+ /**
40
+ * A preview safe to show and log: at most a known prefix and the last 4 characters
41
+ * (`ghp_` and `a1B2` around an ellipsis; the last 4 digits of a card). Findings never hold the secret.
42
+ */
43
+ readonly masked: string;
44
+ }
45
+ //#endregion
46
+ //#region src/secrets/scan.d.ts
47
+ /** Longest text scanned, in characters. Default 1,000,000; the rest is not scanned (`truncated`). */
48
+ export declare const DEFAULT_SECRET_SCAN_LENGTH = 1000000;
49
+ interface ScanSecretsOptions {
50
+ /** Kinds to look for. Default: every kind. */
51
+ readonly kinds?: readonly SecretKind[];
52
+ /** Least confidence reported. Default `'medium'`: everything. `'high'` leaves out guesses. */
53
+ readonly minConfidence?: SecretConfidence;
54
+ /** Longest text scanned, in characters. Default {@link DEFAULT_SECRET_SCAN_LENGTH}. */
55
+ readonly maxLength?: number;
56
+ }
57
+ interface SecretScan {
58
+ /** In the order they appear; findings never overlap. */
59
+ readonly findings: readonly SecretFinding[];
60
+ /** The text was longer than `maxLength`: only its start was scanned. */
61
+ readonly truncated: boolean;
62
+ }
63
+ /**
64
+ * Finds secrets in `text`: keys and tokens of services by their documented formats, private
65
+ * keys, passwords in URLs and connection strings, card numbers and IBANs by their checksums,
66
+ * and random-looking values assigned to names such as `password` or `api_key`.
67
+ *
68
+ * Findings say where each secret is and what kind it is, with a masked preview; they never
69
+ * hold the secret. Every pattern runs in linear time, so any text is safe to scan. Works
70
+ * anywhere, including servers.
71
+ *
72
+ * @example
73
+ * const { findings } = scanSecrets(pastedText);
74
+ * if (findings.length > 0) warn(`This contains a ${findings[0].label}.`);
75
+ *
76
+ * @throws {CopyFailure} `invalid-payload` for an unknown kind or a negative `maxLength`.
77
+ */
78
+ export declare function scanSecrets(text: string, options?: ScanSecretsOptions): SecretScan;
79
+ //#endregion
80
+ //#region src/secrets/redact.d.ts
81
+ interface RedactSecretsOptions extends ScanSecretsOptions {
82
+ /** What replaces each secret. Default: `[redacted <label>]`, as in `[redacted GitHub token]`. */
83
+ readonly replace?: (finding: SecretFinding) => string;
84
+ }
85
+ interface RedactedText {
86
+ /** The text with each secret replaced. */
87
+ readonly text: string;
88
+ /** What was replaced, at its place in the original text. */
89
+ readonly findings: readonly SecretFinding[];
90
+ /** The text was longer than `maxLength`: the rest was neither scanned nor kept. */
91
+ readonly truncated: boolean;
92
+ }
93
+ /**
94
+ * `text` with every secret {@link scanSecrets} finds replaced, by default with
95
+ * `[redacted <label>]`. Text past `maxLength` is dropped, never passed on unscanned.
96
+ *
97
+ * @example
98
+ * redactSecrets('token: ghp_...').text; // 'token: [redacted GitHub token]'
99
+ */
100
+ export declare function redactSecrets(text: string, options?: RedactSecretsOptions): RedactedText;
101
+ /**
102
+ * A transform for `useCopyInterceptor` and `registerCopyInterceptor`: when what people copy
103
+ * from your page (logs, settings, a support console) holds secrets, the clipboard gets the
104
+ * text with them redacted; other copies are left to the browser. The redacted copy is
105
+ * plain text: formatting around a secret could carry it too.
106
+ *
107
+ * @example
108
+ * useCopyInterceptor(logViewerRef, { transform: secretRedactor() });
109
+ */
110
+ export declare function secretRedactor(options?: RedactSecretsOptions): CopyInterceptTransform;
111
+ //#endregion
112
+ //#region src/secrets/paste.d.ts
113
+ /** What {@link pasteWithoutSecrets} did. */
114
+ type SecretPasteOutcome =
115
+ /** No secrets (or nothing to read): the browser pasted as usual. */
116
+ 'clean' |
117
+ /** The paste was inserted with its secrets redacted. */
118
+ 'redacted' |
119
+ /** The paste was stopped: nothing was inserted. */
120
+ 'blocked';
121
+ interface PasteWithoutSecretsOptions extends RedactSecretsOptions {
122
+ /**
123
+ * `'redact'` (default) inserts the paste with its secrets replaced, into a `<textarea>` or
124
+ * text `<input>`, with undo intact. `'block'` inserts nothing. Where text can't be inserted
125
+ * (another element), a paste with secrets is blocked.
126
+ */
127
+ readonly action?: 'redact' | 'block';
128
+ /** Called when a paste held secrets, with what was found and what was done. */
129
+ readonly onSecrets?: (findings: readonly SecretFinding[], outcome: Exclude<SecretPasteOutcome, 'clean'>) => void;
130
+ }
131
+ /** Structural paste event: a DOM `ClipboardEvent` and React's `onPaste` event both fit. */
132
+ interface SecretPasteEvent {
133
+ readonly clipboardData: {
134
+ getData(format: string): string;
135
+ } | null;
136
+ readonly currentTarget: EventTarget | null;
137
+ readonly target: EventTarget | null;
138
+ readonly defaultPrevented: boolean;
139
+ preventDefault(): void;
140
+ }
141
+ /**
142
+ * A paste handler that keeps secrets out of a field: chat boxes, comments, tickets and
143
+ * forms where an API key or a password pasted by mistake would be seen or stored. A paste
144
+ * without secrets is left to the browser.
145
+ *
146
+ * @example
147
+ * <textarea onPaste={(event) => pasteWithoutSecrets(event, { onSecrets: (found) => toast(`Removed a ${found[0].label}.`) })} />
148
+ */
149
+ export declare function pasteWithoutSecrets(event: SecretPasteEvent, options?: PasteWithoutSecretsOptions): SecretPasteOutcome;
150
+ //#endregion
151
+ export type { PasteWithoutSecretsOptions, RedactSecretsOptions, RedactedText, ScanSecretsOptions, SecretConfidence, SecretFinding, SecretKind, SecretPasteEvent, SecretPasteOutcome, SecretScan };
152
+ //# sourceMappingURL=secrets.d.ts.map