react-smart-copy 1.20.0 → 1.22.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 CHANGED
@@ -33,6 +33,8 @@ 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
37
+ - **`react-smart-copy/otp`** and **`useOtpField`**: one-time code fields that typing, pasting a whole SMS, SMS autofill and WebOTP fill, with an accessible name on every box, and `extractOtp` to read the code in a message while leaving prices, dates, phone numbers and order numbers alone
36
38
  - **`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
39
  - **`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
40
  - **`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 +949,114 @@ that names the file by its safe name. Checking files in the browser is for the p
947
949
  using your app: check them again on your server, where `inspectFile` works the same, and
948
950
  serve uploads with `Content-Disposition: attachment` and `X-Content-Type-Options: nosniff`.
949
951
 
952
+ ## Secrets: keep keys out of pastes and copies
953
+
954
+ `react-smart-copy/secrets` keeps secrets from travelling through the clipboard. It finds API
955
+ keys, tokens, private keys, passwords, card numbers and IBANs in text people paste or copy,
956
+ and redacts or blocks them: in a chat box, a support ticket, or a log someone copies from
957
+ your app. No dependencies, about 4.1 kB (about 3.3 kB for `scanSecrets` alone), and it works
958
+ the same on a server.
959
+
960
+ ```tsx
961
+ import { pasteWithoutSecrets } from "react-smart-copy/secrets";
962
+
963
+ <textarea
964
+ onPaste={(event) =>
965
+ pasteWithoutSecrets(event, {
966
+ // "redact" (the default) inserts the paste with each secret replaced; "block" inserts nothing.
967
+ action: "redact",
968
+ onSecrets: (found) => toast(`Removed a ${found[0].label} from your message.`),
969
+ })
970
+ }
971
+ />
972
+ ```
973
+
974
+ **What it finds.** Each finding has a kind, a confidence, and a masked preview.
975
+
976
+ - **Service keys and tokens, by their documented formats:** AWS access key IDs, GitHub
977
+ (classic and fine-grained), GitLab, Slack tokens and webhooks, Stripe live keys, Google API
978
+ keys, npm, PyPI, SendGrid, Twilio, Azure storage keys, and JSON Web Tokens (whose
979
+ header must decode).
980
+ - **Private keys** (PEM and OpenSSH), from their `BEGIN` line to their `END` line.
981
+ - **Passwords inside other text:** in URLs (`postgres://app:password@db`) and in connection
982
+ strings (`;Password=...`).
983
+ - **Card numbers and IBANs, by checksum:** Luhn plus the card brand's ranges and lengths,
984
+ and mod-97 plus the country's IBAN length.
985
+ - **Random-looking values assigned to secret names:** `API_KEY="..."`, `"password": "..."`,
986
+ `client_secret: ...`, including an AWS secret key next to its name. Placeholders
987
+ (`changeme`, `<token>`, `${TOKEN}`) and references (`process.env.TOKEN`) are left alone.
988
+
989
+ **Safe to run on anything.** Every pattern runs in linear time: no nested quantifiers, no
990
+ lookbehind. Hostile text of hundreds of kilobytes is scanned in milliseconds. A finding never
991
+ holds the secret: it holds where the secret is (`start`, `end`), its `kind` and `label`, a
992
+ `confidence`, and `masked`. `masked` keeps at most a known prefix and the last 4 characters
993
+ (`ghp_` and the last 4, or `•••• 4242` for a card), and nothing at all for passwords. Text
994
+ past `maxLength` (1,000,000 characters) is not scanned, and `redactSecrets` drops it rather
995
+ than pass it on unchecked.
996
+
997
+ ```ts
998
+ import { redactSecrets, scanSecrets, secretRedactor } from "react-smart-copy/secrets";
999
+
1000
+ const { findings } = scanSecrets(text, { minConfidence: "high" });
1001
+ // [{ kind: "github-token", label: "GitHub token", confidence: "high", start: 13, end: 53, masked: "ghp_…a1B2" }]
1002
+
1003
+ redactSecrets("token=ghp_…").text; // "token=[redacted GitHub token]"
1004
+
1005
+ // Mask secrets in what people copy from a log viewer or an admin console.
1006
+ useCopyInterceptor(logRef, { transform: secretRedactor() });
1007
+ ```
1008
+
1009
+ | Option | Default | Notes |
1010
+ | --- | --- | --- |
1011
+ | `kinds` | every kind | the kinds to look for |
1012
+ | `minConfidence` | `"medium"` | `"high"` leaves out values that only look like secrets |
1013
+ | `maxLength` | 1,000,000 | characters scanned |
1014
+ | `replace` | `[redacted <label>]` | `redactSecrets`, `pasteWithoutSecrets` and `secretRedactor` |
1015
+ | `action` | `"redact"` | `pasteWithoutSecrets`: `"block"` inserts nothing |
1016
+ | `onSecrets` | | `pasteWithoutSecrets`: called with the findings and what was done |
1017
+
1018
+ A paste is redacted in a `<textarea>` or text `<input>`, with undo intact; anywhere else, a
1019
+ paste with secrets is blocked. Scanning in the browser protects the people using your app.
1020
+ Scan again on your server before you store or forward text, because `scanSecrets` works the
1021
+ same there.
1022
+
1023
+ ## One-time codes
1024
+
1025
+ `react-smart-copy/otp` handles the one-time codes people copy from an SMS or an e-mail.
1026
+ `extractOtp` finds the code in a message, and leaves prices, dates, times, phone numbers and
1027
+ order numbers alone. `useOtpField` (in the React entry) wires a row of single-character
1028
+ boxes: typing moves on, Backspace goes back, and pasting a whole message into any box fills
1029
+ them all. No dependencies, about 3.6 kB (about 2 kB for `extractOtp` alone).
1030
+
1031
+ ```tsx
1032
+ import { useOtpField } from "react-smart-copy";
1033
+
1034
+ const otp = useOtpField({ length: 6, onComplete: verify });
1035
+
1036
+ <div role="group" aria-label="Verification code">
1037
+ {Array.from({ length: 6 }, (_, index) => (
1038
+ <input key={index} {...otp.getInputProps(index)} />
1039
+ ))}
1040
+ </div>
1041
+ ```
1042
+
1043
+ - **SMS autofill** on iOS and Android (`autocomplete="one-time-code"` on the first box), and
1044
+ the **WebOTP API** with `webOtp: true`, cancelled when the boxes unmount or the code is typed.
1045
+ - **Every box is named** (`Digit 1 of 6`), numeric codes get the numeric keyboard, and the
1046
+ arrow keys, Home, End, Backspace and Delete work as people expect.
1047
+ - **`extractOtp`** reads codes on their own (`482 913`), origin-bound lines
1048
+ (`@example.com #482913`, refused for another `domain`), and numbers next to a word that
1049
+ names them in twenty languages, with digits of any script. Linear time, first 100,000
1050
+ characters.
1051
+
1052
+ ```ts
1053
+ import { extractOtp } from "react-smart-copy/otp";
1054
+
1055
+ extractOtp("Your verification code is 482913. It expires in 10 minutes.");
1056
+ // { code: "482913", source: "keyword", confidence: "high", domain: null }
1057
+ extractOtp("Your order 48291 of $1,249.00 ships on 24/10."); // null
1058
+ ```
1059
+
950
1060
  ## Copy links
