@mark1russell7/text 0.0.10 → 0.0.12
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 +41 -0
- package/build/english.d.ts +32 -0
- package/build/english.d.ts.map +1 -0
- package/build/english.js +35 -0
- package/build/english.js.map +1 -0
- package/build/index.d.ts +3 -15
- package/build/index.d.ts.map +1 -1
- package/build/index.js +1 -17
- package/build/index.js.map +1 -1
- package/build/redact.d.ts +30 -1
- package/build/redact.d.ts.map +1 -1
- package/build/redact.js +71 -6
- package/build/redact.js.map +1 -1
- package/package.json +6 -2
- package/src/english.ts +25 -1
- package/src/index.ts +1 -1
- package/src/redact.ts +84 -5
package/README.md
CHANGED
|
@@ -38,6 +38,19 @@ countOf(1024, "site"); // "1,024 sites"
|
|
|
38
38
|
countOf(3, "match", "matches"); // "3 matches"
|
|
39
39
|
```
|
|
40
40
|
|
|
41
|
+
`listOf(parts, options?)` joins the parts into an English list. A comma goes between the parts, and the conjunction goes before the last part. The option `conjunction` sets the word, and its default is "and". With the option `serialComma`, a comma also goes before the conjunction in a list of three parts or more.
|
|
42
|
+
|
|
43
|
+
The entry `@mark1russell7/text/english` has `listOf` and `countOf`. The root entry has only `countOf`, to keep its size.
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
import { listOf } from "@mark1russell7/text/english";
|
|
47
|
+
|
|
48
|
+
listOf([]); // ""
|
|
49
|
+
listOf(["a", "b"]); // "a and b"
|
|
50
|
+
listOf(["a", "b", "c"]); // "a, b and c"
|
|
51
|
+
listOf(["a", "b", "c"], { conjunction: "or", serialComma: true }); // "a, b, or c"
|
|
52
|
+
```
|
|
53
|
+
|
|
41
54
|
## A word search
|
|
42
55
|
|
|
43
56
|
`wordSearch(query)` gives a test of a text. A text agrees when it has each word of the search, in any order and in any case. A word can be a part of a longer word.
|
|
@@ -145,6 +158,32 @@ redactSecretShapes(answer); // "token: [secret]"
|
|
|
145
158
|
findSecretShapes("the prefix ghp_ in a sentence"); // []
|
|
146
159
|
```
|
|
147
160
|
|
|
161
|
+
### The shapes of a secret by its context
|
|
162
|
+
|
|
163
|
+
A password or a key of a service that is not in the table has no shape. Its context can still tell that it is a secret. The context is the name of a parameter, a flag, a field or a header, or the user part of a URL. `CONTEXT_SHAPES` has these shapes. A match is the value only, so the name stays. Use these shapes with `SECRET_SHAPES` on a log line or a command line. Do not use them to refuse a text, because they can match a text with no secret, for example `token: none`.
|
|
164
|
+
|
|
165
|
+
| Shape | What it finds |
|
|
166
|
+
| --- | --- |
|
|
167
|
+
| `secret-parameter` | The value after a name of a secret and `=` or `:`, for example `?access_token=v`, `GITHUB_TOKEN=v`, `"apiKey": "v"` and `X-Api-Key: v` |
|
|
168
|
+
| `secret-flag` | The value after a flag with a name of a secret and a space, for example `--password v`. A value that starts with `-`, `<`, `>` or `\|` is not a match |
|
|
169
|
+
| `url-password` | The password in `scheme://user:password@host` |
|
|
170
|
+
| `authorization` | The credential of an `Authorization` or `Proxy-Authorization` header, after its scheme |
|
|
171
|
+
| `user-password` | The password of `user:password` after the curl flag `-u`, `--user` or `--proxy-user` |
|
|
172
|
+
|
|
173
|
+
A name of a secret ends in one of these words, with no case: `token`, `secret`, `password`, `passwd`, `passphrase`, `credential`, `credentials`, `signature`, `sig` or `auth`. It can also end in `pwd` with one character before it. Or it can end in `key` after `api`, `access`, `secret`, `private`, `signing`, `encryption`, `master`, `license`, `ssh` or `client`. `key` alone is also a name. `isSecretName(name)` tells if a name agrees with this rule, for example the key of a field of a document.
|
|
174
|
+
|
|
175
|
+
A shape of your own can give the span of a part of its match: give the part a group with the name `secret`.
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
import { CONTEXT_SHAPES, isSecretName, redactSecretShapes, SECRET_SHAPES } from "@mark1russell7/text/redact";
|
|
179
|
+
|
|
180
|
+
const shapes = [...SECRET_SHAPES, ...CONTEXT_SHAPES];
|
|
181
|
+
redactSecretShapes("PGPASSWORD=hunter2 psql --token abc123", { shapes }); // "PGPASSWORD=[secret] psql --token [secret]"
|
|
182
|
+
redactSecretShapes("git clone https://user:p%40ss@example.com/r.git", { shapes }); // "git clone https://user:[secret]@example.com/r.git"
|
|
183
|
+
isSecretName("client_secret"); // true
|
|
184
|
+
isSecretName("PWD"); // false
|
|
185
|
+
```
|
|
186
|
+
|
|
148
187
|
## Lengths, truncation and padding
|
|
149
188
|
|
|
150
189
|
The entry `@mark1russell7/text/length` has three functions. Each function counts in the unit that you give. The default unit is `code-unit`.
|
|
@@ -245,9 +284,11 @@ The tests also examine 18 copies of a cut with a mark, from a later list of the
|
|
|
245
284
|
- `escapeMarkdown` does not change spaces. Four spaces at the start of a line make a code block.
|
|
246
285
|
- `wordSearch` keeps accents, so "cafe" does not find "café".
|
|
247
286
|
- `countOf` knows no irregular plural. Give the plural noun for each noun that does not add "s".
|
|
287
|
+
- `listOf` does not change the parts. A part with a comma makes a list that a reader cannot split again.
|
|
248
288
|
- `errorMessage` gives only the message. It does not add the name of the error, its `cause` or its stack.
|
|
249
289
|
- `redactSecrets` removes only the forms in its table. A secret in a JSON string with escapes, or in a different encoding, stays.
|
|
250
290
|
- `findSecretShapes` knows only the shapes in its table. A token directly after a letter or a digit is not a match. A token of a service that is not in the table stays.
|
|
291
|
+
- `CONTEXT_SHAPES` needs the name of a secret before the value. A value with a name that is not in the rule stays, and so does a quoted value that holds its own quote. A value with no quotes ends at a space, a quote, `&` or `#`.
|
|
251
292
|
- `textLength`, `truncate` and `pad` count graphemes with the `Intl.Segmenter` of the runtime. An old runtime can count a new emoji as more than one grapheme.
|
|
252
293
|
- In `pad`, a grapheme of the fill can join the text or the next copy of the fill. A combining mark and a lone regional indicator do this. Then the result has fewer graphemes than the width.
|
|
253
294
|
- `partsAt` counts in code units, as `String.prototype.slice` does. A range can cut a surrogate pair or a grapheme.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This module has the English word forms: a count with a noun, and a list of parts. It is the entry
|
|
3
|
+
* `@mark1russell7/text/english`. The root entry has only `countOf`.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* This function gives a count with a noun, for example "1 site" or "1,024 sites". Only the count 1 takes the singular
|
|
7
|
+
* noun. Each other count takes the plural noun, also 0 and -1. The count has the digit groups of English and at most
|
|
8
|
+
* three decimal places.
|
|
9
|
+
*
|
|
10
|
+
* @param count - The number of things.
|
|
11
|
+
* @param noun - The singular noun.
|
|
12
|
+
* @param plural - The plural noun. The default is the singular noun with the letter "s" at the end.
|
|
13
|
+
* @returns The count, a space and the noun.
|
|
14
|
+
*/
|
|
15
|
+
export declare function countOf(count: number, noun: string, plural?: string): string;
|
|
16
|
+
/** The options of `listOf`. */
|
|
17
|
+
export interface ListOptions {
|
|
18
|
+
/** The word before the last part. The default is "and". */
|
|
19
|
+
readonly conjunction?: string;
|
|
20
|
+
/** With true, a comma also goes before the conjunction in a list of three parts or more. The default is false. */
|
|
21
|
+
readonly serialComma?: boolean;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* This function joins the parts into an English list, for example "a", "a and b" or "a, b and c". A comma and a space go
|
|
25
|
+
* between the parts, and the conjunction goes before the last part. No part gives an empty text. The parts do not change.
|
|
26
|
+
*
|
|
27
|
+
* @param parts - The parts of the list, in their order.
|
|
28
|
+
* @param options - The conjunction and the serial comma.
|
|
29
|
+
* @returns The list as one text.
|
|
30
|
+
*/
|
|
31
|
+
export declare function listOf(parts: readonly string[], options?: ListOptions): string;
|
|
32
|
+
//# sourceMappingURL=english.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"english.d.ts","names":[],"sources":["../src/english.ts"],"mappings":";;;;;;;;;;;;;;wBAegB,QAAQ,eAAe,cAAc;;iBAKpC;;WAEN;;WAEA;;;;;;;;;;wBAWK,OAAO,0BAA0B,UAAS"}
|
package/build/english.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// src/english.ts
|
|
2
|
+
/**
|
|
3
|
+
* This module has the English word forms: a count with a noun, and a list of parts. It is the entry
|
|
4
|
+
* `@mark1russell7/text/english`. The root entry has only `countOf`.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* This function gives a count with a noun, for example "1 site" or "1,024 sites". Only the count 1 takes the singular
|
|
8
|
+
* noun. Each other count takes the plural noun, also 0 and -1. The count has the digit groups of English and at most
|
|
9
|
+
* three decimal places.
|
|
10
|
+
*
|
|
11
|
+
* @param count - The number of things.
|
|
12
|
+
* @param noun - The singular noun.
|
|
13
|
+
* @param plural - The plural noun. The default is the singular noun with the letter "s" at the end.
|
|
14
|
+
* @returns The count, a space and the noun.
|
|
15
|
+
*/
|
|
16
|
+
function countOf(count, noun, plural = `${noun}s`) {
|
|
17
|
+
return `${count.toLocaleString("en")} ${count === 1 ? noun : plural}`;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* This function joins the parts into an English list, for example "a", "a and b" or "a, b and c". A comma and a space go
|
|
21
|
+
* between the parts, and the conjunction goes before the last part. No part gives an empty text. The parts do not change.
|
|
22
|
+
*
|
|
23
|
+
* @param parts - The parts of the list, in their order.
|
|
24
|
+
* @param options - The conjunction and the serial comma.
|
|
25
|
+
* @returns The list as one text.
|
|
26
|
+
*/
|
|
27
|
+
function listOf(parts, options = {}) {
|
|
28
|
+
const { conjunction = "and", serialComma = false } = options;
|
|
29
|
+
if (parts.length < 2) return parts[0] ?? "";
|
|
30
|
+
const comma = serialComma && parts.length > 2 ? "," : "";
|
|
31
|
+
return `${parts.slice(0, -1).join(", ")}${comma} ${conjunction} ${parts[parts.length - 1]}`;
|
|
32
|
+
}
|
|
33
|
+
export { countOf, listOf };
|
|
34
|
+
|
|
35
|
+
//# sourceMappingURL=english.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"english.js","names":[],"sources":["../src/english.ts"],"sourcesContent":["/**\n * This module has the English word forms: a count with a noun, and a list of parts. It is the entry\n * `@mark1russell7/text/english`. The root entry has only `countOf`.\n */\n\n/**\n * This function gives a count with a noun, for example \"1 site\" or \"1,024 sites\". Only the count 1 takes the singular\n * noun. Each other count takes the plural noun, also 0 and -1. The count has the digit groups of English and at most\n * three decimal places.\n *\n * @param count - The number of things.\n * @param noun - The singular noun.\n * @param plural - The plural noun. The default is the singular noun with the letter \"s\" at the end.\n * @returns The count, a space and the noun.\n */\nexport function countOf(count: number, noun: string, plural = `${noun}s`): string {\n return `${count.toLocaleString(\"en\")} ${count === 1 ? noun : plural}`;\n}\n\n/** The options of `listOf`. */\nexport interface ListOptions {\n /** The word before the last part. The default is \"and\". */\n readonly conjunction?: string;\n /** With true, a comma also goes before the conjunction in a list of three parts or more. The default is false. */\n readonly serialComma?: boolean;\n}\n\n/**\n * This function joins the parts into an English list, for example \"a\", \"a and b\" or \"a, b and c\". A comma and a space go\n * between the parts, and the conjunction goes before the last part. No part gives an empty text. The parts do not change.\n *\n * @param parts - The parts of the list, in their order.\n * @param options - The conjunction and the serial comma.\n * @returns The list as one text.\n */\nexport function listOf(parts: readonly string[], options: ListOptions = {}): string {\n const { conjunction = \"and\", serialComma = false } = options;\n if (parts.length < 2) return parts[0] ?? \"\";\n const comma = serialComma && parts.length > 2 ? \",\" : \"\";\n return `${parts.slice(0, -1).join(\", \")}${comma} ${conjunction} ${parts[parts.length - 1]}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAeA,SAAgB,QAAQ,OAAe,MAAc,SAAS,GAAG,KAAK,IAAY;CAChF,OAAO,GAAG,MAAM,eAAe,IAAI,EAAE,GAAG,UAAU,IAAI,OAAO;AAC/D;;;;;;;;;AAkBA,SAAgB,OAAO,OAA0B,UAAuB,CAAC,GAAW;CAClF,MAAM,EAAE,cAAc,OAAO,cAAc,UAAU;CACrD,IAAI,MAAM,SAAS,GAAG,OAAO,MAAM,MAAM;CACzC,MAAM,QAAQ,eAAe,MAAM,SAAS,IAAI,MAAM;CACtD,OAAO,GAAG,MAAM,MAAM,GAAG,EAAE,CAAC,CAAC,KAAK,IAAI,IAAI,MAAM,GAAG,YAAY,GAAG,MAAM,MAAM,SAAS;AACzF"}
|
package/build/index.d.ts
CHANGED
|
@@ -2,22 +2,9 @@
|
|
|
2
2
|
* The entry of `@mark1russell7/text`: plain text helpers. The first group is the escapes for HTML, attributes, regular
|
|
3
3
|
* expressions, Markdown and GitHub Actions workflow commands. The other groups are the English word forms, a word
|
|
4
4
|
* search and the text of a thrown value. The entry `@mark1russell7/text/redact` removes secrets from a text, and the entry
|
|
5
|
-
* `@mark1russell7/text/order` has two orders of texts.
|
|
5
|
+
* `@mark1russell7/text/order` has two orders of texts. The entry `@mark1russell7/text/english` adds the list join `listOf`.
|
|
6
6
|
*/
|
|
7
|
-
|
|
8
|
-
* This module has the English word forms.
|
|
9
|
-
*/
|
|
10
|
-
/**
|
|
11
|
-
* This function gives a count with a noun, for example "1 site" or "1,024 sites". Only the count 1 takes the singular
|
|
12
|
-
* noun. Each other count takes the plural noun, also 0 and -1. The count has the digit groups of English and at most
|
|
13
|
-
* three decimal places.
|
|
14
|
-
*
|
|
15
|
-
* @param count - The number of things.
|
|
16
|
-
* @param noun - The singular noun.
|
|
17
|
-
* @param plural - The plural noun. The default is the singular noun with the letter "s" at the end.
|
|
18
|
-
* @returns The count, a space and the noun.
|
|
19
|
-
*/
|
|
20
|
-
export declare function countOf(count: number, noun: string, plural?: string): string;
|
|
7
|
+
import { countOf } from "./english.js";
|
|
21
8
|
/**
|
|
22
9
|
* This module has the text of a thrown value.
|
|
23
10
|
*/
|
|
@@ -117,4 +104,5 @@ export declare function searchKey(text: string): string;
|
|
|
117
104
|
* @returns The test of a text.
|
|
118
105
|
*/
|
|
119
106
|
export declare function wordSearch(query: string): (text: string) => boolean;
|
|
107
|
+
export { countOf };
|
|
120
108
|
//# sourceMappingURL=index.d.ts.map
|
package/build/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/error.ts","../src/escape.ts","../src/search.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;wBAkBgB,aAAa;;;;;;;;wBCHb,WAAW;;;;;;;;wBAWX,gBAAgB;;;;;;;;;wBAYhB,aAAa;;;;;;;;;;;;wBAeb,eAAe;;;;;;;;wBAWf,mBAAmB;;;;;;;;wBAWnB,uBAAuB;;;;;;;;;;;;;;;;;wBCnDvB,UAAU;;;;;;;;;;;wBAcV,WAAW,iBAAiB"}
|
package/build/index.js
CHANGED
|
@@ -1,21 +1,5 @@
|
|
|
1
|
+
import { countOf } from "./english.js";
|
|
1
2
|
import { a as escapeWorkflowData, i as escapeRegExp, n as escapeHtml, o as escapeWorkflowProperty, r as escapeMarkdown, t as escapeAttribute } from "./escape-vfOeIxac.js";
|
|
2
|
-
// src/english.ts
|
|
3
|
-
/**
|
|
4
|
-
* This module has the English word forms.
|
|
5
|
-
*/
|
|
6
|
-
/**
|
|
7
|
-
* This function gives a count with a noun, for example "1 site" or "1,024 sites". Only the count 1 takes the singular
|
|
8
|
-
* noun. Each other count takes the plural noun, also 0 and -1. The count has the digit groups of English and at most
|
|
9
|
-
* three decimal places.
|
|
10
|
-
*
|
|
11
|
-
* @param count - The number of things.
|
|
12
|
-
* @param noun - The singular noun.
|
|
13
|
-
* @param plural - The plural noun. The default is the singular noun with the letter "s" at the end.
|
|
14
|
-
* @returns The count, a space and the noun.
|
|
15
|
-
*/
|
|
16
|
-
function countOf(count, noun, plural = `${noun}s`) {
|
|
17
|
-
return `${count.toLocaleString("en")} ${count === 1 ? noun : plural}`;
|
|
18
|
-
}
|
|
19
3
|
// src/error.ts
|
|
20
4
|
/**
|
|
21
5
|
* This module has the text of a thrown value.
|
package/build/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/error.ts","../src/search.ts"],"sourcesContent":["/**\n * This module has the text of a thrown value.\n */\n\n/**\n * This function gives the text of a thrown value, for a log line or a message on a screen. It does not throw.\n *\n * - An object with a `message` text gives that text. The check reads the field, not `instanceof Error`, so an error\n * from another realm (a `vm` context or an `iframe`) also gives its message.\n * - An `Error` with a `message` that is not a text gives `String(message)`. The brand check of\n * `Object.prototype.toString` finds an `Error` of each realm.\n * - Each other value gives `String(value)`.\n * - When `String` throws, the function gives the tag of `Object.prototype.toString`, for example `[object Object]`.\n * - A revoked `Proxy` gives its `typeof` in brackets: `[object]`.\n *\n * @param error - The thrown value. It can be any value.\n * @returns The text of the value.\n */\nexport function errorMessage(error: unknown): string {\n try {\n if (typeof error === \"object\" && error !== null && \"message\" in error) {\n const message: unknown = error.message;\n if (typeof message === \"string\") return message;\n if (Object.prototype.toString.call(error) === \"[object Error]\") return String(message);\n }\n return String(error);\n } catch {\n // String() throws for an object with no prototype, for a toString that throws and for a message getter that throws.\n try {\n return Object.prototype.toString.call(error);\n } catch {\n // A revoked Proxy throws also here. The operator typeof never throws.\n return `[${typeof error}]`;\n }\n }\n}\n","/**\n * This module has a word search of plain text. A text agrees with a search when the text has each word of the search,\n * in any order. The case of the letters is not significant.\n */\n\n/** The small final sigma. Unicode case folding changes it to the small sigma, so a word agrees in each position. */\nconst FINAL_SIGMA = /ς/gu;\n\n/**\n * This function gives the search key of a text. `wordSearch` compares the keys of texts. The function does these steps:\n *\n * 1. It applies the Unicode normalization NFKC. Thus the ligature \"fi\" agrees with \"fi\", and full-width letters agree\n * with ASCII letters.\n * 2. It applies the full lower case, then the full upper case, then the full lower case. Thus \"ß\", \"ẞ\" and \"SS\" give\n * \"ss\".\n * 3. It changes the small final sigma \"ς\" to \"σ\", as Unicode case folding does.\n * 4. It applies NFKC again.\n *\n * The steps use no rules of a locale. Thus the Turkish \"İ\" gives \"i\" with a combining dot above (U+0307), and the\n * Turkish \"ı\" gives \"i\". The key of a key is the same key. Accents stay, so \"é\" does not agree with \"e\".\n *\n * @param text - The plain text.\n * @returns The search key of the text.\n */\nexport function searchKey(text: string): string {\n return text.normalize(\"NFKC\").toLowerCase().toUpperCase().toLowerCase().replace(FINAL_SIGMA, \"σ\").normalize(\"NFKC\");\n}\n\n/**\n * This function gives the test of a search. The function makes the key of the search with `searchKey`. Then it splits\n * the key into words at each run of white space, the class `\\s` of a regular expression.\n *\n * The test tells if the key of a text contains each word, in any order. A word can be a part of a longer word, so the\n * search \"art\" finds \"Party\". A search with no words agrees with each text.\n *\n * @param query - The search, as a person types it.\n * @returns The test of a text.\n */\nexport function wordSearch(query: string): (text: string) => boolean {\n const words = searchKey(query)\n .split(/\\s+/u)\n .filter((word) => word !== \"\");\n return (text) => words.length === 0 || words.every((word) => searchKey(text).includes(word));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAkBA,SAAgB,aAAa,OAAwB;CACnD,IAAI;EACF,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,aAAa,OAAO;GACrE,MAAM,UAAmB,MAAM;GAC/B,IAAI,OAAO,YAAY,UAAU,OAAO;GACxC,IAAI,OAAO,UAAU,SAAS,KAAK,KAAK,MAAM,kBAAkB,OAAO,OAAO,OAAO;EACvF;EACA,OAAO,OAAO,KAAK;CACrB,QAAQ;EAEN,IAAI;GACF,OAAO,OAAO,UAAU,SAAS,KAAK,KAAK;EAC7C,QAAQ;GAEN,OAAO,IAAI,OAAO,MAAM;EAC1B;CACF;AACF;;;;;;;AC7BA,MAAM,cAAc;;;;;;;;;;;;;;;;;AAkBpB,SAAgB,UAAU,MAAsB;CAC9C,OAAO,KAAK,UAAU,MAAM,CAAC,CAAC,YAAY,CAAC,CAAC,YAAY,CAAC,CAAC,YAAY,CAAC,CAAC,QAAQ,aAAa,GAAG,CAAC,CAAC,UAAU,MAAM;AACpH;;;;;;;;;;;AAYA,SAAgB,WAAW,OAA0C;CACnE,MAAM,QAAQ,UAAU,KAAK,CAAC,CAC3B,MAAM,MAAM,CAAC,CACb,QAAQ,SAAS,SAAS,EAAE;CAC/B,QAAQ,SAAS,MAAM,WAAW,KAAK,MAAM,OAAO,SAAS,UAAU,IAAI,CAAC,CAAC,SAAS,IAAI,CAAC;AAC7F"}
|
package/build/redact.d.ts
CHANGED
|
@@ -39,7 +39,11 @@ export interface SecretShape {
|
|
|
39
39
|
readonly id: string;
|
|
40
40
|
/** The words that tell a writer what the shape is. */
|
|
41
41
|
readonly label: string;
|
|
42
|
-
/**
|
|
42
|
+
/**
|
|
43
|
+
* The pattern of a token of the shape. The functions add the flags `d` and `g` to a copy of it. If the pattern has a
|
|
44
|
+
* group with the name `secret`, a match is the span of that group, and the text around it stays. An example is the
|
|
45
|
+
* name of a parameter before its value. If that group does not match, the match gives no span.
|
|
46
|
+
*/
|
|
43
47
|
readonly pattern: RegExp;
|
|
44
48
|
}
|
|
45
49
|
/** A match of a shape in a text: the name of the shape and the span of the match. It does not hold the token. */
|
|
@@ -61,6 +65,31 @@ export interface RedactShapeOptions extends RedactOptions {
|
|
|
61
65
|
* alone in a sentence is not a match. A private key block goes to its end line, or to the end of the text.
|
|
62
66
|
*/
|
|
63
67
|
export declare const SECRET_SHAPES: readonly SecretShape[];
|
|
68
|
+
/**
|
|
69
|
+
* The shapes of a secret by its context. The context is the name of a parameter, a flag, a field or a header, or the
|
|
70
|
+
* user part of a URL. A match is the value only, so the name stays: `--password [secret]`. These shapes find a secret that has no
|
|
71
|
+
* known form, for example a password. They can also match a text with no secret, for example `token: none`. Thus use
|
|
72
|
+
* them to redact a log line or a command line, together with `SECRET_SHAPES`, and not to refuse a text.
|
|
73
|
+
*
|
|
74
|
+
* - `secret-parameter`: a name of a secret, then `=` or `:`, then the value. Examples are `?access_token=v`,
|
|
75
|
+
* `GITHUB_TOKEN=v`, `--password=v`, `"apiKey": "v"` and `X-Api-Key: v`. A name directly after `//` is the user
|
|
76
|
+
* of a URL, so it is not a match.
|
|
77
|
+
* - `secret-flag`: a flag with a name of a secret, a space and the value, for example `--token v`. A value can start
|
|
78
|
+
* with `-`, `<`, `>` or `|`. Then it is the next flag or a part of the shell, so it is not a match.
|
|
79
|
+
* - `url-password`: the password of the user part of a URL, for example `https://user:v@host`.
|
|
80
|
+
* - `authorization`: the value of an `Authorization` or `Proxy-Authorization` header, after its scheme. An example is
|
|
81
|
+
* `Authorization: Basic v`.
|
|
82
|
+
* - `user-password`: the password of a `user:password` after the flag `-u`, `--user` or `--proxy-user` of curl.
|
|
83
|
+
*/
|
|
84
|
+
export declare const CONTEXT_SHAPES: readonly SecretShape[];
|
|
85
|
+
/**
|
|
86
|
+
* This function tells if a name is the name of a secret, by the rule of `CONTEXT_SHAPES`. Use it on the key of a field
|
|
87
|
+
* of a document or on the name of a variable. Then you can redact the value of each field with such a name.
|
|
88
|
+
*
|
|
89
|
+
* @param name - The name, for example `GITHUB_TOKEN` or `client_secret`.
|
|
90
|
+
* @returns `true` if the last word of the name is the name of a secret.
|
|
91
|
+
*/
|
|
92
|
+
export declare function isSecretName(name: string): boolean;
|
|
64
93
|
/**
|
|
65
94
|
* This function finds each match of each shape in a text. Use it to refuse a text that holds a token before you write
|
|
66
95
|
* or send the text. The matches are in the order of their start. At one start, the longer match comes first.
|
package/build/redact.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redact.d.ts","names":[],"sources":["../src/redact.ts"],"mappings":";;;;YAWY;WAA6B;WAAuB;;;iBAG/C;;WAEN;;;;;;;;;;;;;;;;;;;;wBA2DK,cAAc,cAAc,kBAAkB,UAAU,UAAS;;;;;iBAmBhE;;WAEN;;WAEA
|
|
1
|
+
{"version":3,"file":"redact.d.ts","names":[],"sources":["../src/redact.ts"],"mappings":";;;;YAWY;WAA6B;WAAuB;;;iBAG/C;;WAEN;;;;;;;;;;;;;;;;;;;;wBA2DK,cAAc,cAAc,kBAAkB,UAAU,UAAS;;;;;iBAmBhE;;WAEN;;WAEA;;;;;;WAMA,SAAS;;;iBAIH;;WAEN;;WAEA;;WAEA;;;iBAIM,2BAA2B;;WAEjC,kBAAkB;;;;;;qBAehB,wBAAwB;;;;;;;;;;;;;;;;;qBA6DxB,yBAAyB;;;;;;;;wBAqBtB,aAAa;;;;;;;;;wBAwBb,iBAAiB,cAAc,kBAAiB,gBAAgC;;;;;;;;;wBAoBhF,mBAAmB,cAAc,UAAS;;iBAazC,wBAAwB;;WAE9B;;WAEA;;;;;;;;;;;;wBA0BK,wBAAwB,gBAAgB,kBAAiB,gBAAgC"}
|
package/build/redact.js
CHANGED
|
@@ -97,9 +97,73 @@ const SECRET_SHAPES = Object.freeze([
|
|
|
97
97
|
shapeOf("bearer", "the value of an HTTP Bearer credential", /Bearer[ \t]+[A-Za-z0-9_.~+/-]{20,}=*/i),
|
|
98
98
|
shapeOf("private-key", "a private key block", /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?(?:-----END (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----|$)/)
|
|
99
99
|
]);
|
|
100
|
-
/**
|
|
100
|
+
/**
|
|
101
|
+
* The last words of a name that holds a secret, for `isSecretName` and `CONTEXT_SHAPES`. The words are not case
|
|
102
|
+
* sensitive. Any letters, digits, `_`, `.` or `-` can come before a word. Thus `GITHUB_TOKEN`, `PGPASSWORD`,
|
|
103
|
+
* `accessToken`, `X-Api-Key` and `client_secret` are names of secrets. The word `pwd` needs one character before it,
|
|
104
|
+
* because the variable `PWD` holds a folder. The word `key` needs a word that names a secret key before it, or nothing.
|
|
105
|
+
*/
|
|
106
|
+
const NAME = "(?:[A-Za-z0-9_.-]*(?:token|secret|password|passwd|passphrase|credentials?|signature|sig|auth|(?:api|access|secret|private|signing|encryption|master|license|ssh|client)[_.-]?key)|[A-Za-z0-9_.-]+pwd|(?<![A-Za-z0-9_.-])key)";
|
|
107
|
+
/** A name of a context shape starts at the start of the text, or after a character that is not in a name. */
|
|
108
|
+
const NAME_START = "(?<![A-Za-z0-9_.-])";
|
|
109
|
+
/**
|
|
110
|
+
* A value is a text in double quotes or in single quotes on one line. Else it is the characters up to a space, a quote,
|
|
111
|
+
* `&` or `#`. A value with an open quote and no end quote ends at a space. The group `secret` holds the value.
|
|
112
|
+
*/
|
|
113
|
+
const VALUE = `["']?(?<secret>(?<=")[^"\\n]*(?=")|(?<=')[^'\\n]*(?=')|[^\\s"'&#]+)`;
|
|
114
|
+
/** The words of the schemes of the HTTP `Authorization` header. */
|
|
115
|
+
const SCHEMES = "(?:Basic|Bearer|Token|Digest|Negotiate|NTLM)";
|
|
116
|
+
/** This function makes a frozen context shape. The pattern is `NAME_START` and then `body`, with no case. */
|
|
117
|
+
function contextShapeOf(id, label, body) {
|
|
118
|
+
return Object.freeze({
|
|
119
|
+
id,
|
|
120
|
+
label,
|
|
121
|
+
pattern: new RegExp(`${NAME_START}${body}`, "i")
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* The shapes of a secret by its context. The context is the name of a parameter, a flag, a field or a header, or the
|
|
126
|
+
* user part of a URL. A match is the value only, so the name stays: `--password [secret]`. These shapes find a secret that has no
|
|
127
|
+
* known form, for example a password. They can also match a text with no secret, for example `token: none`. Thus use
|
|
128
|
+
* them to redact a log line or a command line, together with `SECRET_SHAPES`, and not to refuse a text.
|
|
129
|
+
*
|
|
130
|
+
* - `secret-parameter`: a name of a secret, then `=` or `:`, then the value. Examples are `?access_token=v`,
|
|
131
|
+
* `GITHUB_TOKEN=v`, `--password=v`, `"apiKey": "v"` and `X-Api-Key: v`. A name directly after `//` is the user
|
|
132
|
+
* of a URL, so it is not a match.
|
|
133
|
+
* - `secret-flag`: a flag with a name of a secret, a space and the value, for example `--token v`. A value can start
|
|
134
|
+
* with `-`, `<`, `>` or `|`. Then it is the next flag or a part of the shell, so it is not a match.
|
|
135
|
+
* - `url-password`: the password of the user part of a URL, for example `https://user:v@host`.
|
|
136
|
+
* - `authorization`: the value of an `Authorization` or `Proxy-Authorization` header, after its scheme. An example is
|
|
137
|
+
* `Authorization: Basic v`.
|
|
138
|
+
* - `user-password`: the password of a `user:password` after the flag `-u`, `--user` or `--proxy-user` of curl.
|
|
139
|
+
*/
|
|
140
|
+
const CONTEXT_SHAPES = Object.freeze([
|
|
141
|
+
contextShapeOf("secret-parameter", "the value of a parameter, a variable or a field with the name of a secret", `(?<!//)${NAME}["']?\\s*[:=]\\s*${VALUE}`),
|
|
142
|
+
contextShapeOf("secret-flag", "the value after a flag with the name of a secret", `-{1,2}${NAME}\\s+(?![-<>|])${VALUE}`),
|
|
143
|
+
contextShapeOf("url-password", "the password in the user part of a URL", "[A-Za-z][A-Za-z0-9+.-]*://[^\\s/?#@:]*:(?<secret>[^\\s/?#@]+)@"),
|
|
144
|
+
contextShapeOf("authorization", "the credential of an HTTP Authorization header", `(?:Proxy-)?Authorization["']?\\s*[:=]\\s*["']?(?:${SCHEMES}\\s+)?(?!${SCHEMES}(?![A-Za-z0-9]))(?<secret>[^\\s"',]+)`),
|
|
145
|
+
contextShapeOf("user-password", "the password of the user option of curl", `(?:-u|--user|--proxy-user)(?:\\s+|=)["']?[^\\s:"']*:(?<secret>[^\\s"']+)`)
|
|
146
|
+
]);
|
|
147
|
+
const SECRET_NAME = new RegExp(`^${NAME}$`, "i");
|
|
148
|
+
/**
|
|
149
|
+
* This function tells if a name is the name of a secret, by the rule of `CONTEXT_SHAPES`. Use it on the key of a field
|
|
150
|
+
* of a document or on the name of a variable. Then you can redact the value of each field with such a name.
|
|
151
|
+
*
|
|
152
|
+
* @param name - The name, for example `GITHUB_TOKEN` or `client_secret`.
|
|
153
|
+
* @returns `true` if the last word of the name is the name of a secret.
|
|
154
|
+
*/
|
|
155
|
+
function isSecretName(name) {
|
|
156
|
+
return SECRET_NAME.test(name);
|
|
157
|
+
}
|
|
158
|
+
/** A copy of a pattern with the flags `d` and `g` and without the flag `y`, for `matchAll` with the spans of groups. */
|
|
101
159
|
function globalCopy(pattern) {
|
|
102
|
-
return new RegExp(pattern.source, `${pattern.flags.replace(/[
|
|
160
|
+
return new RegExp(pattern.source, `${pattern.flags.replace(/[dgy]/g, "")}dg`);
|
|
161
|
+
}
|
|
162
|
+
/** The span of a match: the span of the group `secret` if the pattern has that group, or else the span of the match. */
|
|
163
|
+
function spanOf(match) {
|
|
164
|
+
const groups = match.indices?.groups;
|
|
165
|
+
if (groups !== void 0 && "secret" in groups) return groups["secret"];
|
|
166
|
+
return [match.index, match.index + match[0].length];
|
|
103
167
|
}
|
|
104
168
|
/**
|
|
105
169
|
* This function finds each match of each shape in a text. Use it to refuse a text that holds a token before you write
|
|
@@ -112,11 +176,12 @@ function globalCopy(pattern) {
|
|
|
112
176
|
function findSecretShapes(text, shapes = SECRET_SHAPES) {
|
|
113
177
|
const matches = [];
|
|
114
178
|
for (const shape of shapes) for (const match of text.matchAll(globalCopy(shape.pattern))) {
|
|
115
|
-
|
|
179
|
+
const span = spanOf(match);
|
|
180
|
+
if (span === void 0 || span[0] === span[1]) continue;
|
|
116
181
|
matches.push({
|
|
117
182
|
shape: shape.id,
|
|
118
|
-
start:
|
|
119
|
-
end:
|
|
183
|
+
start: span[0],
|
|
184
|
+
end: span[1]
|
|
120
185
|
});
|
|
121
186
|
}
|
|
122
187
|
return matches.sort((left, right) => left.start - right.start || right.end - left.end);
|
|
@@ -192,6 +257,6 @@ function findSecretShapesInValue(value, shapes = SECRET_SHAPES) {
|
|
|
192
257
|
}
|
|
193
258
|
return matches;
|
|
194
259
|
}
|
|
195
|
-
export { SECRET_SHAPES, findSecretShapes, findSecretShapesInValue, redactSecretShapes, redactSecrets };
|
|
260
|
+
export { CONTEXT_SHAPES, SECRET_SHAPES, findSecretShapes, findSecretShapesInValue, isSecretName, redactSecretShapes, redactSecrets };
|
|
196
261
|
|
|
197
262
|
//# sourceMappingURL=redact.js.map
|
package/build/redact.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redact.js","names":[],"sources":["../src/redact.ts"],"sourcesContent":["/**\n * This module removes secrets from a text, for an error message or a log line. A secret goes into a text in more than\n * one form. The forms are the raw form, the forms of a URL and the form of an HTTP Basic credential. The module removes\n * each form. It also finds the shapes of the tokens of known services, for a token that you do not know.\n */\nimport { escapeRegExp } from \"./escape.ts\";\n\n/**\n * A secret to remove from a text. A string is a key, a token or a password. A pair of a user and a password is an HTTP\n * Basic credential: the function also removes the password and the Base64 form of `user:password`.\n */\nexport type Secret = string | { readonly user: string; readonly password: string };\n\n/** The options of `redactSecrets`. */\nexport interface RedactOptions {\n /** The text in place of each secret. The default is `[secret]`. */\n readonly mark?: string;\n}\n\nconst BASE64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n/**\n * The Base64 form of the UTF-8 bytes of a text, with the padding `=`, as RFC 4648 section 4 tells. A lone surrogate\n * gives the bytes of U+FFFD, as the encoders of the platforms do.\n */\nfunction base64(text: string): string {\n const bytes = (encodeURIComponent(text.toWellFormed()).match(/%..|./g) ?? []).map((part) =>\n part.length === 3 ? Number.parseInt(part.slice(1), 16) : part.charCodeAt(0),\n );\n let out = \"\";\n for (let index = 0; index < bytes.length; index += 3) {\n const [first = 0, second, third] = bytes.slice(index, index + 3);\n const group = (first << 16) | ((second ?? 0) << 8) | (third ?? 0);\n out += BASE64.charAt(group >> 18) + BASE64.charAt((group >> 12) & 63);\n out += second === undefined ? \"==\" : BASE64.charAt((group >> 6) & 63) + (third === undefined ? \"=\" : BASE64.charAt(group & 63));\n }\n return out;\n}\n\n/**\n * The forms of a text in a URL: the raw form, the form of `encodeURIComponent` and the form of `URLSearchParams`. The\n * last form goes into a query or the body of an HTML form. It also encodes `!'()~`, and it gives `+` for a space. A\n * lone surrogate is not in a URL, so the URL forms have U+FFFD in its place, as `URLSearchParams` does.\n */\nfunction urlForms(text: string): string[] {\n const encoded = encodeURIComponent(text.toWellFormed());\n const form = encoded.replace(/[!'()~]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g, \"+\");\n return [text, encoded, form];\n}\n\n/** Each form of a secret. */\nfunction formsOf(secret: Secret): string[] {\n if (typeof secret === \"string\") return urlForms(secret);\n const credential = base64(`${secret.user}:${secret.password}`);\n return [...urlForms(secret.password), ...urlForms(credential)];\n}\n\n/**\n * This function removes each secret from a text, and puts a mark in its place. It removes these forms of each secret:\n *\n * - The raw form.\n * - The form of `encodeURIComponent`, for a secret in the path or the query of a URL.\n * - The form of `URLSearchParams`, for a secret in a query or in the body of an HTML form.\n * - For a pair of a user and a password, the forms of the password and of the Base64 form of `user:password`. This\n * form is the value of an HTTP `Authorization: Basic` header.\n *\n * The function examines the text one time, from the start. At each position, it removes the longest form that agrees.\n * Thus a secret that contains a second secret goes as one mark. The function ignores an empty secret and an empty\n * password. The user of a pair stays, because a user name is not a secret. To remove the user, give it as a string also.\n *\n * @param text - The text, for example an error message.\n * @param secrets - The secrets to remove.\n * @param options - The mark in place of each secret.\n * @returns The text with a mark in place of each form of each secret.\n */\nexport function redactSecrets(text: string, secrets: readonly Secret[], options: RedactOptions = {}): string {\n const mark = options.mark ?? \"[secret]\";\n const forms = new Set<string>();\n for (const secret of secrets) {\n if ((typeof secret === \"string\" ? secret : secret.password) === \"\") continue;\n for (const form of formsOf(secret)) forms.add(form);\n }\n if (forms.size === 0) return text;\n const pattern = [...forms]\n .sort((left, right) => right.length - left.length)\n .map(escapeRegExp)\n .join(\"|\");\n return text.replace(new RegExp(pattern, \"g\"), () => mark);\n}\n\n/**\n * A shape of a token of a known service. A match of the pattern is a token, also when you do not know the secret. A\n * report gives `id` and `label`. It does not give the token.\n */\nexport interface SecretShape {\n /** The name of the shape, for example `github-classic`. */\n readonly id: string;\n /** The words that tell a writer what the shape is. */\n readonly label: string;\n /** The pattern of a token of the shape. The functions add the flag `g` to a copy of it. */\n readonly pattern: RegExp;\n}\n\n/** A match of a shape in a text: the name of the shape and the span of the match. It does not hold the token. */\nexport interface SecretShapeMatch {\n /** The `id` of the shape. */\n readonly shape: string;\n /** The index of the first code unit of the match. */\n readonly start: number;\n /** The index after the last code unit of the match. */\n readonly end: number;\n}\n\n/** The options of `redactSecretShapes`. */\nexport interface RedactShapeOptions extends RedactOptions {\n /** The shapes to remove. The default is `SECRET_SHAPES`. */\n readonly shapes?: readonly SecretShape[];\n}\n\n/** A token starts at the start of the text, or after a character that is not a letter or a digit. */\nconst START = \"(?<![A-Za-z0-9])\";\n\n/** This function makes a frozen shape. The pattern is `START` and then `body`, with the flags of `body`. */\nfunction shapeOf(id: string, label: string, body: RegExp): SecretShape {\n return Object.freeze({ id, label, pattern: new RegExp(`${START}${body.source}`, body.flags) });\n}\n\n/**\n * The shapes of the tokens that `findSecretShapes` knows. Each pattern needs the full length of a token, so a prefix\n * alone in a sentence is not a match. A private key block goes to its end line, or to the end of the text.\n */\nexport const SECRET_SHAPES: readonly SecretShape[] = Object.freeze([\n shapeOf(\"github-fine-grained\", \"a fine-grained personal access token of GitHub\", /github_pat_[A-Za-z0-9_]{82,}/),\n shapeOf(\"github-classic\", \"a classic personal access token of GitHub\", /ghp_[A-Za-z0-9]{36,}/),\n shapeOf(\"github-oauth\", \"an OAuth access token of GitHub\", /gho_[A-Za-z0-9]{36,}/),\n shapeOf(\"github-app-user\", \"a user access token of a GitHub App\", /ghu_[A-Za-z0-9]{36,}/),\n shapeOf(\"github-app-installation\", \"an installation access token of a GitHub App\", /ghs_[A-Za-z0-9]{36,}/),\n shapeOf(\"github-app-refresh\", \"a refresh token of a GitHub App\", /ghr_[A-Za-z0-9]{36,}/),\n shapeOf(\"npm\", \"an access token of npm\", /npm_[A-Za-z0-9]{36,}/),\n shapeOf(\"anthropic\", \"an API key of Anthropic\", /sk-ant-[A-Za-z0-9_-]{32,}/),\n shapeOf(\"aws-access-key\", \"an access key ID of AWS\", /(?:AKIA|ASIA)[A-Z0-9]{16}(?![A-Za-z0-9])/),\n shapeOf(\"slack\", \"a token of Slack\", /xox[abposr]-[A-Za-z0-9-]{10,}/),\n shapeOf(\"bearer\", \"the value of an HTTP Bearer credential\", /Bearer[ \\t]+[A-Za-z0-9_.~+/-]{20,}=*/i),\n shapeOf(\n \"private-key\",\n \"a private key block\",\n /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----[\\s\\S]*?(?:-----END (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----|$)/,\n ),\n]);\n\n/** A copy of a pattern with the flag `g` and without the flag `y`, for `matchAll`. */\nfunction globalCopy(pattern: RegExp): RegExp {\n return new RegExp(pattern.source, `${pattern.flags.replace(/[gy]/g, \"\")}g`);\n}\n\n/**\n * This function finds each match of each shape in a text. Use it to refuse a text that holds a token before you write\n * or send the text. The matches are in the order of their start. At one start, the longer match comes first.\n *\n * @param text - The text, for example the answer to a form.\n * @param shapes - The shapes to find. The default is `SECRET_SHAPES`.\n * @returns Each match, with the name of its shape and its span. A text with no token gives an empty list.\n */\nexport function findSecretShapes(text: string, shapes: readonly SecretShape[] = SECRET_SHAPES): SecretShapeMatch[] {\n const matches: SecretShapeMatch[] = [];\n for (const shape of shapes) {\n for (const match of text.matchAll(globalCopy(shape.pattern))) {\n if (match[0] === \"\") continue;\n matches.push({ shape: shape.id, start: match.index, end: match.index + match[0].length });\n }\n }\n return matches.sort((left, right) => left.start - right.start || right.end - left.end);\n}\n\n/**\n * This function puts a mark in place of each match of each shape. Matches that overlap give one mark. Use it on a log\n * line or a message that can hold a token that you do not know.\n *\n * @param text - The text, for example the output of a command.\n * @param options - The mark in place of each match, and the shapes to remove.\n * @returns The text with a mark in place of each match.\n */\nexport function redactSecretShapes(text: string, options: RedactShapeOptions = {}): string {\n const mark = options.mark ?? \"[secret]\";\n let out = \"\";\n let at = 0;\n for (const match of findSecretShapes(text, options.shapes)) {\n if (match.end <= at) continue;\n if (match.start >= at) out += `${text.slice(at, match.start)}${mark}`;\n at = match.end;\n }\n return out + text.slice(at);\n}\n\n/** A match of a shape in a string of a value. It does not hold the token. */\nexport interface ValueShapeMatch extends SecretShapeMatch {\n /** The keys and the indexes from the value to the string. For a match in a key, the last part is that key. */\n readonly path: readonly (string | number)[];\n /** The value is `true` for a match in a key of an object, and `false` for a match in a string. */\n readonly inKey: boolean;\n}\n\n/** A node of the walk of `findSecretShapesInValue`, with a link to its parent. */\ninterface WalkNode {\n readonly value: unknown;\n readonly key: string | number | undefined;\n readonly parent: WalkNode | undefined;\n}\n\nfunction pathOf(node: WalkNode): (string | number)[] {\n const path: (string | number)[] = [];\n for (let at: WalkNode | undefined = node; at?.key !== undefined; at = at.parent) path.push(at.key);\n return path.reverse();\n}\n\n/**\n * This function finds each match of each shape in each string of a value. The strings are the value itself, the items\n * of arrays, and the keys and the values of objects. Use it on a JSON document. A scan of the JSON text misses a token after an\n * escape, for example a token at the start of a line. The function examines each object one time, in the order of\n * the document.\n *\n * @param value - The value, for example the body of a JSON document.\n * @param shapes - The shapes to find. The default is `SECRET_SHAPES`.\n * @returns Each match, with the path to its string. A value with no token gives an empty list.\n */\nexport function findSecretShapesInValue(value: unknown, shapes: readonly SecretShape[] = SECRET_SHAPES): ValueShapeMatch[] {\n const matches: ValueShapeMatch[] = [];\n const seen = new Set<object>();\n const stack: WalkNode[] = [{ value, key: undefined, parent: undefined }];\n while (stack.length > 0) {\n const node = stack.pop() as WalkNode;\n // A string key comes from an object. The index of an array is a number. The key comes before its value.\n if (typeof node.key === \"string\") {\n for (const match of findSecretShapes(node.key, shapes)) matches.push({ ...match, path: pathOf(node), inKey: true });\n }\n if (typeof node.value === \"string\") {\n for (const match of findSecretShapes(node.value, shapes)) matches.push({ ...match, path: pathOf(node), inKey: false });\n continue;\n }\n if (node.value === null || typeof node.value !== \"object\" || seen.has(node.value)) continue;\n seen.add(node.value);\n const entries: [string | number, unknown][] = Array.isArray(node.value) ? node.value.map((item, index) => [index, item]) : Object.entries(node.value);\n for (let index = entries.length - 1; index >= 0; index -= 1) {\n const [key, item] = entries[index] as [string | number, unknown];\n stack.push({ value: item, key, parent: node });\n }\n }\n return matches;\n}\n"],"mappings":";;;;;;;AAmBA,MAAM,SAAS;;;;;AAM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B,KAAK,MAAM,SAAS,iBAAiB,KAAK,KAAK,MAAM,GAAG,QAAQ,KAAK;GAAE,GAAG;GAAO,MAAM,OAAO,IAAI;GAAG,OAAO;EAAK,CAAC;EAEpH,IAAI,OAAO,KAAK,UAAU,UAAU;GAClC,KAAK,MAAM,SAAS,iBAAiB,KAAK,OAAO,MAAM,GAAG,QAAQ,KAAK;IAAE,GAAG;IAAO,MAAM,OAAO,IAAI;IAAG,OAAO;GAAM,CAAC;GACrH;EACF;EACA,IAAI,KAAK,UAAU,QAAQ,OAAO,KAAK,UAAU,YAAY,KAAK,IAAI,KAAK,KAAK,GAAG;EACnF,KAAK,IAAI,KAAK,KAAK;EACnB,MAAM,UAAwC,MAAM,QAAQ,KAAK,KAAK,IAAI,KAAK,MAAM,KAAK,MAAM,UAAU,CAAC,OAAO,IAAI,CAAC,IAAI,OAAO,QAAQ,KAAK,KAAK;EACpJ,KAAK,IAAI,QAAQ,QAAQ,SAAS,GAAG,SAAS,GAAG,SAAS,GAAG;GAC3D,MAAM,CAAC,KAAK,QAAQ,QAAQ;GAC5B,MAAM,KAAK;IAAE,OAAO;IAAM;IAAK,QAAQ;GAAK,CAAC;EAC/C;CACF;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"redact.js","names":[],"sources":["../src/redact.ts"],"sourcesContent":["/**\n * This module removes secrets from a text, for an error message or a log line. A secret goes into a text in more than\n * one form. The forms are the raw form, the forms of a URL and the form of an HTTP Basic credential. The module removes\n * each form. It also finds the shapes of the tokens of known services, for a token that you do not know.\n */\nimport { escapeRegExp } from \"./escape.ts\";\n\n/**\n * A secret to remove from a text. A string is a key, a token or a password. A pair of a user and a password is an HTTP\n * Basic credential: the function also removes the password and the Base64 form of `user:password`.\n */\nexport type Secret = string | { readonly user: string; readonly password: string };\n\n/** The options of `redactSecrets`. */\nexport interface RedactOptions {\n /** The text in place of each secret. The default is `[secret]`. */\n readonly mark?: string;\n}\n\nconst BASE64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n/**\n * The Base64 form of the UTF-8 bytes of a text, with the padding `=`, as RFC 4648 section 4 tells. A lone surrogate\n * gives the bytes of U+FFFD, as the encoders of the platforms do.\n */\nfunction base64(text: string): string {\n const bytes = (encodeURIComponent(text.toWellFormed()).match(/%..|./g) ?? []).map((part) =>\n part.length === 3 ? Number.parseInt(part.slice(1), 16) : part.charCodeAt(0),\n );\n let out = \"\";\n for (let index = 0; index < bytes.length; index += 3) {\n const [first = 0, second, third] = bytes.slice(index, index + 3);\n const group = (first << 16) | ((second ?? 0) << 8) | (third ?? 0);\n out += BASE64.charAt(group >> 18) + BASE64.charAt((group >> 12) & 63);\n out += second === undefined ? \"==\" : BASE64.charAt((group >> 6) & 63) + (third === undefined ? \"=\" : BASE64.charAt(group & 63));\n }\n return out;\n}\n\n/**\n * The forms of a text in a URL: the raw form, the form of `encodeURIComponent` and the form of `URLSearchParams`. The\n * last form goes into a query or the body of an HTML form. It also encodes `!'()~`, and it gives `+` for a space. A\n * lone surrogate is not in a URL, so the URL forms have U+FFFD in its place, as `URLSearchParams` does.\n */\nfunction urlForms(text: string): string[] {\n const encoded = encodeURIComponent(text.toWellFormed());\n const form = encoded.replace(/[!'()~]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g, \"+\");\n return [text, encoded, form];\n}\n\n/** Each form of a secret. */\nfunction formsOf(secret: Secret): string[] {\n if (typeof secret === \"string\") return urlForms(secret);\n const credential = base64(`${secret.user}:${secret.password}`);\n return [...urlForms(secret.password), ...urlForms(credential)];\n}\n\n/**\n * This function removes each secret from a text, and puts a mark in its place. It removes these forms of each secret:\n *\n * - The raw form.\n * - The form of `encodeURIComponent`, for a secret in the path or the query of a URL.\n * - The form of `URLSearchParams`, for a secret in a query or in the body of an HTML form.\n * - For a pair of a user and a password, the forms of the password and of the Base64 form of `user:password`. This\n * form is the value of an HTTP `Authorization: Basic` header.\n *\n * The function examines the text one time, from the start. At each position, it removes the longest form that agrees.\n * Thus a secret that contains a second secret goes as one mark. The function ignores an empty secret and an empty\n * password. The user of a pair stays, because a user name is not a secret. To remove the user, give it as a string also.\n *\n * @param text - The text, for example an error message.\n * @param secrets - The secrets to remove.\n * @param options - The mark in place of each secret.\n * @returns The text with a mark in place of each form of each secret.\n */\nexport function redactSecrets(text: string, secrets: readonly Secret[], options: RedactOptions = {}): string {\n const mark = options.mark ?? \"[secret]\";\n const forms = new Set<string>();\n for (const secret of secrets) {\n if ((typeof secret === \"string\" ? secret : secret.password) === \"\") continue;\n for (const form of formsOf(secret)) forms.add(form);\n }\n if (forms.size === 0) return text;\n const pattern = [...forms]\n .sort((left, right) => right.length - left.length)\n .map(escapeRegExp)\n .join(\"|\");\n return text.replace(new RegExp(pattern, \"g\"), () => mark);\n}\n\n/**\n * A shape of a token of a known service. A match of the pattern is a token, also when you do not know the secret. A\n * report gives `id` and `label`. It does not give the token.\n */\nexport interface SecretShape {\n /** The name of the shape, for example `github-classic`. */\n readonly id: string;\n /** The words that tell a writer what the shape is. */\n readonly label: string;\n /**\n * The pattern of a token of the shape. The functions add the flags `d` and `g` to a copy of it. If the pattern has a\n * group with the name `secret`, a match is the span of that group, and the text around it stays. An example is the\n * name of a parameter before its value. If that group does not match, the match gives no span.\n */\n readonly pattern: RegExp;\n}\n\n/** A match of a shape in a text: the name of the shape and the span of the match. It does not hold the token. */\nexport interface SecretShapeMatch {\n /** The `id` of the shape. */\n readonly shape: string;\n /** The index of the first code unit of the match. */\n readonly start: number;\n /** The index after the last code unit of the match. */\n readonly end: number;\n}\n\n/** The options of `redactSecretShapes`. */\nexport interface RedactShapeOptions extends RedactOptions {\n /** The shapes to remove. The default is `SECRET_SHAPES`. */\n readonly shapes?: readonly SecretShape[];\n}\n\n/** A token starts at the start of the text, or after a character that is not a letter or a digit. */\nconst START = \"(?<![A-Za-z0-9])\";\n\n/** This function makes a frozen shape. The pattern is `START` and then `body`, with the flags of `body`. */\nfunction shapeOf(id: string, label: string, body: RegExp): SecretShape {\n return Object.freeze({ id, label, pattern: new RegExp(`${START}${body.source}`, body.flags) });\n}\n\n/**\n * The shapes of the tokens that `findSecretShapes` knows. Each pattern needs the full length of a token, so a prefix\n * alone in a sentence is not a match. A private key block goes to its end line, or to the end of the text.\n */\nexport const SECRET_SHAPES: readonly SecretShape[] = Object.freeze([\n shapeOf(\"github-fine-grained\", \"a fine-grained personal access token of GitHub\", /github_pat_[A-Za-z0-9_]{82,}/),\n shapeOf(\"github-classic\", \"a classic personal access token of GitHub\", /ghp_[A-Za-z0-9]{36,}/),\n shapeOf(\"github-oauth\", \"an OAuth access token of GitHub\", /gho_[A-Za-z0-9]{36,}/),\n shapeOf(\"github-app-user\", \"a user access token of a GitHub App\", /ghu_[A-Za-z0-9]{36,}/),\n shapeOf(\"github-app-installation\", \"an installation access token of a GitHub App\", /ghs_[A-Za-z0-9]{36,}/),\n shapeOf(\"github-app-refresh\", \"a refresh token of a GitHub App\", /ghr_[A-Za-z0-9]{36,}/),\n shapeOf(\"npm\", \"an access token of npm\", /npm_[A-Za-z0-9]{36,}/),\n shapeOf(\"anthropic\", \"an API key of Anthropic\", /sk-ant-[A-Za-z0-9_-]{32,}/),\n shapeOf(\"aws-access-key\", \"an access key ID of AWS\", /(?:AKIA|ASIA)[A-Z0-9]{16}(?![A-Za-z0-9])/),\n shapeOf(\"slack\", \"a token of Slack\", /xox[abposr]-[A-Za-z0-9-]{10,}/),\n shapeOf(\"bearer\", \"the value of an HTTP Bearer credential\", /Bearer[ \\t]+[A-Za-z0-9_.~+/-]{20,}=*/i),\n shapeOf(\n \"private-key\",\n \"a private key block\",\n /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----[\\s\\S]*?(?:-----END (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----|$)/,\n ),\n]);\n\n/**\n * The last words of a name that holds a secret, for `isSecretName` and `CONTEXT_SHAPES`. The words are not case\n * sensitive. Any letters, digits, `_`, `.` or `-` can come before a word. Thus `GITHUB_TOKEN`, `PGPASSWORD`,\n * `accessToken`, `X-Api-Key` and `client_secret` are names of secrets. The word `pwd` needs one character before it,\n * because the variable `PWD` holds a folder. The word `key` needs a word that names a secret key before it, or nothing.\n */\nconst NAME =\n \"(?:[A-Za-z0-9_.-]*(?:token|secret|password|passwd|passphrase|credentials?|signature|sig|auth|(?:api|access|secret|private|signing|encryption|master|license|ssh|client)[_.-]?key)|[A-Za-z0-9_.-]+pwd|(?<![A-Za-z0-9_.-])key)\";\n\n/** A name of a context shape starts at the start of the text, or after a character that is not in a name. */\nconst NAME_START = \"(?<![A-Za-z0-9_.-])\";\n\n/**\n * A value is a text in double quotes or in single quotes on one line. Else it is the characters up to a space, a quote,\n * `&` or `#`. A value with an open quote and no end quote ends at a space. The group `secret` holds the value.\n */\nconst VALUE = `[\"']?(?<secret>(?<=\")[^\"\\\\n]*(?=\")|(?<=')[^'\\\\n]*(?=')|[^\\\\s\"'&#]+)`;\n\n/** The words of the schemes of the HTTP `Authorization` header. */\nconst SCHEMES = \"(?:Basic|Bearer|Token|Digest|Negotiate|NTLM)\";\n\n/** This function makes a frozen context shape. The pattern is `NAME_START` and then `body`, with no case. */\nfunction contextShapeOf(id: string, label: string, body: string): SecretShape {\n return Object.freeze({ id, label, pattern: new RegExp(`${NAME_START}${body}`, \"i\") });\n}\n\n/**\n * The shapes of a secret by its context. The context is the name of a parameter, a flag, a field or a header, or the\n * user part of a URL. A match is the value only, so the name stays: `--password [secret]`. These shapes find a secret that has no\n * known form, for example a password. They can also match a text with no secret, for example `token: none`. Thus use\n * them to redact a log line or a command line, together with `SECRET_SHAPES`, and not to refuse a text.\n *\n * - `secret-parameter`: a name of a secret, then `=` or `:`, then the value. Examples are `?access_token=v`,\n * `GITHUB_TOKEN=v`, `--password=v`, `\"apiKey\": \"v\"` and `X-Api-Key: v`. A name directly after `//` is the user\n * of a URL, so it is not a match.\n * - `secret-flag`: a flag with a name of a secret, a space and the value, for example `--token v`. A value can start\n * with `-`, `<`, `>` or `|`. Then it is the next flag or a part of the shell, so it is not a match.\n * - `url-password`: the password of the user part of a URL, for example `https://user:v@host`.\n * - `authorization`: the value of an `Authorization` or `Proxy-Authorization` header, after its scheme. An example is\n * `Authorization: Basic v`.\n * - `user-password`: the password of a `user:password` after the flag `-u`, `--user` or `--proxy-user` of curl.\n */\nexport const CONTEXT_SHAPES: readonly SecretShape[] = Object.freeze([\n contextShapeOf(\"secret-parameter\", \"the value of a parameter, a variable or a field with the name of a secret\", `(?<!//)${NAME}[\"']?\\\\s*[:=]\\\\s*${VALUE}`),\n contextShapeOf(\"secret-flag\", \"the value after a flag with the name of a secret\", `-{1,2}${NAME}\\\\s+(?![-<>|])${VALUE}`),\n contextShapeOf(\"url-password\", \"the password in the user part of a URL\", \"[A-Za-z][A-Za-z0-9+.-]*://[^\\\\s/?#@:]*:(?<secret>[^\\\\s/?#@]+)@\"),\n contextShapeOf(\n \"authorization\",\n \"the credential of an HTTP Authorization header\",\n `(?:Proxy-)?Authorization[\"']?\\\\s*[:=]\\\\s*[\"']?(?:${SCHEMES}\\\\s+)?(?!${SCHEMES}(?![A-Za-z0-9]))(?<secret>[^\\\\s\"',]+)`,\n ),\n contextShapeOf(\"user-password\", \"the password of the user option of curl\", `(?:-u|--user|--proxy-user)(?:\\\\s+|=)[\"']?[^\\\\s:\"']*:(?<secret>[^\\\\s\"']+)`),\n]);\n\nconst SECRET_NAME = new RegExp(`^${NAME}$`, \"i\");\n\n/**\n * This function tells if a name is the name of a secret, by the rule of `CONTEXT_SHAPES`. Use it on the key of a field\n * of a document or on the name of a variable. Then you can redact the value of each field with such a name.\n *\n * @param name - The name, for example `GITHUB_TOKEN` or `client_secret`.\n * @returns `true` if the last word of the name is the name of a secret.\n */\nexport function isSecretName(name: string): boolean {\n return SECRET_NAME.test(name);\n}\n\n/** A copy of a pattern with the flags `d` and `g` and without the flag `y`, for `matchAll` with the spans of groups. */\nfunction globalCopy(pattern: RegExp): RegExp {\n return new RegExp(pattern.source, `${pattern.flags.replace(/[dgy]/g, \"\")}dg`);\n}\n\n/** The span of a match: the span of the group `secret` if the pattern has that group, or else the span of the match. */\nfunction spanOf(match: RegExpExecArray): readonly [number, number] | undefined {\n const groups = match.indices?.groups;\n if (groups !== undefined && \"secret\" in groups) return groups[\"secret\"];\n return [match.index, match.index + match[0].length];\n}\n\n/**\n * This function finds each match of each shape in a text. Use it to refuse a text that holds a token before you write\n * or send the text. The matches are in the order of their start. At one start, the longer match comes first.\n *\n * @param text - The text, for example the answer to a form.\n * @param shapes - The shapes to find. The default is `SECRET_SHAPES`.\n * @returns Each match, with the name of its shape and its span. A text with no token gives an empty list.\n */\nexport function findSecretShapes(text: string, shapes: readonly SecretShape[] = SECRET_SHAPES): SecretShapeMatch[] {\n const matches: SecretShapeMatch[] = [];\n for (const shape of shapes) {\n for (const match of text.matchAll(globalCopy(shape.pattern))) {\n const span = spanOf(match);\n if (span === undefined || span[0] === span[1]) continue;\n matches.push({ shape: shape.id, start: span[0], end: span[1] });\n }\n }\n return matches.sort((left, right) => left.start - right.start || right.end - left.end);\n}\n\n/**\n * This function puts a mark in place of each match of each shape. Matches that overlap give one mark. Use it on a log\n * line or a message that can hold a token that you do not know.\n *\n * @param text - The text, for example the output of a command.\n * @param options - The mark in place of each match, and the shapes to remove.\n * @returns The text with a mark in place of each match.\n */\nexport function redactSecretShapes(text: string, options: RedactShapeOptions = {}): string {\n const mark = options.mark ?? \"[secret]\";\n let out = \"\";\n let at = 0;\n for (const match of findSecretShapes(text, options.shapes)) {\n if (match.end <= at) continue;\n if (match.start >= at) out += `${text.slice(at, match.start)}${mark}`;\n at = match.end;\n }\n return out + text.slice(at);\n}\n\n/** A match of a shape in a string of a value. It does not hold the token. */\nexport interface ValueShapeMatch extends SecretShapeMatch {\n /** The keys and the indexes from the value to the string. For a match in a key, the last part is that key. */\n readonly path: readonly (string | number)[];\n /** The value is `true` for a match in a key of an object, and `false` for a match in a string. */\n readonly inKey: boolean;\n}\n\n/** A node of the walk of `findSecretShapesInValue`, with a link to its parent. */\ninterface WalkNode {\n readonly value: unknown;\n readonly key: string | number | undefined;\n readonly parent: WalkNode | undefined;\n}\n\nfunction pathOf(node: WalkNode): (string | number)[] {\n const path: (string | number)[] = [];\n for (let at: WalkNode | undefined = node; at?.key !== undefined; at = at.parent) path.push(at.key);\n return path.reverse();\n}\n\n/**\n * This function finds each match of each shape in each string of a value. The strings are the value itself, the items\n * of arrays, and the keys and the values of objects. Use it on a JSON document. A scan of the JSON text misses a token after an\n * escape, for example a token at the start of a line. The function examines each object one time, in the order of\n * the document.\n *\n * @param value - The value, for example the body of a JSON document.\n * @param shapes - The shapes to find. The default is `SECRET_SHAPES`.\n * @returns Each match, with the path to its string. A value with no token gives an empty list.\n */\nexport function findSecretShapesInValue(value: unknown, shapes: readonly SecretShape[] = SECRET_SHAPES): ValueShapeMatch[] {\n const matches: ValueShapeMatch[] = [];\n const seen = new Set<object>();\n const stack: WalkNode[] = [{ value, key: undefined, parent: undefined }];\n while (stack.length > 0) {\n const node = stack.pop() as WalkNode;\n // A string key comes from an object. The index of an array is a number. The key comes before its value.\n if (typeof node.key === \"string\") {\n for (const match of findSecretShapes(node.key, shapes)) matches.push({ ...match, path: pathOf(node), inKey: true });\n }\n if (typeof node.value === \"string\") {\n for (const match of findSecretShapes(node.value, shapes)) matches.push({ ...match, path: pathOf(node), inKey: false });\n continue;\n }\n if (node.value === null || typeof node.value !== \"object\" || seen.has(node.value)) continue;\n seen.add(node.value);\n const entries: [string | number, unknown][] = Array.isArray(node.value) ? node.value.map((item, index) => [index, item]) : Object.entries(node.value);\n for (let index = entries.length - 1; index >= 0; index -= 1) {\n const [key, item] = entries[index] as [string | number, unknown];\n stack.push({ value: item, key, parent: node });\n }\n }\n return matches;\n}\n"],"mappings":";;;;;;;AAmBA,MAAM,SAAS;;;;;AAMf,SAAS,OAAO,MAAsB;CACpC,MAAM,SAAS,mBAAmB,KAAK,aAAa,CAAC,CAAC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;EACnB,MAAM,UAAwC,MAAM,QAAQ,KAAK,KAAK,IAAI,KAAK,MAAM,KAAK,MAAM,UAAU,CAAC,OAAO,IAAI,CAAC,IAAI,OAAO,QAAQ,KAAK,KAAK;EACpJ,KAAK,IAAI,QAAQ,QAAQ,SAAS,GAAG,SAAS,GAAG,SAAS,GAAG;GAC3D,MAAM,CAAC,KAAK,QAAQ,QAAQ;GAC5B,MAAM,KAAK;IAAE,OAAO;IAAM;IAAK,QAAQ;GAAK,CAAC;EAC/C;CACF;CACA,OAAO;AACT"}
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/text",
|
|
4
|
-
"version": "0.0.
|
|
5
|
-
"description": "Plain text helpers: the escapes for HTML, attributes, patterns, Markdown and workflow commands, English word forms (countOf), a word search (wordSearch), the text of a thrown value (errorMessage), the orders of texts by code units and by code points (compareCodeUnits, compareCodePoints), the removal of secrets (redactSecrets) and the shapes of tokens (findSecretShapes, redactSecretShapes, findSecretShapesInValue), and lengths in code units, code points and graphemes with truncation and padding (textLength, truncate, pad), the marked parts of a text (partsAt, partsOf), and a scan of HTML for its text and its start tags (scanHtml).",
|
|
4
|
+
"version": "0.0.12",
|
|
5
|
+
"description": "Plain text helpers: the escapes for HTML, attributes, patterns, Markdown and workflow commands, English word forms (countOf, listOf), a word search (wordSearch), the text of a thrown value (errorMessage), the orders of texts by code units and by code points (compareCodeUnits, compareCodePoints), the removal of secrets (redactSecrets) and the shapes of tokens and of secrets by their context (findSecretShapes, redactSecretShapes, findSecretShapesInValue, CONTEXT_SHAPES, isSecretName), and lengths in code units, code points and graphemes with truncation and padding (textLength, truncate, pad), the marked parts of a text (partsAt, partsOf), and a scan of HTML for its text and its start tags (scanHtml).",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"text",
|
|
8
8
|
"escape",
|
|
@@ -60,6 +60,10 @@
|
|
|
60
60
|
"types": "./build/html.d.ts",
|
|
61
61
|
"default": "./build/html.js"
|
|
62
62
|
},
|
|
63
|
+
"./english": {
|
|
64
|
+
"types": "./build/english.d.ts",
|
|
65
|
+
"default": "./build/english.js"
|
|
66
|
+
},
|
|
63
67
|
"./package.json": "./package.json"
|
|
64
68
|
},
|
|
65
69
|
"files": [
|
package/src/english.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* This module has the English word forms.
|
|
2
|
+
* This module has the English word forms: a count with a noun, and a list of parts. It is the entry
|
|
3
|
+
* `@mark1russell7/text/english`. The root entry has only `countOf`.
|
|
3
4
|
*/
|
|
4
5
|
|
|
5
6
|
/**
|
|
@@ -15,3 +16,26 @@
|
|
|
15
16
|
export function countOf(count: number, noun: string, plural = `${noun}s`): string {
|
|
16
17
|
return `${count.toLocaleString("en")} ${count === 1 ? noun : plural}`;
|
|
17
18
|
}
|
|
19
|
+
|
|
20
|
+
/** The options of `listOf`. */
|
|
21
|
+
export interface ListOptions {
|
|
22
|
+
/** The word before the last part. The default is "and". */
|
|
23
|
+
readonly conjunction?: string;
|
|
24
|
+
/** With true, a comma also goes before the conjunction in a list of three parts or more. The default is false. */
|
|
25
|
+
readonly serialComma?: boolean;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* This function joins the parts into an English list, for example "a", "a and b" or "a, b and c". A comma and a space go
|
|
30
|
+
* between the parts, and the conjunction goes before the last part. No part gives an empty text. The parts do not change.
|
|
31
|
+
*
|
|
32
|
+
* @param parts - The parts of the list, in their order.
|
|
33
|
+
* @param options - The conjunction and the serial comma.
|
|
34
|
+
* @returns The list as one text.
|
|
35
|
+
*/
|
|
36
|
+
export function listOf(parts: readonly string[], options: ListOptions = {}): string {
|
|
37
|
+
const { conjunction = "and", serialComma = false } = options;
|
|
38
|
+
if (parts.length < 2) return parts[0] ?? "";
|
|
39
|
+
const comma = serialComma && parts.length > 2 ? "," : "";
|
|
40
|
+
return `${parts.slice(0, -1).join(", ")}${comma} ${conjunction} ${parts[parts.length - 1]}`;
|
|
41
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* The entry of `@mark1russell7/text`: plain text helpers. The first group is the escapes for HTML, attributes, regular
|
|
3
3
|
* expressions, Markdown and GitHub Actions workflow commands. The other groups are the English word forms, a word
|
|
4
4
|
* search and the text of a thrown value. The entry `@mark1russell7/text/redact` removes secrets from a text, and the entry
|
|
5
|
-
* `@mark1russell7/text/order` has two orders of texts.
|
|
5
|
+
* `@mark1russell7/text/order` has two orders of texts. The entry `@mark1russell7/text/english` adds the list join `listOf`.
|
|
6
6
|
*/
|
|
7
7
|
export { countOf } from "./english.ts";
|
|
8
8
|
export { errorMessage } from "./error.ts";
|
package/src/redact.ts
CHANGED
|
@@ -97,7 +97,11 @@ export interface SecretShape {
|
|
|
97
97
|
readonly id: string;
|
|
98
98
|
/** The words that tell a writer what the shape is. */
|
|
99
99
|
readonly label: string;
|
|
100
|
-
/**
|
|
100
|
+
/**
|
|
101
|
+
* The pattern of a token of the shape. The functions add the flags `d` and `g` to a copy of it. If the pattern has a
|
|
102
|
+
* group with the name `secret`, a match is the span of that group, and the text around it stays. An example is the
|
|
103
|
+
* name of a parameter before its value. If that group does not match, the match gives no span.
|
|
104
|
+
*/
|
|
101
105
|
readonly pattern: RegExp;
|
|
102
106
|
}
|
|
103
107
|
|
|
@@ -148,9 +152,83 @@ export const SECRET_SHAPES: readonly SecretShape[] = Object.freeze([
|
|
|
148
152
|
),
|
|
149
153
|
]);
|
|
150
154
|
|
|
151
|
-
/**
|
|
155
|
+
/**
|
|
156
|
+
* The last words of a name that holds a secret, for `isSecretName` and `CONTEXT_SHAPES`. The words are not case
|
|
157
|
+
* sensitive. Any letters, digits, `_`, `.` or `-` can come before a word. Thus `GITHUB_TOKEN`, `PGPASSWORD`,
|
|
158
|
+
* `accessToken`, `X-Api-Key` and `client_secret` are names of secrets. The word `pwd` needs one character before it,
|
|
159
|
+
* because the variable `PWD` holds a folder. The word `key` needs a word that names a secret key before it, or nothing.
|
|
160
|
+
*/
|
|
161
|
+
const NAME =
|
|
162
|
+
"(?:[A-Za-z0-9_.-]*(?:token|secret|password|passwd|passphrase|credentials?|signature|sig|auth|(?:api|access|secret|private|signing|encryption|master|license|ssh|client)[_.-]?key)|[A-Za-z0-9_.-]+pwd|(?<![A-Za-z0-9_.-])key)";
|
|
163
|
+
|
|
164
|
+
/** A name of a context shape starts at the start of the text, or after a character that is not in a name. */
|
|
165
|
+
const NAME_START = "(?<![A-Za-z0-9_.-])";
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* A value is a text in double quotes or in single quotes on one line. Else it is the characters up to a space, a quote,
|
|
169
|
+
* `&` or `#`. A value with an open quote and no end quote ends at a space. The group `secret` holds the value.
|
|
170
|
+
*/
|
|
171
|
+
const VALUE = `["']?(?<secret>(?<=")[^"\\n]*(?=")|(?<=')[^'\\n]*(?=')|[^\\s"'&#]+)`;
|
|
172
|
+
|
|
173
|
+
/** The words of the schemes of the HTTP `Authorization` header. */
|
|
174
|
+
const SCHEMES = "(?:Basic|Bearer|Token|Digest|Negotiate|NTLM)";
|
|
175
|
+
|
|
176
|
+
/** This function makes a frozen context shape. The pattern is `NAME_START` and then `body`, with no case. */
|
|
177
|
+
function contextShapeOf(id: string, label: string, body: string): SecretShape {
|
|
178
|
+
return Object.freeze({ id, label, pattern: new RegExp(`${NAME_START}${body}`, "i") });
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* The shapes of a secret by its context. The context is the name of a parameter, a flag, a field or a header, or the
|
|
183
|
+
* user part of a URL. A match is the value only, so the name stays: `--password [secret]`. These shapes find a secret that has no
|
|
184
|
+
* known form, for example a password. They can also match a text with no secret, for example `token: none`. Thus use
|
|
185
|
+
* them to redact a log line or a command line, together with `SECRET_SHAPES`, and not to refuse a text.
|
|
186
|
+
*
|
|
187
|
+
* - `secret-parameter`: a name of a secret, then `=` or `:`, then the value. Examples are `?access_token=v`,
|
|
188
|
+
* `GITHUB_TOKEN=v`, `--password=v`, `"apiKey": "v"` and `X-Api-Key: v`. A name directly after `//` is the user
|
|
189
|
+
* of a URL, so it is not a match.
|
|
190
|
+
* - `secret-flag`: a flag with a name of a secret, a space and the value, for example `--token v`. A value can start
|
|
191
|
+
* with `-`, `<`, `>` or `|`. Then it is the next flag or a part of the shell, so it is not a match.
|
|
192
|
+
* - `url-password`: the password of the user part of a URL, for example `https://user:v@host`.
|
|
193
|
+
* - `authorization`: the value of an `Authorization` or `Proxy-Authorization` header, after its scheme. An example is
|
|
194
|
+
* `Authorization: Basic v`.
|
|
195
|
+
* - `user-password`: the password of a `user:password` after the flag `-u`, `--user` or `--proxy-user` of curl.
|
|
196
|
+
*/
|
|
197
|
+
export const CONTEXT_SHAPES: readonly SecretShape[] = Object.freeze([
|
|
198
|
+
contextShapeOf("secret-parameter", "the value of a parameter, a variable or a field with the name of a secret", `(?<!//)${NAME}["']?\\s*[:=]\\s*${VALUE}`),
|
|
199
|
+
contextShapeOf("secret-flag", "the value after a flag with the name of a secret", `-{1,2}${NAME}\\s+(?![-<>|])${VALUE}`),
|
|
200
|
+
contextShapeOf("url-password", "the password in the user part of a URL", "[A-Za-z][A-Za-z0-9+.-]*://[^\\s/?#@:]*:(?<secret>[^\\s/?#@]+)@"),
|
|
201
|
+
contextShapeOf(
|
|
202
|
+
"authorization",
|
|
203
|
+
"the credential of an HTTP Authorization header",
|
|
204
|
+
`(?:Proxy-)?Authorization["']?\\s*[:=]\\s*["']?(?:${SCHEMES}\\s+)?(?!${SCHEMES}(?![A-Za-z0-9]))(?<secret>[^\\s"',]+)`,
|
|
205
|
+
),
|
|
206
|
+
contextShapeOf("user-password", "the password of the user option of curl", `(?:-u|--user|--proxy-user)(?:\\s+|=)["']?[^\\s:"']*:(?<secret>[^\\s"']+)`),
|
|
207
|
+
]);
|
|
208
|
+
|
|
209
|
+
const SECRET_NAME = new RegExp(`^${NAME}$`, "i");
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* This function tells if a name is the name of a secret, by the rule of `CONTEXT_SHAPES`. Use it on the key of a field
|
|
213
|
+
* of a document or on the name of a variable. Then you can redact the value of each field with such a name.
|
|
214
|
+
*
|
|
215
|
+
* @param name - The name, for example `GITHUB_TOKEN` or `client_secret`.
|
|
216
|
+
* @returns `true` if the last word of the name is the name of a secret.
|
|
217
|
+
*/
|
|
218
|
+
export function isSecretName(name: string): boolean {
|
|
219
|
+
return SECRET_NAME.test(name);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** A copy of a pattern with the flags `d` and `g` and without the flag `y`, for `matchAll` with the spans of groups. */
|
|
152
223
|
function globalCopy(pattern: RegExp): RegExp {
|
|
153
|
-
return new RegExp(pattern.source, `${pattern.flags.replace(/[
|
|
224
|
+
return new RegExp(pattern.source, `${pattern.flags.replace(/[dgy]/g, "")}dg`);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** The span of a match: the span of the group `secret` if the pattern has that group, or else the span of the match. */
|
|
228
|
+
function spanOf(match: RegExpExecArray): readonly [number, number] | undefined {
|
|
229
|
+
const groups = match.indices?.groups;
|
|
230
|
+
if (groups !== undefined && "secret" in groups) return groups["secret"];
|
|
231
|
+
return [match.index, match.index + match[0].length];
|
|
154
232
|
}
|
|
155
233
|
|
|
156
234
|
/**
|
|
@@ -165,8 +243,9 @@ export function findSecretShapes(text: string, shapes: readonly SecretShape[] =
|
|
|
165
243
|
const matches: SecretShapeMatch[] = [];
|
|
166
244
|
for (const shape of shapes) {
|
|
167
245
|
for (const match of text.matchAll(globalCopy(shape.pattern))) {
|
|
168
|
-
|
|
169
|
-
|
|
246
|
+
const span = spanOf(match);
|
|
247
|
+
if (span === undefined || span[0] === span[1]) continue;
|
|
248
|
+
matches.push({ shape: shape.id, start: span[0], end: span[1] });
|
|
170
249
|
}
|
|
171
250
|
}
|
|
172
251
|
return matches.sort((left, right) => left.start - right.start || right.end - left.end);
|