@mark1russell7/text 0.0.7 → 0.0.8

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
@@ -100,6 +100,34 @@ redactSecrets("token=k/y!", secrets, options); // "token=***"
100
100
 
101
101
  The function examines the text one time. At each position, it removes the longest form that agrees, so a secret in a secret gives one mark. It ignores an empty secret.
102
102
 
103
+ ### The shapes of tokens
104
+
105
+ `redactSecrets` needs the secret. A text can also hold a token that you do not know, for example the output of a command in the answer to a form. `findSecretShapes(text, shapes?)` finds the tokens of known services by their shape. Use it to refuse a text before you write it or send it. Each match gives the name of its shape and its span. It does not give the token.
106
+
107
+ | Shape | What it is |
108
+ | --- | --- |
109
+ | `github-fine-grained` | `github_pat_` and 82 or more characters |
110
+ | `github-classic`, `github-oauth`, `github-app-user`, `github-app-installation`, `github-app-refresh` | `ghp_`, `gho_`, `ghu_`, `ghs_` or `ghr_`, and 36 or more letters and digits |
111
+ | `npm` | `npm_` and 36 or more letters and digits |
112
+ | `anthropic` | `sk-ant-` and 32 or more characters |
113
+ | `aws-access-key` | `AKIA` or `ASIA`, and 16 capital letters and digits |
114
+ | `slack` | `xoxb-`, `xoxp-` and the other `xox` prefixes, and 10 or more characters |
115
+ | `bearer` | `Bearer` and a value of 20 or more characters, as in an `Authorization` header |
116
+ | `private-key` | A `PRIVATE KEY` block, to its end line or to the end of the text |
117
+
118
+ `SECRET_SHAPES` is the catalog. Each `SecretShape` has `id`, `label` and `pattern`. To find more shapes, give your own list. `redactSecretShapes(text, options?)` puts a mark in place of each match. Matches that overlap give one mark. `RedactShapeOptions` has `mark` and `shapes`.
119
+
120
+ `findSecretShapesInValue(value, shapes?)` examines each string of a value, for example the body of a JSON document. Each match also gives `path`, the keys and indexes to its string, and `inKey`. Do not examine the JSON text. An escape, for example `\n`, puts a letter directly before a token at the start of a line. Then the token is not a match.
121
+
122
+ ```ts
123
+ import { findSecretShapes, redactSecretShapes } from "@mark1russell7/text/redact";
124
+
125
+ const answer = "token: " + "ghp_" + "A1b2C3d4E5f6".repeat(3);
126
+ findSecretShapes(answer); // [{ shape: "github-classic", start: 7, end: 47 }]
127
+ redactSecretShapes(answer); // "token: [secret]"
128
+ findSecretShapes("the prefix ghp_ in a sentence"); // []
129
+ ```
130
+
103
131
  ## Lengths, truncation and padding
104
132
 
105
133
  The entry `@mark1russell7/text/length` has three functions. Each function counts in the unit that you give. The default unit is `code-unit`.
@@ -181,6 +209,7 @@ The tests also examine 18 copies of a cut with a mark, from a later list of the
181
209
  - `countOf` knows no irregular plural. Give the plural noun for each noun that does not add "s".
182
210
  - `errorMessage` gives only the message. It does not add the name of the error, its `cause` or its stack.
183
211
  - `redactSecrets` removes only the forms in its table. A secret in a JSON string with escapes, or in a different encoding, stays.
212
+ - `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.
184
213
  - `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.
185
214
  - 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.
186
215
  - `partsAt` counts in code units, as `String.prototype.slice` does. A range can cut a surrogate pair or a grapheme.