951
1061
 
952
1062
  `react-smart-copy/link` is for "Copy link" and "Share" buttons, and for fields people
@@ -1765,6 +1875,8 @@ embedded webviews. Where a capability is missing you get a typed error, never a
1765
1875
  - ~~**1.18** One shared copy of the core across entry points: smaller bundles when you use several modules, and one `CopyFailure` class~~ shipped
1766
1876
  - ~~**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
1877
  - ~~**1.20** `react-smart-copy/files` — take pasted and dropped files and folders safely: types from content, risky files rejected, safe names, limits~~ shipped
1878
+ - ~~**1.21** `react-smart-copy/secrets` — find and redact API keys, tokens, private keys, passwords, cards and IBANs in pastes and copies~~ shipped
1879
+ - ~~**1.22** `react-smart-copy/otp` and `useOtpField` — one-time code fields filled by typing, pasting, SMS autofill and WebOTP, and codes read from pasted messages~~ shipped
1768
1880
 
1769
1881
  Full history: [CHANGELOG.md](./CHANGELOG.md) or the [Releases page](https://suprabhat02.github.io/react-smart-copy/project/releases/).
1770
1882
 
@@ -0,0 +1,87 @@
1
+
2
+ //#region src/otp/normalize.d.ts
3
+ /** What a one-time code is made of. */
4
+ type OtpAlphabet = 'numeric' | 'alphanumeric';
5
+ /**
6
+ * `text` with its digits in ASCII and, for alphanumeric codes, its letters in upper case:
7
+ * full-width digits and letters, and Arabic-Indic, Devanagari and other scripts' digits,
8
+ * become ASCII. Other characters are kept: callers decide what to drop.
9
+ */
10
+ declare function normalizeOtpText(text: string, alphabet: OtpAlphabet): string;
11
+ //#endregion
12
+ //#region src/otp/web-otp.d.ts
13
+ /**
14
+ * Where filling a code from an SMS (the WebOTP API) stands.
15
+ *
16
+ * - `idle`: not asked for.
17
+ * - `waiting`: the browser is waiting for an SMS that ends with `@your.host #code`.
18
+ * - `received`: it came, and filled the field.
19
+ * - `unsupported`: this browser has no WebOTP API (only Chrome on Android has).
20
+ * - `failed`: the browser refused or gave up (no permission, a timeout, an insecure page).
21
+ * - `aborted`: the field was detached before an SMS came.
22
+ */
23
+ type WebOtpStatus = 'idle' | 'waiting' | 'received' | 'unsupported' | 'failed' | 'aborted';
24
+ //#endregion
25
+ //#region src/otp/field.d.ts
26
+ interface OtpFieldOptions {
27
+ /** How many characters the code has: one box each. Default 6. */
28
+ readonly length?: number;
29
+ /** Default `'numeric'`. */
30
+ readonly alphabet?: OtpAlphabet;
31
+ /**
32
+ * Each box's accessible name. Default `Digit 1 of 6` (`Character 1 of 6` for alphanumeric
33
+ * codes). Name the group around the boxes too (`role="group"` with a label).
34
+ */
35
+ readonly label?: (index: number, length: number) => string;
36
+ /**
37
+ * Fill the code from an SMS with the WebOTP API, where the browser has it (Chrome on
38
+ * Android): the message must end with `@your.host #code`. Asked for when the boxes are
39
+ * attached; cancelled when they are detached, or when the code is typed. Default `false`.
40
+ */
41
+ readonly webOtp?: boolean;
42
+ /** Called when the value changes. */
43
+ readonly onChange?: (snapshot: OtpSnapshot) => void;
44
+ /** Called when every box is filled, with the code. Again after an edit fills them anew. */
45
+ readonly onComplete?: (code: string) => void;
46
+ }
47
+ interface OtpSnapshot {
48
+ /** Each box's character: `''` for an empty box. */
49
+ readonly chars: readonly string[];
50
+ /** The characters typed so far, in order, without gaps. */
51
+ readonly value: string;
52
+ /** Every box holds a character: `value` is the code. */
53
+ readonly complete: boolean;
54
+ /** Where filling the code from an SMS stands. `idle` unless `webOtp` is on. */
55
+ readonly webOtp: WebOtpStatus;
56
+ }
57
+ /** The field's functions are bound: pass them around freely (`onClick={field.clear}`). */
58
+ interface OtpField {
59
+ /**
60
+ * Wires up the boxes (one `<input>` each, in order): their typing, pasting, autofill,
61
+ * keys, focus and attributes. Returns a function that undoes it. Boxes are wired to one
62
+ * field at a time: attaching again first detaches the previous boxes.
63
+ */
64
+ readonly attach: (inputs: readonly HTMLInputElement[]) => () => void;
65
+ /** The current state. A new object after each change, the same one otherwise. */
66
+ readonly getSnapshot: () => OtpSnapshot;
67
+ /** Calls `listener` after each change. Returns a function that stops it. */
68
+ readonly subscribe: (listener: () => void) => () => void;
69
+ /** Fills the boxes with `code` from the first (characters a code can't have are dropped). */
70
+ readonly setValue: (code: string) => void;
71
+ /** Empties every box and focuses the first. */
72
+ readonly clear: () => void;
73
+ /** Focuses the first empty box (or the last, when all are filled). */
74
+ readonly focus: () => void;
75
+ }
76
+ /**
77
+ * A one-time code field over a row of single-character boxes, without a framework:
78
+ * typing moves to the next box, Backspace to the one before; pasting a code, or an SMS
79
+ * holding one, fills every box from any of them; an SMS autofill into the first box
80
+ * (iOS, Android) fills them all. `useOtpField` is this, for React.
81
+ *
82
+ * @throws {CopyFailure} `invalid-payload` for a `length` that is not 1 to 32.
83
+ */
84
+ declare function createOtpField(options?: OtpFieldOptions): OtpField;
85
+ //#endregion
86
+ export { WebOtpStatus as a, createOtpField as i, OtpFieldOptions as n, OtpAlphabet as o, OtpSnapshot as r, normalizeOtpText as s, OtpField as t };
87
+ //# sourceMappingURL=field-BTsKTs2M.d.cts.map
@@ -0,0 +1,87 @@
1
+
2
+ //#region src/otp/normalize.d.ts
3
+ /** What a one-time code is made of. */
4
+ type OtpAlphabet = 'numeric' | 'alphanumeric';
5
+ /**
6
+ * `text` with its digits in ASCII and, for alphanumeric codes, its letters in upper case:
7
+ * full-width digits and letters, and Arabic-Indic, Devanagari and other scripts' digits,
8
+ * become ASCII. Other characters are kept: callers decide what to drop.
9
+ */
10
+ declare function normalizeOtpText(text: string, alphabet: OtpAlphabet): string;
11
+ //#endregion
12
+ //#region src/otp/web-otp.d.ts
13
+ /**
14
+ * Where filling a code from an SMS (the WebOTP API) stands.
15
+ *
16
+ * - `idle`: not asked for.
17
+ * - `waiting`: the browser is waiting for an SMS that ends with `@your.host #code`.
18
+ * - `received`: it came, and filled the field.
19
+ * - `unsupported`: this browser has no WebOTP API (only Chrome on Android has).
20
+ * - `failed`: the browser refused or gave up (no permission, a timeout, an insecure page).
21
+ * - `aborted`: the field was detached before an SMS came.
22
+ */
23
+ type WebOtpStatus = 'idle' | 'waiting' | 'received' | 'unsupported' | 'failed' | 'aborted';
24
+ //#endregion
25
+ //#region src/otp/field.d.ts
26
+ interface OtpFieldOptions {
27
+ /** How many characters the code has: one box each. Default 6. */
28
+ readonly length?: number;
29
+ /** Default `'numeric'`. */
30
+ readonly alphabet?: OtpAlphabet;
31
+ /**
32
+ * Each box's accessible name. Default `Digit 1 of 6` (`Character 1 of 6` for alphanumeric
33
+ * codes). Name the group around the boxes too (`role="group"` with a label).
34
+ */
35
+ readonly label?: (index: number, length: number) => string;
36
+ /**
37
+ * Fill the code from an SMS with the WebOTP API, where the browser has it (Chrome on
38
+ * Android): the message must end with `@your.host #code`. Asked for when the boxes are
39
+ * attached; cancelled when they are detached, or when the code is typed. Default `false`.
40
+ */
41
+ readonly webOtp?: boolean;
42
+ /** Called when the value changes. */
43
+ readonly onChange?: (snapshot: OtpSnapshot) => void;
44
+ /** Called when every box is filled, with the code. Again after an edit fills them anew. */
45
+ readonly onComplete?: (code: string) => void;
46
+ }
47
+ interface OtpSnapshot {
48
+ /** Each box's character: `''` for an empty box. */
49
+ readonly chars: readonly string[];
50
+ /** The characters typed so far, in order, without gaps. */
51
+ readonly value: string;
52
+ /** Every box holds a character: `value` is the code. */
53
+ readonly complete: boolean;
54
+ /** Where filling the code from an SMS stands. `idle` unless `webOtp` is on. */
55
+ readonly webOtp: WebOtpStatus;
56
+ }
57
+ /** The field's functions are bound: pass them around freely (`onClick={field.clear}`). */
58
+ interface OtpField {
59
+ /**
60
+ * Wires up the boxes (one `<input>` each, in order): their typing, pasting, autofill,
61
+ * keys, focus and attributes. Returns a function that undoes it. Boxes are wired to one
62
+ * field at a time: attaching again first detaches the previous boxes.
63
+ */
64
+ readonly attach: (inputs: readonly HTMLInputElement[]) => () => void;
65
+ /** The current state. A new object after each change, the same one otherwise. */
66
+ readonly getSnapshot: () => OtpSnapshot;
67
+ /** Calls `listener` after each change. Returns a function that stops it. */
68
+ readonly subscribe: (listener: () => void) => () => void;
69
+ /** Fills the boxes with `code` from the first (characters a code can't have are dropped). */
70
+ readonly setValue: (code: string) => void;
71
+ /** Empties every box and focuses the first. */
72
+ readonly clear: () => void;
73
+ /** Focuses the first empty box (or the last, when all are filled). */
74
+ readonly focus: () => void;
75
+ }
76
+ /**
77
+ * A one-time code field over a row of single-character boxes, without a framework:
78
+ * typing moves to the next box, Backspace to the one before; pasting a code, or an SMS
79
+ * holding one, fills every box from any of them; an SMS autofill into the first box
80
+ * (iOS, Android) fills them all. `useOtpField` is this, for React.
81
+ *
82
+ * @throws {CopyFailure} `invalid-payload` for a `length` that is not 1 to 32.
83
+ */
84
+ declare function createOtpField(options?: OtpFieldOptions): OtpField;
85
+ //#endregion
86
+ export { WebOtpStatus as a, createOtpField as i, OtpFieldOptions as n, OtpAlphabet as o, OtpSnapshot as r, normalizeOtpText as s, OtpField as t };
87
+ //# sourceMappingURL=field-BTsKTs2M.d.ts.map