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.
- package/README.md +73 -0
- package/dist/secrets.cjs +551 -0
- package/dist/secrets.cjs.map +1 -0
- package/dist/secrets.d.cts +152 -0
- package/dist/secrets.d.ts +152 -0
- package/dist/secrets.js +544 -0
- package/dist/secrets.js.map +1 -0
- package/package.json +31 -3
package/README.md
CHANGED
|
@@ -33,6 +33,7 @@ ID PLT-29018 [Copy]
|
|
|
33
33
|
- **`react-smart-copy/code`**: copy code blocks the way developers expect (a terminal session copies as its commands, gutters and prompts stay behind, colours survive in Docs and Slack), paste code cleaned and indented, and catch Trojan Source, invisible identifiers and lookalike letters
|
|
34
34
|
- **`react-smart-copy/image`**: get pasted photos and screenshots ready to upload. It removes GPS location, camera data and hidden thumbnails without touching a pixel, and fits size and byte limits, re-encoding only when it has to
|
|
35
35
|
- **`react-smart-copy/files`**: take pasted and dropped files and whole folders safely. Types come from each file's content, so a program named `invoice.pdf.exe` or a web page named `report.pdf` is turned away with a reason, names are made safe for every operating system, and limits cap count, size and depth
|
|
36
|
+
- **`react-smart-copy/secrets`**: keep API keys, tokens, private keys, passwords, card numbers and IBANs out of pastes and copies. Paste guards for chat boxes and forms, and redaction of what people copy from logs and consoles. Every pattern runs in linear time, and no finding holds the secret
|
|
36
37
|
- **`react-smart-copy/link`**: "Copy link" buttons that paste as a titled link in Slack, Docs and Notion and as the URL in editors, links that scroll to a highlighted passage, tracking parameters removed, and pasting a URL over selected text to make a link
|
|
37
38
|
- **`react-smart-copy/rich`**: copy styled content so it pastes as it looks in Gmail, Outlook, Apple Mail, Google Docs, Word, Notion and Slack: sanitized HTML with inline styles, email-safe colours and absolute links, plus readable plain text. Works for buttons and for Ctrl/⌘+C. And the other way: paste from Docs, Word and mail into a rich-text editor (TipTap, Lexical, `contenteditable`) as clean, semantic HTML
|
|
38
39
|
- **`react-smart-copy/color`**: copy colours in any CSS format (hex to `oklch()` and Display P3) with a swatch for Docs and Slack, paste any format into a colour field, and check WCAG contrast. Wide-gamut colours are mapped the way CSS specifies, never clipped to a wrong hue
|
|
@@ -947,6 +948,77 @@ that names the file by its safe name. Checking files in the browser is for the p
|
|
|
947
948
|
using your app: check them again on your server, where `inspectFile` works the same, and
|
|
948
949
|
serve uploads with `Content-Disposition: attachment` and `X-Content-Type-Options: nosniff`.
|
|
949
950
|
|
|
951
|
+
## Secrets: keep keys out of pastes and copies
|
|
952
|
+
|
|
953
|
+
`react-smart-copy/secrets` keeps secrets from travelling through the clipboard. It finds API
|
|
954
|
+
keys, tokens, private keys, passwords, card numbers and IBANs in text people paste or copy,
|
|
955
|
+
and redacts or blocks them: in a chat box, a support ticket, or a log someone copies from
|
|
956
|
+
your app. No dependencies, about 4.1 kB (about 3.3 kB for `scanSecrets` alone), and it works
|
|
957
|
+
the same on a server.
|
|
958
|
+
|
|
959
|
+
```tsx
|
|
960
|
+
import { pasteWithoutSecrets } from "react-smart-copy/secrets";
|
|
961
|
+
|
|
962
|
+
<textarea
|
|
963
|
+
onPaste={(event) =>
|
|
964
|
+
pasteWithoutSecrets(event, {
|
|
965
|
+
// "redact" (the default) inserts the paste with each secret replaced; "block" inserts nothing.
|
|
966
|
+
action: "redact",
|
|
967
|
+
onSecrets: (found) => toast(`Removed a ${found[0].label} from your message.`),
|
|
968
|
+
})
|
|
969
|
+
}
|
|
970
|
+
/>
|
|
971
|
+
```
|
|
972
|
+
|
|
973
|
+
**What it finds.** Each finding has a kind, a confidence, and a masked preview.
|
|
974
|
+
|
|
975
|
+
- **Service keys and tokens, by their documented formats:** AWS access key IDs, GitHub
|
|
976
|
+
(classic and fine-grained), GitLab, Slack tokens and webhooks, Stripe live keys, Google API
|
|
977
|
+
keys, npm, PyPI, SendGrid, Twilio, Azure storage keys, and JSON Web Tokens (whose
|
|
978
|
+
header must decode).
|
|
979
|
+
- **Private keys** (PEM and OpenSSH), from their `BEGIN` line to their `END` line.
|
|
980
|
+
- **Passwords inside other text:** in URLs (`postgres://app:password@db`) and in connection
|
|
981
|
+
strings (`;Password=...`).
|
|
982
|
+
- **Card numbers and IBANs, by checksum:** Luhn plus the card brand's ranges and lengths,
|
|
983
|
+
and mod-97 plus the country's IBAN length.
|
|
984
|
+
- **Random-looking values assigned to secret names:** `API_KEY="..."`, `"password": "..."`,
|
|
985
|
+
`client_secret: ...`, including an AWS secret key next to its name. Placeholders
|
|
986
|
+
(`changeme`, `<token>`, `${TOKEN}`) and references (`process.env.TOKEN`) are left alone.
|
|
987
|
+
|
|
988
|
+
**Safe to run on anything.** Every pattern runs in linear time: no nested quantifiers, no
|
|
989
|
+
lookbehind. Hostile text of hundreds of kilobytes is scanned in milliseconds. A finding never
|
|
990
|
+
holds the secret: it holds where the secret is (`start`, `end`), its `kind` and `label`, a
|
|
991
|
+
`confidence`, and `masked`. `masked` keeps at most a known prefix and the last 4 characters
|
|
992
|
+
(`ghp_` and the last 4, or `•••• 4242` for a card), and nothing at all for passwords. Text
|
|
993
|
+
past `maxLength` (1,000,000 characters) is not scanned, and `redactSecrets` drops it rather
|
|
994
|
+
than pass it on unchecked.
|
|
995
|
+
|
|
996
|
+
```ts
|
|
997
|
+
import { redactSecrets, scanSecrets, secretRedactor } from "react-smart-copy/secrets";
|
|
998
|
+
|
|
999
|
+
const { findings } = scanSecrets(text, { minConfidence: "high" });
|
|
1000
|
+
// [{ kind: "github-token", label: "GitHub token", confidence: "high", start: 13, end: 53, masked: "ghp_…a1B2" }]
|
|
1001
|
+
|
|
1002
|
+
redactSecrets("token=ghp_…").text; // "token=[redacted GitHub token]"
|
|
1003
|
+
|
|
1004
|
+
// Mask secrets in what people copy from a log viewer or an admin console.
|
|
1005
|
+
useCopyInterceptor(logRef, { transform: secretRedactor() });
|
|
1006
|
+
```
|
|
1007
|
+
|
|
1008
|
+
| Option | Default | Notes |
|
|
1009
|
+
| --- | --- | --- |
|
|
1010
|
+
| `kinds` | every kind | the kinds to look for |
|
|
1011
|
+
| `minConfidence` | `"medium"` | `"high"` leaves out values that only look like secrets |
|
|
1012
|
+
| `maxLength` | 1,000,000 | characters scanned |
|
|
1013
|
+
| `replace` | `[redacted <label>]` | `redactSecrets`, `pasteWithoutSecrets` and `secretRedactor` |
|
|
1014
|
+
| `action` | `"redact"` | `pasteWithoutSecrets`: `"block"` inserts nothing |
|
|
1015
|
+
| `onSecrets` | | `pasteWithoutSecrets`: called with the findings and what was done |
|
|
1016
|
+
|
|
1017
|
+
A paste is redacted in a `<textarea>` or text `<input>`, with undo intact; anywhere else, a
|
|
1018
|
+
paste with secrets is blocked. Scanning in the browser protects the people using your app.
|
|
1019
|
+
Scan again on your server before you store or forward text, because `scanSecrets` works the
|
|
1020
|
+
same there.
|
|
1021
|
+
|
|
950
1022
|
## Copy links
|
|
951
1023
|
|
|
952
1024
|
`react-smart-copy/link` is for "Copy link" and "Share" buttons, and for fields people
|
|
@@ -1765,6 +1837,7 @@ embedded webviews. Where a capability is missing you get a typed error, never a
|
|
|
1765
1837
|
- ~~**1.18** One shared copy of the core across entry points: smaller bundles when you use several modules, and one `CopyFailure` class~~ shipped
|
|
1766
1838
|
- ~~**1.19** `react-smart-copy/rich`, paste side: paste from Word, Google Docs and web pages into rich-text editors as clean, safe HTML~~ shipped
|
|
1767
1839
|
- ~~**1.20** `react-smart-copy/files` — take pasted and dropped files and folders safely: types from content, risky files rejected, safe names, limits~~ shipped
|
|
1840
|
+
- ~~**1.21** `react-smart-copy/secrets` — find and redact API keys, tokens, private keys, passwords, cards and IBANs in pastes and copies~~ shipped
|
|
1768
1841
|
|
|
1769
1842
|
Full history: [CHANGELOG.md](./CHANGELOG.md) or the [Releases page](https://suprabhat02.github.io/react-smart-copy/project/releases/).
|
|
1770
1843
|
|
package/dist/secrets.cjs
ADDED
|
@@ -0,0 +1,551 @@
|
|
|
1
|
+
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const require_errors = require("./chunks/errors-BwOF6T_M.cjs");
|
|
4
|
+
const require_text_field = require("./chunks/text-field-Ba8W3v4R.cjs");
|
|
5
|
+
//#region src/secrets/checks.ts
|
|
6
|
+
/** Checks that tell real secrets from look-alikes: checksums, structure and randomness. */
|
|
7
|
+
/** The Luhn checksum of card numbers. `digits` holds only digits. */
|
|
8
|
+
function luhn(digits) {
|
|
9
|
+
let sum = 0;
|
|
10
|
+
for (let index = 0; index < digits.length; index += 1) {
|
|
11
|
+
let digit = digits.charCodeAt(digits.length - 1 - index) - 48;
|
|
12
|
+
if (index % 2 === 1) {
|
|
13
|
+
digit *= 2;
|
|
14
|
+
if (digit > 9) digit -= 9;
|
|
15
|
+
}
|
|
16
|
+
sum += digit;
|
|
17
|
+
}
|
|
18
|
+
return sum % 10 === 0;
|
|
19
|
+
}
|
|
20
|
+
/** Card brands by their number ranges (IIN) and lengths. */
|
|
21
|
+
const BRANDS = [
|
|
22
|
+
{
|
|
23
|
+
prefix: /^4/,
|
|
24
|
+
lengths: [
|
|
25
|
+
13,
|
|
26
|
+
16,
|
|
27
|
+
19
|
|
28
|
+
]
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
prefix: /^(?:5[1-5]|222[1-9]|22[3-9]\d|2[3-6]\d\d|27[01]\d|2720)/,
|
|
32
|
+
lengths: [16]
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
prefix: /^3[47]/,
|
|
36
|
+
lengths: [15]
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
prefix: /^(?:6011|65|64[4-9])/,
|
|
40
|
+
lengths: [
|
|
41
|
+
16,
|
|
42
|
+
17,
|
|
43
|
+
18,
|
|
44
|
+
19
|
|
45
|
+
]
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
prefix: /^35(?:2[89]|[3-8]\d)/,
|
|
49
|
+
lengths: [
|
|
50
|
+
16,
|
|
51
|
+
17,
|
|
52
|
+
18,
|
|
53
|
+
19
|
|
54
|
+
]
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
prefix: /^3(?:0[0-5]|[689])/,
|
|
58
|
+
lengths: [
|
|
59
|
+
14,
|
|
60
|
+
15,
|
|
61
|
+
16,
|
|
62
|
+
17,
|
|
63
|
+
18,
|
|
64
|
+
19
|
|
65
|
+
]
|
|
66
|
+
},
|
|
67
|
+
{
|
|
68
|
+
prefix: /^62/,
|
|
69
|
+
lengths: [
|
|
70
|
+
16,
|
|
71
|
+
17,
|
|
72
|
+
18,
|
|
73
|
+
19
|
|
74
|
+
]
|
|
75
|
+
}
|
|
76
|
+
];
|
|
77
|
+
/**
|
|
78
|
+
* Whether `candidate` is a card number: a known brand's range and length, a valid Luhn
|
|
79
|
+
* checksum, and separators (spaces or dashes) used the way cards print them: none, or one
|
|
80
|
+
* kind in groups of 4 (Amex: 4-6-5).
|
|
81
|
+
*/
|
|
82
|
+
function isCardNumber(candidate) {
|
|
83
|
+
const digits = candidate.replace(/[ -]/g, "");
|
|
84
|
+
const separators = new Set(candidate.replace(/\d/g, ""));
|
|
85
|
+
if (separators.size > 1) return false;
|
|
86
|
+
if (separators.size === 1) {
|
|
87
|
+
const groups = candidate.split(/[ -]/).map((group) => group.length);
|
|
88
|
+
const fours = groups.slice(0, -1).every((length) => length === 4) && groups[groups.length - 1] <= 4;
|
|
89
|
+
const amex = groups.join("-") === "4-6-5";
|
|
90
|
+
if (!fours && !amex) return false;
|
|
91
|
+
}
|
|
92
|
+
if (/^(\d)\1+$/.test(digits)) return false;
|
|
93
|
+
return BRANDS.some((brand) => brand.prefix.test(digits) && brand.lengths.includes(digits.length)) && luhn(digits);
|
|
94
|
+
}
|
|
95
|
+
/** IBAN lengths by country (ISO 13616 registry), for the countries that use one. */
|
|
96
|
+
const IBAN_LENGTHS = {
|
|
97
|
+
AD: 24,
|
|
98
|
+
AE: 23,
|
|
99
|
+
AL: 28,
|
|
100
|
+
AT: 20,
|
|
101
|
+
AZ: 28,
|
|
102
|
+
BA: 20,
|
|
103
|
+
BE: 16,
|
|
104
|
+
BG: 22,
|
|
105
|
+
BH: 22,
|
|
106
|
+
BR: 29,
|
|
107
|
+
BY: 28,
|
|
108
|
+
CH: 21,
|
|
109
|
+
CR: 22,
|
|
110
|
+
CY: 28,
|
|
111
|
+
CZ: 24,
|
|
112
|
+
DE: 22,
|
|
113
|
+
DK: 18,
|
|
114
|
+
DO: 28,
|
|
115
|
+
EE: 20,
|
|
116
|
+
EG: 29,
|
|
117
|
+
ES: 24,
|
|
118
|
+
FI: 18,
|
|
119
|
+
FO: 18,
|
|
120
|
+
FR: 27,
|
|
121
|
+
GB: 22,
|
|
122
|
+
GE: 22,
|
|
123
|
+
GI: 23,
|
|
124
|
+
GL: 18,
|
|
125
|
+
GR: 27,
|
|
126
|
+
GT: 28,
|
|
127
|
+
HR: 21,
|
|
128
|
+
HU: 28,
|
|
129
|
+
IE: 22,
|
|
130
|
+
IL: 23,
|
|
131
|
+
IQ: 23,
|
|
132
|
+
IS: 26,
|
|
133
|
+
IT: 27,
|
|
134
|
+
JO: 30,
|
|
135
|
+
KW: 30,
|
|
136
|
+
KZ: 20,
|
|
137
|
+
LB: 28,
|
|
138
|
+
LC: 32,
|
|
139
|
+
LI: 21,
|
|
140
|
+
LT: 20,
|
|
141
|
+
LU: 20,
|
|
142
|
+
LV: 21,
|
|
143
|
+
MC: 27,
|
|
144
|
+
MD: 24,
|
|
145
|
+
ME: 22,
|
|
146
|
+
MK: 19,
|
|
147
|
+
MR: 27,
|
|
148
|
+
MT: 31,
|
|
149
|
+
MU: 30,
|
|
150
|
+
NL: 18,
|
|
151
|
+
NO: 15,
|
|
152
|
+
PK: 24,
|
|
153
|
+
PL: 28,
|
|
154
|
+
PS: 29,
|
|
155
|
+
PT: 25,
|
|
156
|
+
QA: 29,
|
|
157
|
+
RO: 24,
|
|
158
|
+
RS: 22,
|
|
159
|
+
SA: 24,
|
|
160
|
+
SC: 31,
|
|
161
|
+
SE: 24,
|
|
162
|
+
SI: 19,
|
|
163
|
+
SK: 24,
|
|
164
|
+
SM: 27,
|
|
165
|
+
ST: 25,
|
|
166
|
+
SV: 28,
|
|
167
|
+
TL: 23,
|
|
168
|
+
TN: 24,
|
|
169
|
+
TR: 26,
|
|
170
|
+
UA: 29,
|
|
171
|
+
VA: 22,
|
|
172
|
+
VG: 24,
|
|
173
|
+
XK: 20
|
|
174
|
+
};
|
|
175
|
+
/** Whether `candidate` (spaces allowed) is an IBAN: its country's length and a valid mod-97 checksum. */
|
|
176
|
+
function isIban(candidate) {
|
|
177
|
+
const iban = candidate.replace(/ /g, "");
|
|
178
|
+
if (IBAN_LENGTHS[iban.slice(0, 2)] !== iban.length) return false;
|
|
179
|
+
const rearranged = iban.slice(4) + iban.slice(0, 4);
|
|
180
|
+
let remainder = 0;
|
|
181
|
+
for (const char of rearranged) {
|
|
182
|
+
const code = char.charCodeAt(0);
|
|
183
|
+
const value = code >= 65 ? code - 55 : code - 48;
|
|
184
|
+
remainder = (value > 9 ? remainder * 100 + value : remainder * 10 + value) % 97;
|
|
185
|
+
}
|
|
186
|
+
return remainder === 1;
|
|
187
|
+
}
|
|
188
|
+
/** Shannon entropy of `text`, in bits per character. */
|
|
189
|
+
function entropy(text) {
|
|
190
|
+
const counts = /* @__PURE__ */ new Map();
|
|
191
|
+
for (const char of text) counts.set(char, (counts.get(char) ?? 0) + 1);
|
|
192
|
+
let bits = 0;
|
|
193
|
+
for (const count of counts.values()) {
|
|
194
|
+
const p = count / text.length;
|
|
195
|
+
bits -= p * Math.log2(p);
|
|
196
|
+
}
|
|
197
|
+
return bits;
|
|
198
|
+
}
|
|
199
|
+
/** Values that stand in for a secret in examples and templates, never a secret themselves. */
|
|
200
|
+
const PLACEHOLDER = /^(?: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;
|
|
201
|
+
/** A reference to another value, not a value: `process.env.TOKEN`, `config.api.key`. */
|
|
202
|
+
const REFERENCE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/;
|
|
203
|
+
/** Whether `value` looks like a real secret: random enough, and not a placeholder or a reference. */
|
|
204
|
+
function looksSecret(value, minEntropy) {
|
|
205
|
+
return !PLACEHOLDER.test(value) && !REFERENCE.test(value) && entropy(value) >= minEntropy;
|
|
206
|
+
}
|
|
207
|
+
/** Whether the first part of a JWT decodes to a JSON header with an algorithm. */
|
|
208
|
+
function isJwtHeader(part) {
|
|
209
|
+
if (typeof atob !== "function") return true;
|
|
210
|
+
try {
|
|
211
|
+
const base64 = part.replace(/-/g, "+").replace(/_/g, "/");
|
|
212
|
+
const header = JSON.parse(atob(base64 + "=".repeat((4 - base64.length % 4) % 4)));
|
|
213
|
+
return typeof header === "object" && header !== null && typeof header.alg === "string";
|
|
214
|
+
} catch {
|
|
215
|
+
return false;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
//#endregion
|
|
219
|
+
//#region src/secrets/rules.ts
|
|
220
|
+
const high = (secret) => ({
|
|
221
|
+
confidence: "high",
|
|
222
|
+
length: secret.length
|
|
223
|
+
});
|
|
224
|
+
const medium = (secret) => ({
|
|
225
|
+
confidence: "medium",
|
|
226
|
+
length: secret.length
|
|
227
|
+
});
|
|
228
|
+
/** Start of a token: the start of the text, or a character that can't be part of one. */
|
|
229
|
+
const B = "(^|[^A-Za-z0-9_])";
|
|
230
|
+
/** After a token: nothing that could continue it. */
|
|
231
|
+
const E = "(?![A-Za-z0-9_])";
|
|
232
|
+
const token = (kind, body, keep, options = {}) => ({
|
|
233
|
+
kind,
|
|
234
|
+
pattern: new RegExp(`${B}(${body})${options.end ?? E}`, `g${options.flags ?? ""}`),
|
|
235
|
+
group: 2,
|
|
236
|
+
keep,
|
|
237
|
+
tail: true,
|
|
238
|
+
check: options.confidence === "medium" ? medium : high
|
|
239
|
+
});
|
|
240
|
+
/** A name, an assignment (`=`, `:`, `=>`, `:=`) and a value: `API_KEY="..."`, `"password": "..."`. */
|
|
241
|
+
const ASSIGNMENT = /(^|[^A-Za-z0-9_])(["']?([A-Za-z_][A-Za-z0-9_.-]{0,63})["']?\s{0,8}(?:=>|:=|[:=])\s{0,8}["'`]?)([^\s"'`,;()[\]{}<>]{8,200})/g;
|
|
242
|
+
/** Names that hold secrets, at the end of the name: `password`, `GITHUB_TOKEN`, `db.apiKey`. */
|
|
243
|
+
const SECRET_NAME = /(?:pass(?:word|wd|phrase)?|pwd|secret|token|api[_.-]?key|access[_.-]?key|private[_.-]?key|auth[_.-]?key|credentials?|client[_.-]?secret|signing[_.-]?key)$/i;
|
|
244
|
+
/**
|
|
245
|
+
* A card number, grouped as cards print it or not. The last group is tried without itself
|
|
246
|
+
* too: what follows a card is often more digits (`4242 4242 4242 4242 12/26`, a date).
|
|
247
|
+
*/
|
|
248
|
+
function card(candidate) {
|
|
249
|
+
if (isCardNumber(candidate)) return {
|
|
250
|
+
confidence: /[ -]/.test(candidate) ? "high" : "medium",
|
|
251
|
+
length: candidate.length
|
|
252
|
+
};
|
|
253
|
+
const cut = candidate.search(/[ -]\d{1,4}$/);
|
|
254
|
+
return cut !== -1 && isCardNumber(candidate.slice(0, cut)) ? {
|
|
255
|
+
confidence: "high",
|
|
256
|
+
length: cut
|
|
257
|
+
} : null;
|
|
258
|
+
}
|
|
259
|
+
/** An IBAN, cut to its country's length: what follows (a BIC, a word) is not part of it. */
|
|
260
|
+
function iban(candidate) {
|
|
261
|
+
let letters = 0;
|
|
262
|
+
for (let index = 0; index < candidate.length; index += 1) {
|
|
263
|
+
if (candidate[index] !== " ") letters += 1;
|
|
264
|
+
if (letters >= 15 && (index + 1 === candidate.length || candidate[index + 1] === " ") && isIban(candidate.slice(0, index + 1))) return {
|
|
265
|
+
confidence: "high",
|
|
266
|
+
length: index + 1
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
return null;
|
|
270
|
+
}
|
|
271
|
+
/** Rules in priority order: when findings overlap, the earlier rule's finding is kept. */
|
|
272
|
+
const RULES = [
|
|
273
|
+
token("aws-access-key-id", "(?:AKIA|ASIA|ABIA|ACCA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|APKA)[A-Z2-7]{16}", 4),
|
|
274
|
+
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)),
|
|
275
|
+
token("gitlab-token", "glpat-[A-Za-z0-9_-]{20,64}", 6, { end: "(?![A-Za-z0-9_-])" }),
|
|
276
|
+
token("slack-webhook", "https://hooks\\.slack\\.com/services/[A-Z0-9]{8,12}/[A-Z0-9]{8,12}/[A-Za-z0-9]{24}", 33),
|
|
277
|
+
token("slack-token", "xox[abposr]-[A-Za-z0-9-]{10,250}", 5, { end: "(?![A-Za-z0-9-])" }),
|
|
278
|
+
token("stripe-key", "(?:sk|rk)_live_[A-Za-z0-9]{24,247}", 8),
|
|
279
|
+
token("google-api-key", "AIza[A-Za-z0-9_-]{35}", 4, { end: "(?![A-Za-z0-9_-])" }),
|
|
280
|
+
token("npm-token", "npm_[A-Za-z0-9]{36}", 4),
|
|
281
|
+
token("pypi-token", "pypi-AgEIcHlwaS5vcmc[A-Za-z0-9_-]{50,1000}", 5, { end: "(?![A-Za-z0-9_-])" }),
|
|
282
|
+
token("sendgrid-key", "SG\\.[A-Za-z0-9_-]{22}\\.[A-Za-z0-9_-]{43}", 3, { end: "(?![A-Za-z0-9_-])" }),
|
|
283
|
+
{
|
|
284
|
+
kind: "jwt",
|
|
285
|
+
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,
|
|
286
|
+
group: 2,
|
|
287
|
+
keep: 3,
|
|
288
|
+
tail: true,
|
|
289
|
+
check: (secret) => isJwtHeader(secret.slice(0, secret.indexOf("."))) ? high(secret) : null
|
|
290
|
+
},
|
|
291
|
+
{
|
|
292
|
+
kind: "azure-storage-key",
|
|
293
|
+
pattern: /(^|[;\s"'])(AccountKey\s{0,4}=\s{0,4})([A-Za-z0-9+/]{86}==)/gi,
|
|
294
|
+
group: 3,
|
|
295
|
+
keep: 0,
|
|
296
|
+
tail: false,
|
|
297
|
+
check: high
|
|
298
|
+
},
|
|
299
|
+
{
|
|
300
|
+
kind: "url-credentials",
|
|
301
|
+
pattern: /((?:^|[^A-Za-z0-9+.-])[A-Za-z][A-Za-z0-9+.-]{1,30}:\/\/[^\s:/?#@]{0,256}:)([^\s/?#@]{1,256})(?=@)/g,
|
|
302
|
+
group: 2,
|
|
303
|
+
keep: 0,
|
|
304
|
+
tail: false,
|
|
305
|
+
check: (secret) => looksSecret(secret, 0) ? high(secret) : null
|
|
306
|
+
},
|
|
307
|
+
{
|
|
308
|
+
kind: "connection-string",
|
|
309
|
+
pattern: /(;\s{0,4}(?:password|pwd)\s{0,4}=\s{0,4})([^;'"\s]{1,256})/gi,
|
|
310
|
+
group: 2,
|
|
311
|
+
keep: 0,
|
|
312
|
+
tail: false,
|
|
313
|
+
check: (secret) => looksSecret(secret, 0) ? high(secret) : null
|
|
314
|
+
},
|
|
315
|
+
token("twilio-key", "SK[0-9a-fA-F]{32}", 2, { confidence: "medium" }),
|
|
316
|
+
{
|
|
317
|
+
kind: "card-number",
|
|
318
|
+
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,
|
|
319
|
+
group: 2,
|
|
320
|
+
keep: 0,
|
|
321
|
+
tail: true,
|
|
322
|
+
check: card,
|
|
323
|
+
retry: true
|
|
324
|
+
},
|
|
325
|
+
{
|
|
326
|
+
kind: "iban",
|
|
327
|
+
pattern: /(^|[^A-Za-z0-9])([A-Z]{2}\d{2}(?: ?[A-Z0-9]){11,40})(?![A-Za-z0-9])/g,
|
|
328
|
+
group: 2,
|
|
329
|
+
keep: 2,
|
|
330
|
+
tail: true,
|
|
331
|
+
check: iban,
|
|
332
|
+
retry: true
|
|
333
|
+
},
|
|
334
|
+
{
|
|
335
|
+
kind: "generic-secret",
|
|
336
|
+
pattern: ASSIGNMENT,
|
|
337
|
+
group: 4,
|
|
338
|
+
keep: 0,
|
|
339
|
+
tail: false,
|
|
340
|
+
check: (secret, match) => {
|
|
341
|
+
const name = match[3];
|
|
342
|
+
if (/^[A-Za-z0-9/+]{40}$/.test(secret) && /aws/i.test(name) && /secret/i.test(name)) return {
|
|
343
|
+
kind: "aws-secret-access-key",
|
|
344
|
+
confidence: "medium",
|
|
345
|
+
length: secret.length
|
|
346
|
+
};
|
|
347
|
+
return SECRET_NAME.test(name) && looksSecret(secret, 3) ? medium(secret) : null;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
];
|
|
351
|
+
/** `-----BEGIN ... PRIVATE KEY-----`, through its `END` line (or the end of the text, when cut off). */
|
|
352
|
+
const PRIVATE_KEY = /-----BEGIN (?:[A-Z0-9]{1,16} ){0,3}PRIVATE KEY(?: BLOCK)?-----/g;
|
|
353
|
+
//#endregion
|
|
354
|
+
//#region src/secrets/types.ts
|
|
355
|
+
/** People-facing names of the kinds, for messages and redaction marks. */
|
|
356
|
+
const SECRET_LABELS = Object.freeze({
|
|
357
|
+
"private-key": "private key",
|
|
358
|
+
"aws-access-key-id": "AWS access key ID",
|
|
359
|
+
"aws-secret-access-key": "AWS secret access key",
|
|
360
|
+
"github-token": "GitHub token",
|
|
361
|
+
"gitlab-token": "GitLab token",
|
|
362
|
+
"slack-token": "Slack token",
|
|
363
|
+
"slack-webhook": "Slack webhook URL",
|
|
364
|
+
"stripe-key": "Stripe live key",
|
|
365
|
+
"google-api-key": "Google API key",
|
|
366
|
+
"npm-token": "npm token",
|
|
367
|
+
"pypi-token": "PyPI token",
|
|
368
|
+
"sendgrid-key": "SendGrid API key",
|
|
369
|
+
"twilio-key": "Twilio API key",
|
|
370
|
+
"azure-storage-key": "Azure storage key",
|
|
371
|
+
jwt: "JSON Web Token",
|
|
372
|
+
"url-credentials": "password in a URL",
|
|
373
|
+
"connection-string": "password in a connection string",
|
|
374
|
+
"card-number": "card number",
|
|
375
|
+
iban: "IBAN",
|
|
376
|
+
"generic-secret": "secret"
|
|
377
|
+
});
|
|
378
|
+
/** Every kind, in a stable order. */
|
|
379
|
+
const SECRET_KINDS = Object.freeze(Object.keys(SECRET_LABELS));
|
|
380
|
+
//#endregion
|
|
381
|
+
//#region src/secrets/scan.ts
|
|
382
|
+
/** Longest text scanned, in characters. Default 1,000,000; the rest is not scanned (`truncated`). */
|
|
383
|
+
const DEFAULT_SECRET_SCAN_LENGTH = 1e6;
|
|
384
|
+
/** A preview of `secret` safe to show: a known prefix and, where allowed, the last 4 characters. */
|
|
385
|
+
function mask(kind, secret, keep, tail) {
|
|
386
|
+
if (kind === "private-key") return "-----BEGIN … PRIVATE KEY-----";
|
|
387
|
+
const compact = kind === "card-number" || kind === "iban" ? secret.replace(/[ -]/g, "") : secret;
|
|
388
|
+
if (kind === "card-number") return `\u2022\u2022\u2022\u2022 ${compact.slice(-4)}`;
|
|
389
|
+
if (!tail) return "•".repeat(8);
|
|
390
|
+
return compact.length - keep < 12 ? `${compact.slice(0, keep)}\u2026` : `${compact.slice(0, keep)}\u2026${compact.slice(-4)}`;
|
|
391
|
+
}
|
|
392
|
+
function finding(kind, confidence, start, secret, keep, tail, priority) {
|
|
393
|
+
return {
|
|
394
|
+
kind,
|
|
395
|
+
label: SECRET_LABELS[kind],
|
|
396
|
+
confidence,
|
|
397
|
+
start,
|
|
398
|
+
end: start + secret.length,
|
|
399
|
+
masked: mask(kind, secret, keep, tail),
|
|
400
|
+
priority
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
/** Private keys: from their `BEGIN` line to their `END` line, or to the end of the text when it is cut off. */
|
|
404
|
+
function privateKeys(text) {
|
|
405
|
+
const found = [];
|
|
406
|
+
for (const match of text.matchAll(PRIVATE_KEY)) {
|
|
407
|
+
const start = match.index;
|
|
408
|
+
const endLine = /-----END [A-Z0-9 ]{0,80}-----/g;
|
|
409
|
+
endLine.lastIndex = start + match[0].length;
|
|
410
|
+
const end = endLine.exec(text);
|
|
411
|
+
const stop = end === null ? text.length : end.index + end[0].length;
|
|
412
|
+
found.push(finding("private-key", "high", start, text.slice(start, stop), 0, false, -1));
|
|
413
|
+
}
|
|
414
|
+
return found;
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Finds secrets in `text`: keys and tokens of services by their documented formats, private
|
|
418
|
+
* keys, passwords in URLs and connection strings, card numbers and IBANs by their checksums,
|
|
419
|
+
* and random-looking values assigned to names such as `password` or `api_key`.
|
|
420
|
+
*
|
|
421
|
+
* Findings say where each secret is and what kind it is, with a masked preview; they never
|
|
422
|
+
* hold the secret. Every pattern runs in linear time, so any text is safe to scan. Works
|
|
423
|
+
* anywhere, including servers.
|
|
424
|
+
*
|
|
425
|
+
* @example
|
|
426
|
+
* const { findings } = scanSecrets(pastedText);
|
|
427
|
+
* if (findings.length > 0) warn(`This contains a ${findings[0].label}.`);
|
|
428
|
+
*
|
|
429
|
+
* @throws {CopyFailure} `invalid-payload` for an unknown kind or a negative `maxLength`.
|
|
430
|
+
*/
|
|
431
|
+
function scanSecrets(text, options = {}) {
|
|
432
|
+
const kinds = new Set(options.kinds ?? SECRET_KINDS);
|
|
433
|
+
for (const kind of kinds) if (!SECRET_KINDS.includes(kind)) throw require_errors.copyFailure("invalid-payload", `Unknown secret kind: ${kind}.`);
|
|
434
|
+
const maxLength = options.maxLength ?? 1e6;
|
|
435
|
+
if (!(maxLength >= 0)) throw require_errors.copyFailure("invalid-payload", "maxLength must be a number of at least 0.");
|
|
436
|
+
const scanned = text.length > maxLength ? text.slice(0, maxLength) : text;
|
|
437
|
+
const highOnly = options.minConfidence === "high";
|
|
438
|
+
const candidates = kinds.has("private-key") ? privateKeys(scanned) : [];
|
|
439
|
+
RULES.forEach((rule, priority) => {
|
|
440
|
+
if (!kinds.has(rule.kind) && !(rule.kind === "generic-secret" && kinds.has("aws-secret-access-key"))) return;
|
|
441
|
+
const pattern = rule.pattern;
|
|
442
|
+
pattern.lastIndex = 0;
|
|
443
|
+
for (let match = pattern.exec(scanned); match !== null; match = pattern.exec(scanned)) {
|
|
444
|
+
const secret = match[rule.group];
|
|
445
|
+
const start = match.index + match[0].length - secret.length;
|
|
446
|
+
const verdict = rule.check(secret, match);
|
|
447
|
+
const kind = verdict?.kind ?? rule.kind;
|
|
448
|
+
if (verdict === null || !kinds.has(kind)) {
|
|
449
|
+
if (rule.retry === true) pattern.lastIndex = start + 1;
|
|
450
|
+
continue;
|
|
451
|
+
}
|
|
452
|
+
const value = secret.slice(0, verdict.length);
|
|
453
|
+
const keep = typeof rule.keep === "number" ? rule.keep : rule.keep(value);
|
|
454
|
+
candidates.push(finding(kind, verdict.confidence, start, value, keep, rule.tail, priority));
|
|
455
|
+
pattern.lastIndex = start + verdict.length;
|
|
456
|
+
}
|
|
457
|
+
});
|
|
458
|
+
candidates.sort((a, b) => a.start - b.start || a.priority - b.priority);
|
|
459
|
+
const findings = [];
|
|
460
|
+
let reached = 0;
|
|
461
|
+
for (const candidate of candidates) {
|
|
462
|
+
if (highOnly && candidate.confidence !== "high" || candidate.start < reached) continue;
|
|
463
|
+
const { kind, label, confidence, start, end, masked } = candidate;
|
|
464
|
+
findings.push({
|
|
465
|
+
kind,
|
|
466
|
+
label,
|
|
467
|
+
confidence,
|
|
468
|
+
start,
|
|
469
|
+
end,
|
|
470
|
+
masked
|
|
471
|
+
});
|
|
472
|
+
reached = end;
|
|
473
|
+
}
|
|
474
|
+
return {
|
|
475
|
+
findings,
|
|
476
|
+
truncated: scanned.length < text.length
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
//#endregion
|
|
480
|
+
//#region src/secrets/redact.ts
|
|
481
|
+
const defaultReplace = (finding) => `[redacted ${finding.label}]`;
|
|
482
|
+
/**
|
|
483
|
+
* `text` with every secret {@link scanSecrets} finds replaced, by default with
|
|
484
|
+
* `[redacted <label>]`. Text past `maxLength` is dropped, never passed on unscanned.
|
|
485
|
+
*
|
|
486
|
+
* @example
|
|
487
|
+
* redactSecrets('token: ghp_...').text; // 'token: [redacted GitHub token]'
|
|
488
|
+
*/
|
|
489
|
+
function redactSecrets(text, options = {}) {
|
|
490
|
+
const { findings, truncated } = scanSecrets(text, options);
|
|
491
|
+
const replace = options.replace ?? defaultReplace;
|
|
492
|
+
let out = "";
|
|
493
|
+
let at = 0;
|
|
494
|
+
for (const finding of findings) {
|
|
495
|
+
out += text.slice(at, finding.start) + replace(finding);
|
|
496
|
+
at = finding.end;
|
|
497
|
+
}
|
|
498
|
+
const end = truncated ? options.maxLength : text.length;
|
|
499
|
+
return {
|
|
500
|
+
text: out + text.slice(at, end),
|
|
501
|
+
findings,
|
|
502
|
+
truncated
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* A transform for `useCopyInterceptor` and `registerCopyInterceptor`: when what people copy
|
|
507
|
+
* from your page (logs, settings, a support console) holds secrets, the clipboard gets the
|
|
508
|
+
* text with them redacted; other copies are left to the browser. The redacted copy is
|
|
509
|
+
* plain text: formatting around a secret could carry it too.
|
|
510
|
+
*
|
|
511
|
+
* @example
|
|
512
|
+
* useCopyInterceptor(logViewerRef, { transform: secretRedactor() });
|
|
513
|
+
*/
|
|
514
|
+
function secretRedactor(options = {}) {
|
|
515
|
+
return (selection) => {
|
|
516
|
+
const redacted = redactSecrets(selection.text, options);
|
|
517
|
+
return redacted.findings.length === 0 && !redacted.truncated ? null : redacted.text;
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
//#endregion
|
|
521
|
+
//#region src/secrets/paste.ts
|
|
522
|
+
/**
|
|
523
|
+
* A paste handler that keeps secrets out of a field: chat boxes, comments, tickets and
|
|
524
|
+
* forms where an API key or a password pasted by mistake would be seen or stored. A paste
|
|
525
|
+
* without secrets is left to the browser.
|
|
526
|
+
*
|
|
527
|
+
* @example
|
|
528
|
+
* <textarea onPaste={(event) => pasteWithoutSecrets(event, { onSecrets: (found) => toast(`Removed a ${found[0].label}.`) })} />
|
|
529
|
+
*/
|
|
530
|
+
function pasteWithoutSecrets(event, options = {}) {
|
|
531
|
+
if (event.defaultPrevented || event.clipboardData === null) return "clean";
|
|
532
|
+
const text = event.clipboardData.getData("text/plain");
|
|
533
|
+
if (text === "") return "clean";
|
|
534
|
+
const redacted = redactSecrets(text, options);
|
|
535
|
+
if (redacted.findings.length === 0 && !redacted.truncated) return "clean";
|
|
536
|
+
event.preventDefault();
|
|
537
|
+
const field = require_text_field.asTextField(event.currentTarget) ?? require_text_field.asTextField(event.target);
|
|
538
|
+
const outcome = options.action !== "block" && field !== null && require_text_field.insertText(field, redacted.text) ? "redacted" : "blocked";
|
|
539
|
+
options.onSecrets?.(redacted.findings, outcome);
|
|
540
|
+
return outcome;
|
|
541
|
+
}
|
|
542
|
+
//#endregion
|
|
543
|
+
exports.DEFAULT_SECRET_SCAN_LENGTH = DEFAULT_SECRET_SCAN_LENGTH;
|
|
544
|
+
exports.SECRET_KINDS = SECRET_KINDS;
|
|
545
|
+
exports.SECRET_LABELS = SECRET_LABELS;
|
|
546
|
+
exports.pasteWithoutSecrets = pasteWithoutSecrets;
|
|
547
|
+
exports.redactSecrets = redactSecrets;
|
|
548
|
+
exports.scanSecrets = scanSecrets;
|
|
549
|
+
exports.secretRedactor = secretRedactor;
|
|
550
|
+
|
|
551
|
+
//# sourceMappingURL=secrets.cjs.map
|