package/build/redact.d.ts CHANGED
@@ -30,4 +30,71 @@ export interface RedactOptions {
30
30
  * @returns The text with a mark in place of each form of each secret.
31
31
  */
32
32
  export declare function redactSecrets(text: string, secrets: readonly Secret[], options?: RedactOptions): string;
33
+ /**
34
+ * 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
35
+ * report gives `id` and `label`. It does not give the token.
36
+ */
37
+ export interface SecretShape {
38
+ /** The name of the shape, for example `github-classic`. */
39
+ readonly id: string;
40
+ /** The words that tell a writer what the shape is. */
41
+ readonly label: string;
42
+ /** The pattern of a token of the shape. The functions add the flag `g` to a copy of it. */
43
+ readonly pattern: RegExp;
44
+ }
45
+ /** 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. */
46
+ export interface SecretShapeMatch {
47
+ /** The `id` of the shape. */
48
+ readonly shape: string;
49
+ /** The index of the first code unit of the match. */
50
+ readonly start: number;
51
+ /** The index after the last code unit of the match. */
52
+ readonly end: number;
53
+ }
54
+ /** The options of `redactSecretShapes`. */
55
+ export interface RedactShapeOptions extends RedactOptions {
56
+ /** The shapes to remove. The default is `SECRET_SHAPES`. */
57
+ readonly shapes?: readonly SecretShape[];
58
+ }
59
+ /**
60
+ * The shapes of the tokens that `findSecretShapes` knows. Each pattern needs the full length of a token, so a prefix
61
+ * 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
+ */
63
+ export declare const SECRET_SHAPES: readonly SecretShape[];
64
+ /**
65
+ * 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
+ * or send the text. The matches are in the order of their start. At one start, the longer match comes first.
67
+ *
68
+ * @param text - The text, for example the answer to a form.
69
+ * @param shapes - The shapes to find. The default is `SECRET_SHAPES`.
70
+ * @returns Each match, with the name of its shape and its span. A text with no token gives an empty list.
71
+ */
72
+ export declare function findSecretShapes(text: string, shapes?: readonly SecretShape[]): SecretShapeMatch[];
73
+ /**
74
+ * This function puts a mark in place of each match of each shape. Matches that overlap give one mark. Use it on a log
75
+ * line or a message that can hold a token that you do not know.
76
+ *
77
+ * @param text - The text, for example the output of a command.
78
+ * @param options - The mark in place of each match, and the shapes to remove.
79
+ * @returns The text with a mark in place of each match.
80
+ */
81
+ export declare function redactSecretShapes(text: string, options?: RedactShapeOptions): string;
82
+ /** A match of a shape in a string of a value. It does not hold the token. */
83
+ export interface ValueShapeMatch extends SecretShapeMatch {
84
+ /** The keys and the indexes from the value to the string. For a match in a key, the last part is that key. */
85
+ readonly path: readonly (string | number)[];
86
+ /** The value is `true` for a match in a key of an object, and `false` for a match in a string. */
87
+ readonly inKey: boolean;
88
+ }
89
+ /**
90
+ * This function finds each match of each shape in each string of a value. The strings are the value itself, the items
91
+ * 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
92
+ * escape, for example a token at the start of a line. The function examines each object one time, in the order of
93
+ * the document.
94
+ *
95
+ * @param value - The value, for example the body of a JSON document.
96
+ * @param shapes - The shapes to find. The default is `SECRET_SHAPES`.
97
+ * @returns Each match, with the path to its string. A value with no token gives an empty list.
98
+ */
99
+ export declare function findSecretShapesInValue(value: unknown, shapes?: readonly SecretShape[]): ValueShapeMatch[];
33
100
  //# sourceMappingURL=redact.d.ts.map
@@ -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"}
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;;WAEA,SAAS;;;iBAIH;;WAEN;;WAEA;;WAEA;;;iBAIM,2BAA2B;;WAEjC,kBAAkB;;;;;;qBAehB,wBAAwB;;;;;;;;;wBAgCrB,iBAAiB,cAAc,kBAAiB,gBAAgC;;;;;;;;;wBAmBhF,mBAAmB,cAAc,UAAS;;iBAazC,wBAAwB;;WAE9B;;WAEA;;;;;;;;;;;;wBA0BK,wBAAwB,gBAAgB,kBAAiB,gBAAgC"}
package/build/redact.js CHANGED
@@ -3,7 +3,7 @@ import { i as escapeRegExp } from "./escape-vfOeIxac.js";
3
3
  /**
4
4
  * This module removes secrets from a text, for an error message or a log line. A secret goes into a text in more than
5
5
  * one form. The forms are the raw form, the forms of a URL and the form of an HTTP Basic credential. The module removes
6
- * each form.
6
+ * each form. It also finds the shapes of the tokens of known services, for a token that you do not know.
7
7
  */
8
8
  const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
9
9
  /**
@@ -69,6 +69,129 @@ function redactSecrets(text, secrets, options = {}) {
69
69
  const pattern = [...forms].sort((left, right) => right.length - left.length).map(escapeRegExp).join("|");
70
70
  return text.replace(new RegExp(pattern, "g"), () => mark);
71
71
  }
72
- export { redactSecrets };
72
+ /** A token starts at the start of the text, or after a character that is not a letter or a digit. */
73
+ const START = "(?<![A-Za-z0-9])";
74
+ /** This function makes a frozen shape. The pattern is `START` and then `body`, with the flags of `body`. */
75
+ function shapeOf(id, label, body) {
76
+ return Object.freeze({
77
+ id,
78
+ label,
79
+ pattern: new RegExp(`${START}${body.source}`, body.flags)
80
+ });
81
+ }
82
+ /**
83
+ * The shapes of the tokens that `findSecretShapes` knows. Each pattern needs the full length of a token, so a prefix
84
+ * alone in a sentence is not a match. A private key block goes to its end line, or to the end of the text.
85
+ */
86
+ const SECRET_SHAPES = Object.freeze([
87
+ shapeOf("github-fine-grained", "a fine-grained personal access token of GitHub", /github_pat_[A-Za-z0-9_]{82,}/),
88
+ shapeOf("github-classic", "a classic personal access token of GitHub", /ghp_[A-Za-z0-9]{36,}/),
89
+ shapeOf("github-oauth", "an OAuth access token of GitHub", /gho_[A-Za-z0-9]{36,}/),
90
+ shapeOf("github-app-user", "a user access token of a GitHub App", /ghu_[A-Za-z0-9]{36,}/),
91
+ shapeOf("github-app-installation", "an installation access token of a GitHub App", /ghs_[A-Za-z0-9]{36,}/),
92
+ shapeOf("github-app-refresh", "a refresh token of a GitHub App", /ghr_[A-Za-z0-9]{36,}/),
93
+ shapeOf("npm", "an access token of npm", /npm_[A-Za-z0-9]{36,}/),
94
+ shapeOf("anthropic", "an API key of Anthropic", /sk-ant-[A-Za-z0-9_-]{32,}/),
95
+ shapeOf("aws-access-key", "an access key ID of AWS", /(?:AKIA|ASIA)[A-Z0-9]{16}(?![A-Za-z0-9])/),
96
+ shapeOf("slack", "a token of Slack", /xox[abposr]-[A-Za-z0-9-]{10,}/),
97
+ shapeOf("bearer", "the value of an HTTP Bearer credential", /Bearer[ \t]+[A-Za-z0-9_.~+/-]{20,}=*/i),
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
+ ]);
100
+ /** A copy of a pattern with the flag `g` and without the flag `y`, for `matchAll`. */
101
+ function globalCopy(pattern) {
102
+ return new RegExp(pattern.source, `${pattern.flags.replace(/[gy]/g, "")}g`);
103
+ }
104
+ /**
105
+ * This function finds each match of each shape in a text. Use it to refuse a text that holds a token before you write
106
+ * or send the text. The matches are in the order of their start. At one start, the longer match comes first.
107
+ *
108
+ * @param text - The text, for example the answer to a form.
109
+ * @param shapes - The shapes to find. The default is `SECRET_SHAPES`.
110
+ * @returns Each match, with the name of its shape and its span. A text with no token gives an empty list.
111
+ */
112
+ function findSecretShapes(text, shapes = SECRET_SHAPES) {
113
+ const matches = [];
114
+ for (const shape of shapes) for (const match of text.matchAll(globalCopy(shape.pattern))) {
115
+ if (match[0] === "") continue;
116
+ matches.push({
117
+ shape: shape.id,
118
+ start: match.index,
119
+ end: match.index + match[0].length
120
+ });
121
+ }
122
+ return matches.sort((left, right) => left.start - right.start || right.end - left.end);
123
+ }
124
+ /**
125
+ * This function puts a mark in place of each match of each shape. Matches that overlap give one mark. Use it on a log
126
+ * line or a message that can hold a token that you do not know.
127
+ *
128
+ * @param text - The text, for example the output of a command.
129
+ * @param options - The mark in place of each match, and the shapes to remove.
130
+ * @returns The text with a mark in place of each match.
131
+ */
132
+ function redactSecretShapes(text, options = {}) {
133
+ const mark = options.mark ?? "[secret]";
134
+ let out = "";
135
+ let at = 0;
136
+ for (const match of findSecretShapes(text, options.shapes)) {
137
+ if (match.end <= at) continue;
138
+ if (match.start >= at) out += `${text.slice(at, match.start)}${mark}`;
139
+ at = match.end;
140
+ }
141
+ return out + text.slice(at);
142
+ }
143
+ function pathOf(node) {
144
+ const path = [];
145
+ for (let at = node; at?.key !== void 0; at = at.parent) path.push(at.key);
146
+ return path.reverse();
147
+ }
148
+ /**
149
+ * This function finds each match of each shape in each string of a value. The strings are the value itself, the items
150
+ * 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
151
+ * escape, for example a token at the start of a line. The function examines each object one time, in the order of
152
+ * the document.
153
+ *
154
+ * @param value - The value, for example the body of a JSON document.
155
+ * @param shapes - The shapes to find. The default is `SECRET_SHAPES`.
156
+ * @returns Each match, with the path to its string. A value with no token gives an empty list.
157
+ */
158
+ function findSecretShapesInValue(value, shapes = SECRET_SHAPES) {
159
+ const matches = [];
160
+ const seen = /* @__PURE__ */ new Set();
161
+ const stack = [{
162
+ value,
163
+ key: void 0,
164
+ parent: void 0
165
+ }];
166
+ while (stack.length > 0) {
167
+ const node = stack.pop();
168
+ if (typeof node.key === "string") for (const match of findSecretShapes(node.key, shapes)) matches.push({
169
+ ...match,
170
+ path: pathOf(node),
171
+ inKey: true
172
+ });
173
+ if (typeof node.value === "string") {
174
+ for (const match of findSecretShapes(node.value, shapes)) matches.push({
175
+ ...match,
176
+ path: pathOf(node),
177
+ inKey: false
178
+ });
179
+ continue;
180
+ }
181
+ if (node.value === null || typeof node.value !== "object" || seen.has(node.value)) continue;
182
+ seen.add(node.value);
183
+ const entries = Array.isArray(node.value) ? node.value.map((item, index) => [index, item]) : Object.entries(node.value);
184
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
185
+ const [key, item] = entries[index];
186
+ stack.push({
187
+ value: item,
188
+ key,
189
+ parent: node
190
+ });
191
+ }
192
+ }
193
+ return matches;
194
+ }
195
+ export { SECRET_SHAPES, findSecretShapes, findSecretShapesInValue, redactSecretShapes, redactSecrets };
73
196
 
74
197
  //# sourceMappingURL=redact.js.map
@@ -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.\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"],"mappings":";;;;;;;AAmBA,MAAM,SAAS;;;;;AAMf,SAAS,OAAO,MAAsB;CACpC,MAAM,SAAS,mBAAmB,KAAK,aAAa,CAAC,CAAC,CAAC,MAAM,QAAQ,KAAK,CAAC,EAAA,CAAG,KAAK,SACjF,KAAK,WAAW,IAAI,OAAO,SAAS,KAAK,MAAM,CAAC,GAAG,EAAE,IAAI,KAAK,WAAW,CAAC,CAC5E;CACA,IAAI,MAAM;CACV,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,GAAG;EACpD,MAAM,CAAC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C,CACjD,IAAI,YAAY,CAAC,CACjB,KAAK,GAAG;CACX,OAAO,KAAK,QAAQ,IAAI,OAAO,SAAS,GAAG,SAAS,IAAI;AAC1D"}
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;;;;;AAMf,SAAS,OAAO,MAAsB;CACpC,MAAM,SAAS,mBAAmB,KAAK,aAAa,CAAC,CAAC,CAAC,MAAM,QAAQ,KAAK,CAAC,EAAA,CAAG,KAAK,SACjF,KAAK,WAAW,IAAI,OAAO,SAAS,KAAK,MAAM,CAAC,GAAG,EAAE,IAAI,KAAK,WAAW,CAAC,CAC5E;CACA,IAAI,MAAM;CACV,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,GAAG;EACpD,MAAM,CAAC,QAAQ,GAAG,QAAQ,SAAS,MAAM,MAAM,OAAO,QAAQ,CAAC;EAC/D,MAAM,QAAS,SAAS,MAAQ,UAAU,MAAM,KAAM,SAAS;EAC/D,OAAO,OAAO,OAAO,SAAS,EAAE,IAAI,OAAO,OAAQ,SAAS,KAAM,EAAE;EACpE,OAAO,WAAW,KAAA,IAAY,OAAO,OAAO,OAAQ,SAAS,IAAK,EAAE,KAAK,UAAU,KAAA,IAAY,MAAM,OAAO,OAAO,QAAQ,EAAE;CAC/H;CACA,OAAO;AACT;;;;;;AAOA,SAAS,SAAS,MAAwB;CACxC,MAAM,UAAU,mBAAmB,KAAK,aAAa,CAAC;CAEtD,OAAO;EAAC;EAAM;EADD,QAAQ,QAAQ,aAAa,SAAS,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,YAAY,GAAG,CAAC,CAAC,QAAQ,QAAQ,GAC9F;CAAC;AAC7B;;AAGA,SAAS,QAAQ,QAA0B;CACzC,IAAI,OAAO,WAAW,UAAU,OAAO,SAAS,MAAM;CACtD,MAAM,aAAa,OAAO,GAAG,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,UAA6B,CAAC;CACpC,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,QAAoB,CAAC;EAAE;EAAO,KAAK,KAAA;EAAW,QAAQ,KAAA;CAAU,CAAC;CACvE,OAAO,MAAM,SAAS,GAAG;EACvB,MAAM,OAAO,MAAM,IAAI;EAEvB,IAAI,OAAO,KAAK,QAAQ,UACtB,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"}
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.7",
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 removal of secrets (redactSecrets), and lengths in code units, code points and graphemes with truncation and padding (textLength, truncate, pad).",
4
+ "version": "0.0.8",
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 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), and the marked parts of a text (partsAt, partsOf).",
6
6
  "keywords": [
7
7
  "text",
8
8
  "escape",
package/src/redact.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * This module removes secrets from a text, for an error message or a log line. A secret goes into a text in more than
3
3
  * one form. The forms are the raw form, the forms of a URL and the form of an HTTP Basic credential. The module removes
4
- * each form.
4
+ * each form. It also finds the shapes of the tokens of known services, for a token that you do not know.
5
5
  */
6
6
  import { escapeRegExp } from "./escape.ts";
7
7
 
@@ -87,3 +87,163 @@ export function redactSecrets(text: string, secrets: readonly Secret[], options:
87
87
  .join("|");
88
88
  return text.replace(new RegExp(pattern, "g"), () => mark);
89
89
  }
90
+
91
+ /**
92
+ * 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
93
+ * report gives `id` and `label`. It does not give the token.
94
+ */
95
+ export interface SecretShape {
96
+ /** The name of the shape, for example `github-classic`. */
97
+ readonly id: string;
98
+ /** The words that tell a writer what the shape is. */
99
+ readonly label: string;
100
+ /** The pattern of a token of the shape. The functions add the flag `g` to a copy of it. */
101
+ readonly pattern: RegExp;
102
+ }
103
+
104
+ /** 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. */
105
+ export interface SecretShapeMatch {
106
+ /** The `id` of the shape. */
107
+ readonly shape: string;
108
+ /** The index of the first code unit of the match. */
109
+ readonly start: number;
110
+ /** The index after the last code unit of the match. */
111
+ readonly end: number;
112
+ }
113
+
114
+ /** The options of `redactSecretShapes`. */
115
+ export interface RedactShapeOptions extends RedactOptions {
116
+ /** The shapes to remove. The default is `SECRET_SHAPES`. */
117
+ readonly shapes?: readonly SecretShape[];
118
+ }
119
+
120
+ /** A token starts at the start of the text, or after a character that is not a letter or a digit. */
121
+ const START = "(?<![A-Za-z0-9])";
122
+
123
+ /** This function makes a frozen shape. The pattern is `START` and then `body`, with the flags of `body`. */
124
+ function shapeOf(id: string, label: string, body: RegExp): SecretShape {
125
+ return Object.freeze({ id, label, pattern: new RegExp(`${START}${body.source}`, body.flags) });
126
+ }
127
+
128
+ /**
129
+ * The shapes of the tokens that `findSecretShapes` knows. Each pattern needs the full length of a token, so a prefix
130
+ * alone in a sentence is not a match. A private key block goes to its end line, or to the end of the text.
131
+ */
132
+ export const SECRET_SHAPES: readonly SecretShape[] = Object.freeze([
133
+ shapeOf("github-fine-grained", "a fine-grained personal access token of GitHub", /github_pat_[A-Za-z0-9_]{82,}/),
134
+ shapeOf("github-classic", "a classic personal access token of GitHub", /ghp_[A-Za-z0-9]{36,}/),
135
+ shapeOf("github-oauth", "an OAuth access token of GitHub", /gho_[A-Za-z0-9]{36,}/),
136
+ shapeOf("github-app-user", "a user access token of a GitHub App", /ghu_[A-Za-z0-9]{36,}/),
137
+ shapeOf("github-app-installation", "an installation access token of a GitHub App", /ghs_[A-Za-z0-9]{36,}/),
138
+ shapeOf("github-app-refresh", "a refresh token of a GitHub App", /ghr_[A-Za-z0-9]{36,}/),
139
+ shapeOf("npm", "an access token of npm", /npm_[A-Za-z0-9]{36,}/),
140
+ shapeOf("anthropic", "an API key of Anthropic", /sk-ant-[A-Za-z0-9_-]{32,}/),
141
+ shapeOf("aws-access-key", "an access key ID of AWS", /(?:AKIA|ASIA)[A-Z0-9]{16}(?![A-Za-z0-9])/),
142
+ shapeOf("slack", "a token of Slack", /xox[abposr]-[A-Za-z0-9-]{10,}/),
143
+ shapeOf("bearer", "the value of an HTTP Bearer credential", /Bearer[ \t]+[A-Za-z0-9_.~+/-]{20,}=*/i),
144
+ shapeOf(
145
+ "private-key",
146
+ "a private key block",
147
+ /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?(?:-----END (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----|$)/,
148
+ ),
149
+ ]);
150
+
151
+ /** A copy of a pattern with the flag `g` and without the flag `y`, for `matchAll`. */
152
+ function globalCopy(pattern: RegExp): RegExp {
153
+ return new RegExp(pattern.source, `${pattern.flags.replace(/[gy]/g, "")}g`);
154
+ }
155
+
156
+ /**
157
+ * This function finds each match of each shape in a text. Use it to refuse a text that holds a token before you write
158
+ * or send the text. The matches are in the order of their start. At one start, the longer match comes first.
159
+ *
160
+ * @param text - The text, for example the answer to a form.
161
+ * @param shapes - The shapes to find. The default is `SECRET_SHAPES`.
162
+ * @returns Each match, with the name of its shape and its span. A text with no token gives an empty list.
163
+ */
164
+ export function findSecretShapes(text: string, shapes: readonly SecretShape[] = SECRET_SHAPES): SecretShapeMatch[] {
165
+ const matches: SecretShapeMatch[] = [];
166
+ for (const shape of shapes) {
167
+ for (const match of text.matchAll(globalCopy(shape.pattern))) {
168
+ if (match[0] === "") continue;
169
+ matches.push({ shape: shape.id, start: match.index, end: match.index + match[0].length });
170
+ }
171
+ }
172
+ return matches.sort((left, right) => left.start - right.start || right.end - left.end);
173
+ }
174
+
175
+ /**
176
+ * This function puts a mark in place of each match of each shape. Matches that overlap give one mark. Use it on a log
177
+ * line or a message that can hold a token that you do not know.
178
+ *
179
+ * @param text - The text, for example the output of a command.
180
+ * @param options - The mark in place of each match, and the shapes to remove.
181
+ * @returns The text with a mark in place of each match.
182
+ */
183
+ export function redactSecretShapes(text: string, options: RedactShapeOptions = {}): string {
184
+ const mark = options.mark ?? "[secret]";
185
+ let out = "";
186
+ let at = 0;
187
+ for (const match of findSecretShapes(text, options.shapes)) {
188
+ if (match.end <= at) continue;
189
+ if (match.start >= at) out += `${text.slice(at, match.start)}${mark}`;
190
+ at = match.end;
191
+ }
192
+ return out + text.slice(at);
193
+ }
194
+
195
+ /** A match of a shape in a string of a value. It does not hold the token. */
196
+ export interface ValueShapeMatch extends SecretShapeMatch {
197
+ /** The keys and the indexes from the value to the string. For a match in a key, the last part is that key. */
198
+ readonly path: readonly (string | number)[];
199
+ /** The value is `true` for a match in a key of an object, and `false` for a match in a string. */
200
+ readonly inKey: boolean;
201
+ }
202
+
203
+ /** A node of the walk of `findSecretShapesInValue`, with a link to its parent. */
204
+ interface WalkNode {
205
+ readonly value: unknown;
206
+ readonly key: string | number | undefined;
207
+ readonly parent: WalkNode | undefined;
208
+ }
209
+
210
+ function pathOf(node: WalkNode): (string | number)[] {
211
+ const path: (string | number)[] = [];
212
+ for (let at: WalkNode | undefined = node; at?.key !== undefined; at = at.parent) path.push(at.key);
213
+ return path.reverse();
214
+ }
215
+
216
+ /**
217
+ * This function finds each match of each shape in each string of a value. The strings are the value itself, the items
218
+ * 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
219
+ * escape, for example a token at the start of a line. The function examines each object one time, in the order of
220
+ * the document.
221
+ *
222
+ * @param value - The value, for example the body of a JSON document.
223
+ * @param shapes - The shapes to find. The default is `SECRET_SHAPES`.
224
+ * @returns Each match, with the path to its string. A value with no token gives an empty list.
225
+ */
226
+ export function findSecretShapesInValue(value: unknown, shapes: readonly SecretShape[] = SECRET_SHAPES): ValueShapeMatch[] {
227
+ const matches: ValueShapeMatch[] = [];
228
+ const seen = new Set<object>();
229
+ const stack: WalkNode[] = [{ value, key: undefined, parent: undefined }];
230
+ while (stack.length > 0) {
231
+ const node = stack.pop() as WalkNode;
232
+ // A string key comes from an object. The index of an array is a number. The key comes before its value.
233
+ if (typeof node.key === "string") {
234
+ for (const match of findSecretShapes(node.key, shapes)) matches.push({ ...match, path: pathOf(node), inKey: true });
235
+ }
236
+ if (typeof node.value === "string") {
237
+ for (const match of findSecretShapes(node.value, shapes)) matches.push({ ...match, path: pathOf(node), inKey: false });
238
+ continue;
239
+ }
240
+ if (node.value === null || typeof node.value !== "object" || seen.has(node.value)) continue;
241
+ seen.add(node.value);
242
+ const entries: [string | number, unknown][] = Array.isArray(node.value) ? node.value.map((item, index) => [index, item]) : Object.entries(node.value);
243
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
244
+ const [key, item] = entries[index] as [string | number, unknown];
245
+ stack.push({ value: item, key, parent: node });
246
+ }
247
+ }
248
+ return matches;
249
+ }