@hoshinotatsuya/committed-secrets 0.0.0-stage → 0.6.3
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/CHANGELOG.md +166 -0
- package/LICENSE +21 -0
- package/README.md +248 -2
- package/README.ru.md +202 -0
- package/bin/committed-secrets.cjs +8 -0
- package/dist/scanner/auth-header-value.constant.d.ts +8 -0
- package/dist/scanner/auth-header-value.constant.d.ts.map +1 -0
- package/dist/scanner/auth-header-value.constant.js +11 -0
- package/dist/scanner/auth-header-value.constant.js.map +1 -0
- package/dist/scanner/base64-credentials.d.ts +36 -0
- package/dist/scanner/base64-credentials.d.ts.map +1 -0
- package/dist/scanner/base64-credentials.js +108 -0
- package/dist/scanner/base64-credentials.js.map +1 -0
- package/dist/scanner/baseline.d.ts +18 -0
- package/dist/scanner/baseline.d.ts.map +1 -0
- package/dist/scanner/baseline.js +53 -0
- package/dist/scanner/baseline.js.map +1 -0
- package/dist/scanner/cli.d.ts +3 -0
- package/dist/scanner/cli.d.ts.map +1 -0
- package/dist/scanner/cli.js +12 -0
- package/dist/scanner/cli.js.map +1 -0
- package/dist/scanner/code-fallbacks.d.ts +30 -0
- package/dist/scanner/code-fallbacks.d.ts.map +1 -0
- package/dist/scanner/code-fallbacks.js +78 -0
- package/dist/scanner/code-fallbacks.js.map +1 -0
- package/dist/scanner/code-points.d.ts +3 -0
- package/dist/scanner/code-points.d.ts.map +1 -0
- package/dist/scanner/code-points.js +7 -0
- package/dist/scanner/code-points.js.map +1 -0
- package/dist/scanner/command-rules.d.ts +53 -0
- package/dist/scanner/command-rules.d.ts.map +1 -0
- package/dist/scanner/command-rules.js +245 -0
- package/dist/scanner/command-rules.js.map +1 -0
- package/dist/scanner/config-source.d.ts +17 -0
- package/dist/scanner/config-source.d.ts.map +1 -0
- package/dist/scanner/config-source.js +45 -0
- package/dist/scanner/config-source.js.map +1 -0
- package/dist/scanner/credential-value.d.ts +7 -0
- package/dist/scanner/credential-value.d.ts.map +1 -0
- package/dist/scanner/credential-value.js +17 -0
- package/dist/scanner/credential-value.js.map +1 -0
- package/dist/scanner/data-file-name.constant.d.ts +10 -0
- package/dist/scanner/data-file-name.constant.d.ts.map +1 -0
- package/dist/scanner/data-file-name.constant.js +13 -0
- package/dist/scanner/data-file-name.constant.js.map +1 -0
- package/dist/scanner/documented-example-secrets.constant.d.ts +7 -0
- package/dist/scanner/documented-example-secrets.constant.d.ts.map +1 -0
- package/dist/scanner/documented-example-secrets.constant.js +13 -0
- package/dist/scanner/documented-example-secrets.constant.js.map +1 -0
- package/dist/scanner/exit-code.constant.d.ts +7 -0
- package/dist/scanner/exit-code.constant.d.ts.map +1 -0
- package/dist/scanner/exit-code.constant.js +6 -0
- package/dist/scanner/exit-code.constant.js.map +1 -0
- package/dist/scanner/expression-extent.d.ts +9 -0
- package/dist/scanner/expression-extent.d.ts.map +1 -0
- package/dist/scanner/expression-extent.js +42 -0
- package/dist/scanner/expression-extent.js.map +1 -0
- package/dist/scanner/file-kind.type.d.ts +15 -0
- package/dist/scanner/file-kind.type.d.ts.map +1 -0
- package/dist/scanner/file-kind.type.js +3 -0
- package/dist/scanner/file-kind.type.js.map +1 -0
- package/dist/scanner/file-kinds.d.ts +8 -0
- package/dist/scanner/file-kinds.d.ts.map +1 -0
- package/dist/scanner/file-kinds.js +50 -0
- package/dist/scanner/file-kinds.js.map +1 -0
- package/dist/scanner/finding.type.d.ts +18 -0
- package/dist/scanner/finding.type.d.ts.map +1 -0
- package/dist/scanner/finding.type.js +3 -0
- package/dist/scanner/finding.type.js.map +1 -0
- package/dist/scanner/fingerprint.d.ts +9 -0
- package/dist/scanner/fingerprint.d.ts.map +1 -0
- package/dist/scanner/fingerprint.js +15 -0
- package/dist/scanner/fingerprint.js.map +1 -0
- package/dist/scanner/fixture-entry.type.d.ts +7 -0
- package/dist/scanner/fixture-entry.type.d.ts.map +1 -0
- package/dist/scanner/fixture-entry.type.js +3 -0
- package/dist/scanner/fixture-entry.type.js.map +1 -0
- package/dist/scanner/fixture-list.d.ts +22 -0
- package/dist/scanner/fixture-list.d.ts.map +1 -0
- package/dist/scanner/fixture-list.js +74 -0
- package/dist/scanner/fixture-list.js.map +1 -0
- package/dist/scanner/flag-rule.type.d.ts +18 -0
- package/dist/scanner/flag-rule.type.d.ts.map +1 -0
- package/dist/scanner/flag-rule.type.js +3 -0
- package/dist/scanner/flag-rule.type.js.map +1 -0
- package/dist/scanner/gate-broken.error.d.ts +5 -0
- package/dist/scanner/gate-broken.error.d.ts.map +1 -0
- package/dist/scanner/gate-broken.error.js +12 -0
- package/dist/scanner/gate-broken.error.js.map +1 -0
- package/dist/scanner/gate-config.type.d.ts +14 -0
- package/dist/scanner/gate-config.type.d.ts.map +1 -0
- package/dist/scanner/gate-config.type.js +3 -0
- package/dist/scanner/gate-config.type.js.map +1 -0
- package/dist/scanner/gate-files.d.ts +19 -0
- package/dist/scanner/gate-files.d.ts.map +1 -0
- package/dist/scanner/gate-files.js +86 -0
- package/dist/scanner/gate-files.js.map +1 -0
- package/dist/scanner/gate-options.type.d.ts +15 -0
- package/dist/scanner/gate-options.type.d.ts.map +1 -0
- package/dist/scanner/gate-options.type.js +3 -0
- package/dist/scanner/gate-options.type.js.map +1 -0
- package/dist/scanner/gate-report.type.d.ts +11 -0
- package/dist/scanner/gate-report.type.d.ts.map +1 -0
- package/dist/scanner/gate-report.type.js +3 -0
- package/dist/scanner/gate-report.type.js.map +1 -0
- package/dist/scanner/git.d.ts +36 -0
- package/dist/scanner/git.d.ts.map +1 -0
- package/dist/scanner/git.js +190 -0
- package/dist/scanner/git.js.map +1 -0
- package/dist/scanner/index-entry.type.d.ts +7 -0
- package/dist/scanner/index-entry.type.d.ts.map +1 -0
- package/dist/scanner/index-entry.type.js +3 -0
- package/dist/scanner/index-entry.type.js.map +1 -0
- package/dist/scanner/known-token-shapes.constant.d.ts +20 -0
- package/dist/scanner/known-token-shapes.constant.d.ts.map +1 -0
- package/dist/scanner/known-token-shapes.constant.js +57 -0
- package/dist/scanner/known-token-shapes.constant.js.map +1 -0
- package/dist/scanner/line-forms.d.ts +28 -0
- package/dist/scanner/line-forms.d.ts.map +1 -0
- package/dist/scanner/line-forms.js +90 -0
- package/dist/scanner/line-forms.js.map +1 -0
- package/dist/scanner/line-sink.d.ts +18 -0
- package/dist/scanner/line-sink.d.ts.map +1 -0
- package/dist/scanner/line-sink.js +43 -0
- package/dist/scanner/line-sink.js.map +1 -0
- package/dist/scanner/load-config.d.ts +10 -0
- package/dist/scanner/load-config.d.ts.map +1 -0
- package/dist/scanner/load-config.js +81 -0
- package/dist/scanner/load-config.js.map +1 -0
- package/dist/scanner/markdown-code-languages.constant.d.ts +8 -0
- package/dist/scanner/markdown-code-languages.constant.d.ts.map +1 -0
- package/dist/scanner/markdown-code-languages.constant.js +40 -0
- package/dist/scanner/markdown-code-languages.constant.js.map +1 -0
- package/dist/scanner/parse-gate-options.d.ts +8 -0
- package/dist/scanner/parse-gate-options.d.ts.map +1 -0
- package/dist/scanner/parse-gate-options.js +68 -0
- package/dist/scanner/parse-gate-options.js.map +1 -0
- package/dist/scanner/path-suffix.d.ts +3 -0
- package/dist/scanner/path-suffix.d.ts.map +1 -0
- package/dist/scanner/path-suffix.js +10 -0
- package/dist/scanner/path-suffix.js.map +1 -0
- package/dist/scanner/read-json.d.ts +4 -0
- package/dist/scanner/read-json.d.ts.map +1 -0
- package/dist/scanner/read-json.js +18 -0
- package/dist/scanner/read-json.js.map +1 -0
- package/dist/scanner/report-formats.d.ts +20 -0
- package/dist/scanner/report-formats.d.ts.map +1 -0
- package/dist/scanner/report-formats.js +121 -0
- package/dist/scanner/report-formats.js.map +1 -0
- package/dist/scanner/reported-finding.type.d.ts +12 -0
- package/dist/scanner/reported-finding.type.d.ts.map +1 -0
- package/dist/scanner/reported-finding.type.js +3 -0
- package/dist/scanner/reported-finding.type.js.map +1 -0
- package/dist/scanner/repository-files.d.ts +7 -0
- package/dist/scanner/repository-files.d.ts.map +1 -0
- package/dist/scanner/repository-files.js +3 -0
- package/dist/scanner/repository-files.js.map +1 -0
- package/dist/scanner/repository-source.d.ts +42 -0
- package/dist/scanner/repository-source.d.ts.map +1 -0
- package/dist/scanner/repository-source.js +162 -0
- package/dist/scanner/repository-source.js.map +1 -0
- package/dist/scanner/rule-catalog.constant.d.ts +3 -0
- package/dist/scanner/rule-catalog.constant.d.ts.map +1 -0
- package/dist/scanner/rule-catalog.constant.js +14 -0
- package/dist/scanner/rule-catalog.constant.js.map +1 -0
- package/dist/scanner/run-gate.d.ts +14 -0
- package/dist/scanner/run-gate.d.ts.map +1 -0
- package/dist/scanner/run-gate.js +198 -0
- package/dist/scanner/run-gate.js.map +1 -0
- package/dist/scanner/scan-text.d.ts +4 -0
- package/dist/scanner/scan-text.d.ts.map +1 -0
- package/dist/scanner/scan-text.js +9 -0
- package/dist/scanner/scan-text.js.map +1 -0
- package/dist/scanner/secret-key.d.ts +15 -0
- package/dist/scanner/secret-key.d.ts.map +1 -0
- package/dist/scanner/secret-key.js +43 -0
- package/dist/scanner/secret-key.js.map +1 -0
- package/dist/scanner/secret-rules.d.ts +33 -0
- package/dist/scanner/secret-rules.d.ts.map +1 -0
- package/dist/scanner/secret-rules.js +137 -0
- package/dist/scanner/secret-rules.js.map +1 -0
- package/dist/scanner/secret-value.d.ts +14 -0
- package/dist/scanner/secret-value.d.ts.map +1 -0
- package/dist/scanner/secret-value.js +85 -0
- package/dist/scanner/secret-value.js.map +1 -0
- package/dist/scanner/shell-token.type.d.ts +6 -0
- package/dist/scanner/shell-token.type.d.ts.map +1 -0
- package/dist/scanner/shell-token.type.js +3 -0
- package/dist/scanner/shell-token.type.js.map +1 -0
- package/dist/scanner/shell-words.d.ts +28 -0
- package/dist/scanner/shell-words.d.ts.map +1 -0
- package/dist/scanner/shell-words.js +148 -0
- package/dist/scanner/shell-words.js.map +1 -0
- package/dist/scanner/text-of.d.ts +7 -0
- package/dist/scanner/text-of.d.ts.map +1 -0
- package/dist/scanner/text-of.js +41 -0
- package/dist/scanner/text-of.js.map +1 -0
- package/dist/scanner/text-scanner.d.ts +115 -0
- package/dist/scanner/text-scanner.d.ts.map +1 -0
- package/dist/scanner/text-scanner.js +491 -0
- package/dist/scanner/text-scanner.js.map +1 -0
- package/dist/scanner/value-text.d.ts +10 -0
- package/dist/scanner/value-text.d.ts.map +1 -0
- package/dist/scanner/value-text.js +26 -0
- package/dist/scanner/value-text.js.map +1 -0
- package/dist/scanner/volume-mode.constant.d.ts +3 -0
- package/dist/scanner/volume-mode.constant.d.ts.map +1 -0
- package/dist/scanner/volume-mode.constant.js +6 -0
- package/dist/scanner/volume-mode.constant.js.map +1 -0
- package/package.json +71 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this package are documented here. The format follows
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/); the package uses
|
|
5
|
+
[Semantic Versioning](https://semver.org/) with the pre-1.0 rule that a breaking change or a change of
|
|
6
|
+
verdicts bumps the minor.
|
|
7
|
+
|
|
8
|
+
## [0.6.3] — 2026-11-21
|
|
9
|
+
|
|
10
|
+
First public release as `@hoshinotatsuya/committed-secrets`, MIT; documentation in English and Russian;
|
|
11
|
+
no functional changes to scanning.
|
|
12
|
+
|
|
13
|
+
### Changed
|
|
14
|
+
|
|
15
|
+
- The GitLab Secret Detection report names the vendor `@hoshinotatsuya` (was the previous scope).
|
|
16
|
+
- Code-shaped false-positive fixtures moved to `fixtures/code-forms/` as synthetic lines of the same form
|
|
17
|
+
(the spec gives the same pass/fail result per test on the 0.5.1 scanner as the previous fixtures did).
|
|
18
|
+
- The README quick start (`examples/committed-secrets.json`, `examples/committed-secret-fixtures.json`) is
|
|
19
|
+
run by a spec against the built CLI in a throwaway git repository.
|
|
20
|
+
- CI runs on GitHub Actions; dev dependencies: arch-gates 0.12.2, jest-groups 0.7.2.
|
|
21
|
+
|
|
22
|
+
## [0.6.2] — 2026-11-21
|
|
23
|
+
|
|
24
|
+
### Fixed
|
|
25
|
+
|
|
26
|
+
- The "could not check" branch built its reason with `String()`: a thrown value without a prototype or with
|
|
27
|
+
a throwing `toString` / `Symbol.toPrimitive` turned a clear exit code 2 into a `TypeError`. Now it is exit
|
|
28
|
+
code 2 with the reason (`message` if it is a string, otherwise the object tag).
|
|
29
|
+
|
|
30
|
+
## [0.6.1] — 2026-11-18
|
|
31
|
+
|
|
32
|
+
### Fixed
|
|
33
|
+
|
|
34
|
+
- A file name under a secret-named key is not a finding: a CI report key
|
|
35
|
+
(`secret_detection: gl-secret-detection-report.json`), a key file path without `./`
|
|
36
|
+
(`client_secret: keys/client-secret.json`, `private_key: tls/server.key`), a file name in `.env` and in
|
|
37
|
+
code. The form is narrow: lowercase words separated by `-`, `_` or `.`, and an extension from a fixed list
|
|
38
|
+
of data, report and key-file formats. A literal with an appended extension in mixed case is still a finding.
|
|
39
|
+
|
|
40
|
+
## [0.6.0] — 2026-11-17
|
|
41
|
+
|
|
42
|
+
Fixes from an external audit; verdicts change.
|
|
43
|
+
|
|
44
|
+
### Changed
|
|
45
|
+
|
|
46
|
+
- Run from a monorepo subdirectory, `--staged` scanned zero changed files (paths from the repository root
|
|
47
|
+
never matched the index paths from the working directory) and `--history` scanned the whole monorepo.
|
|
48
|
+
Both now use `--relative`: the working directory and paths relative to it.
|
|
49
|
+
- `--write-baseline` together with `--history`/`--since` is a refusal (exit code 2).
|
|
50
|
+
- A `name`/`value` pair with a non-secret name (`- name: IMAGE_TAG` / `value: a1b2c3d4…`) is no longer a
|
|
51
|
+
finding.
|
|
52
|
+
- A Markdown code block with a programming language (`ts`, `python`, `go`, `java`, …) is judged as code.
|
|
53
|
+
|
|
54
|
+
### Added (found now, missed before)
|
|
55
|
+
|
|
56
|
+
- YAML list commands in quotes; Kubernetes env with `value:` above `name:`, comments after `name:`,
|
|
57
|
+
`value: |`; `#` inside an unquoted value; escaped quotes inside literals; a literal on the line after its
|
|
58
|
+
key; `Authorization` of any scheme and raw tokens; argument arrays with brackets inside strings; keys to the
|
|
59
|
+
right of the first assignment; `.npmrc` `_auth` decoded from base64.
|
|
60
|
+
|
|
61
|
+
### Fixed
|
|
62
|
+
|
|
63
|
+
- A literal of a neighbouring property is not attributed to the key; `${…}` inside a default literal is
|
|
64
|
+
not a literal.
|
|
65
|
+
- `EPIPE` on an interrupted blob read was an `uncaughtException` (exit code 1, "secrets found").
|
|
66
|
+
- UTF-16 BE with a BOM and an odd length is decoded without the last byte instead of a `RangeError`.
|
|
67
|
+
|
|
68
|
+
### Migration
|
|
69
|
+
|
|
70
|
+
Fixture-list entries that covered `name`/`value` pairs with non-secret names become stale (refusal
|
|
71
|
+
"entry is stale") — remove them.
|
|
72
|
+
|
|
73
|
+
## [0.5.2] — 2026-11-16
|
|
74
|
+
|
|
75
|
+
### Fixed
|
|
76
|
+
|
|
77
|
+
False positives of 0.5.1 on lines with the full surrounding code structure (comment blocks, code blocks
|
|
78
|
+
inside JSDoc, quotes): a URL password cut with an ellipsis in a comment; a description in words with the
|
|
79
|
+
secret word in plural; a quoted SQL column on the right of a qualified key; a hash in a JSDoc `@example`
|
|
80
|
+
section several lines after the tag (the section is closed by another tag, the end of the comment or a line
|
|
81
|
+
that is not a comment); a single-word environment variable name (`PGPASSWORD: 'PGPASSWORD'`). Each form has
|
|
82
|
+
pairs where a real secret in the same position is still a finding.
|
|
83
|
+
|
|
84
|
+
### Migration
|
|
85
|
+
|
|
86
|
+
Fixture-list or baseline entries that covered one of these false positives become entries without a
|
|
87
|
+
finding: remove fixture entries (stale entries are a refusal), rewrite the baseline with `--write-baseline`.
|
|
88
|
+
|
|
89
|
+
## [0.5.1] — 2026-11-16
|
|
90
|
+
|
|
91
|
+
### Fixed
|
|
92
|
+
|
|
93
|
+
False positives found in real use (no secret values in them): BuildKit `--secret id=…[,env=…|,src=…]`;
|
|
94
|
+
compose volumes `path:path[:mode]`; an escaped variable reference in a command for another shell
|
|
95
|
+
(`\"\$PW\"`); an identifier value with a version suffix; an SQL column compared with a column; a URL with
|
|
96
|
+
placeholders in a comment example; a 32/40/64-hex hash in an `@example` comment; the AWS documentation
|
|
97
|
+
example keys. Each form has a pair "the same position with a real secret is a finding".
|
|
98
|
+
|
|
99
|
+
## [0.5.0] — 2026-11-15
|
|
100
|
+
|
|
101
|
+
### Changed (breaking)
|
|
102
|
+
|
|
103
|
+
- A fixture-list entry exempts SPECIFIC findings: `count` findings of each key (default one), not every
|
|
104
|
+
finding of the key in the file. Migration: add `"count": N` to entries that cover several fixtures.
|
|
105
|
+
- The configuration is type-checked: `minFiles` is an integer ≥ 0, string fields are non-empty, an unknown
|
|
106
|
+
key is a refusal (exit code 2). Migration: remove extra keys (`$schema`, `$comment` are allowed), write
|
|
107
|
+
`minFiles` as a number.
|
|
108
|
+
- An unknown argument is a refusal (exit code 2), not a path.
|
|
109
|
+
- `--staged` reads the configuration, fixture list and baseline from the index and checks only what changed
|
|
110
|
+
relative to HEAD (`--staged --full` for the whole index).
|
|
111
|
+
- New forms find what used to be missed: a repository green on 0.4.0 can turn red.
|
|
112
|
+
|
|
113
|
+
### Added
|
|
114
|
+
|
|
115
|
+
- Command-line flags and assignments, the exec form, YAML lists; `curl -u`, `curl -H "Authorization: …"`,
|
|
116
|
+
`sshpass -p`, `mysql -pPASS`, `docker login -p`, `… set token …`; `requirepass` and ACL passwords,
|
|
117
|
+
`.netrc`, `.pgpass`, shell profiles; base64 credentials (`auth`, kubeconfig `*-data`, `Basic`); JWT,
|
|
118
|
+
GitLab, OpenAI, Anthropic, Yandex Cloud and age tokens; literal defaults; `=>`, XML, `name`/`value` pairs;
|
|
119
|
+
YAML `|` blocks, `!!str`, `~~~`, UTF-16, `prod.env.example`; more key words.
|
|
120
|
+
- Not a finding: SOPS `ENC[…]`, SealedSecret `encryptedData`, age ciphertext, Maven `{…}`,
|
|
121
|
+
`--password-stdin`, `--no-password`, `docker run -p 8080:80`, `mysql -p db`, configparser `%(…)s`,
|
|
122
|
+
CloudFormation `!Ref`.
|
|
123
|
+
- `--history`, `--since <commit>`; the baseline (`baselinePath`, `--write-baseline`); `--format
|
|
124
|
+
json|sarif|gitlab`, `--output`; `testCodePatterns`; the `ENOBUFS` reason.
|
|
125
|
+
- `--staged` on 500 MB: 0.22 s instead of 20.9 s, 69 MB instead of 1147 MB.
|
|
126
|
+
|
|
127
|
+
## [0.4.0] — 2026-11-15
|
|
128
|
+
|
|
129
|
+
### Changed
|
|
130
|
+
|
|
131
|
+
- The `exports` map closes `dist/*`: the package is a CLI only. Running through `bin` is unchanged.
|
|
132
|
+
|
|
133
|
+
## [0.3.0] — 2026-11-15
|
|
134
|
+
|
|
135
|
+
### Changed
|
|
136
|
+
|
|
137
|
+
- The scanner runs on Node; python3 is no longer needed. Ported one to one and compared on the same
|
|
138
|
+
corpus before the old implementation was removed (stdout, stderr and exit codes matched byte for byte).
|
|
139
|
+
- `auth` and `authorization` as words are no longer secrets; authorization headers are judged by the
|
|
140
|
+
value form.
|
|
141
|
+
|
|
142
|
+
### Added
|
|
143
|
+
|
|
144
|
+
- Type annotations between key and value (`const apiKey: string = '…'`), tokens by known prefix under any
|
|
145
|
+
key and in URLs, `Authorization` with a scheme, PGP private keys. One literal — one finding.
|
|
146
|
+
|
|
147
|
+
## [0.2.0] — 2026-11-14
|
|
148
|
+
|
|
149
|
+
### Changed
|
|
150
|
+
|
|
151
|
+
- `--staged` checks the INDEX, not the working tree.
|
|
152
|
+
- Exit code 2 "could not check", separate from a finding (1).
|
|
153
|
+
- `local-dev-only` is no longer a built-in placeholder; new configuration key `extraPlaceholders`.
|
|
154
|
+
|
|
155
|
+
## [0.1.1] — 2026-11-10
|
|
156
|
+
|
|
157
|
+
### Fixed
|
|
158
|
+
|
|
159
|
+
- A description of a secret in camelCase (`secretAccessKey`, `isStrongPassword`) is not a finding, like
|
|
160
|
+
kebab-case; the words of the value must name a secret.
|
|
161
|
+
|
|
162
|
+
## [0.1.0] — 2026-11-10
|
|
163
|
+
|
|
164
|
+
First release: literal secrets in committed files, project configuration in `committed-secrets.json`.
|
|
165
|
+
|
|
166
|
+
[0.6.3]: https://github.com/HoshinoTatsuya/committed-secrets/releases/tag/v0.6.3
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Hoshino Tatsuya
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,249 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @hoshinotatsuya/committed-secrets
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@hoshinotatsuya/committed-secrets)
|
|
4
|
+
[](https://github.com/HoshinoTatsuya/committed-secrets/actions/workflows/ci.yml)
|
|
5
|
+
|
|
6
|
+
[Русская версия](README.ru.md) · [Changelog](CHANGELOG.md)
|
|
7
|
+
|
|
8
|
+
A gate that keeps **literal secrets out of committed files**. A value that reached git is in every clone
|
|
9
|
+
and every CI checkout, and editing the file does not clean the history — the secret is compromised from
|
|
10
|
+
the moment of the commit. Run it in CI over the whole tree, in the commit hook over what is about to be
|
|
11
|
+
committed, and once over the history.
|
|
12
|
+
|
|
13
|
+
A simplified check that sees one form — a quoted value right after a key — missed 12 of 15 real lines.
|
|
14
|
+
This one sees:
|
|
15
|
+
|
|
16
|
+
- `KEY=value` / `KEY: value` without quotes in configuration files (`.env` and its variants, YAML,
|
|
17
|
+
compose, Dockerfile, shell, `.npmrc`, shell profiles, `.netrc`, `.pgpass`, `.my.cnf`, Markdown code
|
|
18
|
+
blocks ``` and ~~~);
|
|
19
|
+
- quoted values in code and JSON, `=>` (PHP, Ruby), XML elements and `name`/`value` pairs in XML and JSON;
|
|
20
|
+
- keys of any shape (`dbPassword`, `apiKey`, `secret_token`, `JWT_SECRET`, `REDIS_PASSWORD_PREVIOUS`),
|
|
21
|
+
glued (`PGPASSWORD`, `accesstoken`), abbreviated (`DB_PWD`), encryption and signing keys
|
|
22
|
+
(`ENCRYPTION_KEY`, `SIGNING_KEY`), `AUTH` as the last word of an environment variable name
|
|
23
|
+
(`REDISCLI_AUTH`, `BASIC_AUTH`), `.npmrc` `_auth`;
|
|
24
|
+
- command lines: password flags (`--requirepass`, `--password=…`, `redis-cli -a`, `sshpass -p`,
|
|
25
|
+
`curl -u user:pass`, `curl -H "Authorization: Bearer …"`, `mysql -pPASS`, `docker login -p`,
|
|
26
|
+
`openssl … pass:…`, `ldapsearch -w`), `KEY=…` assignments in any position (`PGPASSWORD='…' psql`,
|
|
27
|
+
`docker run -e`, `--from-literal=password=…`), `… set token …`; the exec form
|
|
28
|
+
(`["redis-server", "--requirepass", "…"]`), YAML lists line by line, a command inside a code string or
|
|
29
|
+
inline Markdown code;
|
|
30
|
+
- base64: Docker `config.json` `auth`, kubeconfig `*-data`, the `Basic` scheme — decoded and judged by
|
|
31
|
+
content (a PEM private key or `user:password`); base64 PEM (`LS0tLS1CRUdJTi…`) anywhere;
|
|
32
|
+
- literal defaults: `${VAR:-literal}` and in code `process.env.X ?? 'literal'`, `|| 'literal'`,
|
|
33
|
+
`config.get('DB_PASSWORD', 'literal')`, `os.getenv("KEY", "literal")`, `.default('literal')`,
|
|
34
|
+
`Buffer.from('literal', 'hex')`;
|
|
35
|
+
- tokens by shape under any key: GitHub, GitLab (`glpat-`, `glrt-`, `gldt-`, …), Slack, AWS, Google,
|
|
36
|
+
Stripe `sk_live_`, npm, OpenAI, Anthropic, JWT, Yandex Cloud (`y0_`, `t1.`, `AQVN`), age keys;
|
|
37
|
+
- passwords in URLs, PEM and PGP private keys, a YAML `key: |` block on one line, the `!!str` tag;
|
|
38
|
+
- UTF-16 files (with and without a BOM) are text, not binary.
|
|
39
|
+
|
|
40
|
+
**Not a finding**: placeholders (an exact match with the list, not a prefix), substitutions and
|
|
41
|
+
**encrypted storage** — SOPS `ENC[AES256_GCM,…]`, SealedSecret `encryptedData`, age ciphertext, Maven
|
|
42
|
+
`{…}`. A project that stores secrets properly turns the gate on without exceptions.
|
|
43
|
+
|
|
44
|
+
The list of files comes from git (a host `.env` is not in git, and secrets there are legitimate).
|
|
45
|
+
**The value is never printed** — not in text, JSON, SARIF or the GitLab report, neither raw nor base64 nor
|
|
46
|
+
decoded: a report carries the key, the length and a fingerprint.
|
|
47
|
+
|
|
48
|
+
## Install
|
|
49
|
+
|
|
50
|
+
```sh
|
|
51
|
+
pnpm add -D @hoshinotatsuya/committed-secrets
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Node.js **24 or newer** and `git` on `PATH`. No runtime dependencies. The package is a CLI only (no
|
|
55
|
+
programmatic entry point: the `exports` map closes `dist/*`).
|
|
56
|
+
|
|
57
|
+
## Quick start
|
|
58
|
+
|
|
59
|
+
**1.** Put `committed-secrets.json` into the project root. There are no defaults: without the file the gate
|
|
60
|
+
refuses (defaults would judge someone else's repository by someone else's threshold).
|
|
61
|
+
|
|
62
|
+
```json
|
|
63
|
+
{
|
|
64
|
+
"minFiles": 50,
|
|
65
|
+
"requiredKinds": [".ts", ".json", ".yml", ".md"],
|
|
66
|
+
"fixturesPath": "committed-secret-fixtures.json",
|
|
67
|
+
"deliveryPattern": "^(deploy/|docker-compose[^/]*\\.ya?ml$|(?:[^/]*/)*Dockerfile[^/]*$|\\.github/workflows/|\\.env\\.example$)",
|
|
68
|
+
"serviceCodeRoot": "src/"
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
**2.** List legitimate test secrets (throwaway container passwords) in the fixture list named by
|
|
73
|
+
`fixturesPath` — or `[]`:
|
|
74
|
+
|
|
75
|
+
```json
|
|
76
|
+
[
|
|
77
|
+
{
|
|
78
|
+
"file": "src/testing/postgres.harness.ts",
|
|
79
|
+
"keys": ["POSTGRES_PASSWORD"],
|
|
80
|
+
"reason": "one-off password of the throwaway test container on 127.0.0.1"
|
|
81
|
+
}
|
|
82
|
+
]
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
**3.** Run it:
|
|
86
|
+
|
|
87
|
+
```sh
|
|
88
|
+
pnpm exec committed-secrets # CI: every file git tracks in the working tree
|
|
89
|
+
pnpm exec committed-secrets --staged # commit hook: what is about to be committed
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Exit code `0` — no secrets; `1` — findings or fixture-list violations; `2` — the gate could not check
|
|
93
|
+
(no configuration or git, a bad argument or field, broken JSON, a degenerate sample, git output too large).
|
|
94
|
+
"Could not check" is distinct from both success and a finding.
|
|
95
|
+
|
|
96
|
+
Both JSON files above are [`examples/`](examples) and are quoted verbatim; a spec of this package runs
|
|
97
|
+
the built CLI with exactly these files in a throwaway git repository: the listed fixture passes with exit
|
|
98
|
+
code 0, a new `apiKey` literal in `src/` gives exit code 1 in both modes, and the value does not appear in
|
|
99
|
+
the output.
|
|
100
|
+
|
|
101
|
+
## Configuration
|
|
102
|
+
|
|
103
|
+
Every field is type-checked: `minFiles` is an integer ≥ 0 (`"1,500"` is a refusal — it used to silently
|
|
104
|
+
turn the threshold off), an unknown key is a refusal (a typo never silently does nothing; `$schema` and
|
|
105
|
+
`$comment` are allowed), `deliveryPattern` must be a regular expression.
|
|
106
|
+
|
|
107
|
+
| key | required | meaning |
|
|
108
|
+
|---|---|---|
|
|
109
|
+
| `minFiles` | yes | lower bound of the number of scanned files: "no findings" on a degenerate sample proves nothing |
|
|
110
|
+
| `requiredKinds` | yes | file kinds that must be present in the sample (a missing one means the sample degenerated) |
|
|
111
|
+
| `fixturesPath` | yes | the fixture list (below) |
|
|
112
|
+
| `deliveryPattern` | yes | regular expression of delivery files (deploy manifests, compose, Dockerfiles, CI): a secret there is a production secret, the fixture list never exempts it |
|
|
113
|
+
| `serviceCodeRoot` | yes | root of the service code: the fixture list exempts code there only if it matches `testCodePatterns` |
|
|
114
|
+
| `extraPlaceholders` | no | project placeholders, exact case-insensitive match (e.g. a local dev default `${POSTGRES_PASSWORD:-local-dev-only}`) |
|
|
115
|
+
| `testCodePatterns` | no | regular expressions of test code under `serviceCodeRoot`; default `["spec\\.ts$", "/testing/"]` |
|
|
116
|
+
| `baselinePath` | no | baseline file (below) |
|
|
117
|
+
|
|
118
|
+
## Modes
|
|
119
|
+
|
|
120
|
+
| command | what is checked | where |
|
|
121
|
+
|---|---|---|
|
|
122
|
+
| `committed-secrets` | files git tracks, in the working tree | CI |
|
|
123
|
+
| `committed-secrets --staged` | what changed in the INDEX relative to HEAD — what goes into the commit | commit hook |
|
|
124
|
+
| `committed-secrets --staged --full` | the whole index | hook that wants a full scan |
|
|
125
|
+
| `committed-secrets --history` / `--since <commit>` | history blobs (all refs / after a commit up to HEAD), with the commit in the report | initial audit |
|
|
126
|
+
| `committed-secrets <paths…>` | only these files, without the fixture list and the threshold | one-off |
|
|
127
|
+
| `committed-secrets --write-baseline` | writes the current findings into `baselinePath` | adopting the gate |
|
|
128
|
+
|
|
129
|
+
`--format text|json|sarif|gitlab` (default `text`), `--output <file>` — the machine-readable document to a
|
|
130
|
+
file (without it — to stdout, and the summary goes to stderr). SARIF 2.1.0 and the GitLab Secret Detection
|
|
131
|
+
report format are supported.
|
|
132
|
+
|
|
133
|
+
`--staged` judges the index **by the rules in the index**: configuration, fixture list and baseline are
|
|
134
|
+
read from the index, not from disk — a fixture entry added on disk but not staged does not exempt the
|
|
135
|
+
commit. Only changed blobs are read (streamed through `git cat-file --batch`); unchanged files passed the
|
|
136
|
+
gate when they were committed, and CI does the full scan. A change to the gate's own files (configuration,
|
|
137
|
+
list, baseline) in the index switches to a full index scan. Run from a monorepo subdirectory, `--staged`
|
|
138
|
+
and `--history` cover that directory with paths relative to it, like `git ls-files`.
|
|
139
|
+
|
|
140
|
+
Text messages are in Russian; exit codes, the JSON/SARIF/GitLab structure and finding keys are stable.
|
|
141
|
+
|
|
142
|
+
## Fixture list
|
|
143
|
+
|
|
144
|
+
`fixturesPath` is `[{ file, keys, reason, count? }]`: one-off passwords of test containers and the like.
|
|
145
|
+
An entry exempts `count` findings of EACH key in the file (default one): a second secret under the same key
|
|
146
|
+
is a finding again. A delivery file (`deliveryPattern`) and service code outside `testCodePatterns` are
|
|
147
|
+
never exempted; an entry that matches fewer findings than it exempts is a refusal (remove stale entries).
|
|
148
|
+
Finding keys: the key name, `адрес` (a password in a URL), `PEM`, `PGP`, `токен <kind>`, a command flag
|
|
149
|
+
(`redis-cli -a`, `--requirepass`).
|
|
150
|
+
|
|
151
|
+
## Baseline
|
|
152
|
+
|
|
153
|
+
To adopt the gate in a repository with history without fixing everything at once: set `baselinePath` and
|
|
154
|
+
run `committed-secrets --write-baseline`. Current findings are written as fingerprints (file, key,
|
|
155
|
+
fingerprint of the value; no values in the file). From then on the gate fails only on NEW findings; a moved
|
|
156
|
+
line does not refresh a finding, a new value under the same key is a new finding. A baseline entry without
|
|
157
|
+
a finding is not a refusal; the summary mentions it.
|
|
158
|
+
|
|
159
|
+
The fingerprint is scrypt (N=1024) of the value salted with "file + key": it ends up in CI reports, and a
|
|
160
|
+
fast hash would let a weak password be brute-forced in seconds; scrypt costs about a millisecond per
|
|
161
|
+
attempt. It does not protect a truly weak password — a value that reached git must be rotated anyway.
|
|
162
|
+
|
|
163
|
+
## CI and hooks
|
|
164
|
+
|
|
165
|
+
GitHub Actions (SARIF into code scanning):
|
|
166
|
+
|
|
167
|
+
```yaml
|
|
168
|
+
secrets:
|
|
169
|
+
runs-on: ubuntu-latest
|
|
170
|
+
permissions: { contents: read, security-events: write }
|
|
171
|
+
steps:
|
|
172
|
+
- uses: actions/checkout@v5
|
|
173
|
+
- uses: pnpm/action-setup@v4
|
|
174
|
+
- uses: actions/setup-node@v5
|
|
175
|
+
with: { node-version: 24, cache: pnpm }
|
|
176
|
+
- run: pnpm install --frozen-lockfile
|
|
177
|
+
- run: pnpm exec committed-secrets --format sarif --output committed-secrets.sarif
|
|
178
|
+
- if: always()
|
|
179
|
+
uses: github/codeql-action/upload-sarif@v3
|
|
180
|
+
with: { sarif_file: committed-secrets.sarif }
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
GitLab merge requests: `--format gitlab --output gl-secret-detection-report.json` and the report under
|
|
184
|
+
`artifacts.reports.secret_detection`. A commit hook (husky, lefthook, a plain `.git/hooks/pre-commit`):
|
|
185
|
+
`pnpm exec committed-secrets --staged`.
|
|
186
|
+
|
|
187
|
+
## Guarantees and limits
|
|
188
|
+
|
|
189
|
+
- **A descriptive value counts as a placeholder**: `super-secret-jwt-token` in a secret field — the words of
|
|
190
|
+
the value name a secret, and that is not a finding. A real secret in such a form is missed; the price of
|
|
191
|
+
the opposite is noise on field names and enum members.
|
|
192
|
+
- `--staged` over changed files does not see a secret committed around the hook: CI (working tree) or
|
|
193
|
+
`--history` finds it.
|
|
194
|
+
- No online validity check of tokens, and there will be none: that would send the secret out.
|
|
195
|
+
- `.http`/`.rest` files (request headers as lines) are not recognised as a file kind; `Authorization: …`
|
|
196
|
+
in them is not judged.
|
|
197
|
+
- A literal default split across lines (`=` ⏎ `env.X ?? '…'`) is not seen.
|
|
198
|
+
- A random lowercase-and-digits literal with an extension from the data-file list (`x7k2m9q4.json`) is
|
|
199
|
+
read as a file name.
|
|
200
|
+
|
|
201
|
+
**Capacity** (`bench/capacity.cjs`, `pnpm build && node bench/capacity.cjs [root …]`, Node 24 on a laptop, measured on 0.5.0):
|
|
202
|
+
|
|
203
|
+
| input | throughput |
|
|
204
|
+
|---|---|
|
|
205
|
+
| TypeScript code, 16.6 MB | 54 MB/s |
|
|
206
|
+
| `.env.example`, 9.5 MB | 17 MB/s |
|
|
207
|
+
| a minified 1 MB line | 110 MB/s |
|
|
208
|
+
| base64 on one 2 MB line | 141 MB/s |
|
|
209
|
+
| `key=` × 260k on one line | 40 MB/s |
|
|
210
|
+
| `password: ` × 100k on one line | 24 MB/s (one finding: a line literal is named once) |
|
|
211
|
+
|
|
212
|
+
The whole gate on a synthetic monorepo (16k files, 500 MB of text, one changed file in the index):
|
|
213
|
+
`--staged` 0.22 s and 69 MB peak memory; the working tree 22.2 s and 200 MB. Files are read one at a time,
|
|
214
|
+
so memory is one file, not the repository; no catastrophic regex backtracking on long lines (worst inputs
|
|
215
|
+
are linear).
|
|
216
|
+
|
|
217
|
+
## Failure behaviour
|
|
218
|
+
|
|
219
|
+
Fail-closed: a missing or invalid configuration, missing git, broken JSON of the configuration or fixture
|
|
220
|
+
list, a sample below `minFiles` or without a required kind, a path that does not exist, git output beyond
|
|
221
|
+
the buffer (reported as `ENOBUFS`, not "no git") — exit code 2 with a one-line reason. An interrupted blob
|
|
222
|
+
read (`EPIPE`) is handled, not an uncaught exception that would look like "secrets found". A stale fixture
|
|
223
|
+
entry is a refusal, so exemptions do not outlive what they exempted.
|
|
224
|
+
|
|
225
|
+
## Compatibility
|
|
226
|
+
|
|
227
|
+
- Node.js ≥ 24 and git on `PATH` (it runs `ls-files`, `cat-file --batch`, `diff --cached --relative`, `log`); checked with git 2.50 locally and the git of the CI runner, no lower bound is established.
|
|
228
|
+
- Any repository layout, including a monorepo subdirectory; Windows is not verified (no Windows runner in CI).
|
|
229
|
+
|
|
230
|
+
## Testing and development
|
|
231
|
+
|
|
232
|
+
```sh
|
|
233
|
+
pnpm install
|
|
234
|
+
pnpm run typecheck
|
|
235
|
+
pnpm run lint # biome
|
|
236
|
+
pnpm test # build, then Jest in sequential groups of at most 300 tests, 2 workers
|
|
237
|
+
pnpm run build
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
The suite needs only git (specs create throwaway repositories and run the built CLI). Every form in the
|
|
241
|
+
corpus has a pair "finds exactly one, with its key / the same form without a secret is silent"
|
|
242
|
+
(`corpus.spec.ts`, `forms.spec.ts`), token shapes are tested at full length and one character shorter, and
|
|
243
|
+
every output format is checked not to contain the value — raw, base64, hex or decoded. Code-shaped false
|
|
244
|
+
positives (`fixtures/code-forms/`) are synthetic lines of the same form as those met in real use, kept with
|
|
245
|
+
the surrounding comment and JSDoc structure that affects parsing.
|
|
246
|
+
|
|
247
|
+
## License
|
|
248
|
+
|
|
249
|
+
[MIT](LICENSE) © 2026 Hoshino Tatsuya
|
package/README.ru.md
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
# @hoshinotatsuya/committed-secrets
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@hoshinotatsuya/committed-secrets)
|
|
4
|
+
[](https://github.com/HoshinoTatsuya/committed-secrets/actions/workflows/ci.yml)
|
|
5
|
+
|
|
6
|
+
[English](README.md) · [Changelog](CHANGELOG.md)
|
|
7
|
+
|
|
8
|
+
Гейт: в закоммиченных файлах нет литеральных секретов. Значение, попавшее в git, есть в каждом клоне и чекауте CI, и правка файла историю не чистит — секрет скомпрометирован с момента коммита.
|
|
9
|
+
|
|
10
|
+
Упрощённая проверка, видящая одну форму — значение в кавычках сразу после ключа, — пропускала 12 из 15 проверенных строк. Здесь:
|
|
11
|
+
|
|
12
|
+
- `КЛЮЧ=значение` / `КЛЮЧ: значение` без кавычек в файлах конфигурации (.env и его варианты, YAML, compose, Dockerfile, shell, .npmrc, профили оболочки, `.netrc`, `.pgpass`, `.my.cnf`, блоки кода Markdown ``` и ~~~);
|
|
13
|
+
- значение в кавычках в коде и JSON, `=>` (PHP, Ruby), элементы и пары `name`/`value` XML и JSON;
|
|
14
|
+
- ключ любой формы (`dbPassword`, `apiKey`, `secret_token`, `JWT_SECRET`, `REDIS_PASSWORD_PREVIOUS`), склеенный (`PGPASSWORD`, `accesstoken`), сокращённый (`DB_PWD`), ключи шифрования и подписи (`ENCRYPTION_KEY`, `SIGNING_KEY`), `AUTH` последним словом имени переменной окружения (`REDISCLI_AUTH`, `BASIC_AUTH`), `_auth` `.npmrc`;
|
|
15
|
+
- командная строка: флаги с паролем (`--requirepass`, `--password=…`, `redis-cli -a`, `sshpass -p`, `curl -u логин:пароль`, `curl -H "Authorization: Bearer …"`, `mysql -pПАРОЛЬ`, `docker login -p`, `openssl … pass:…`, `ldapsearch -w`), присваивание `KEY=…` в любой позиции (`PGPASSWORD='…' psql`, `docker run -e`, `--from-literal=password=…`, `-o user=…,password=…`), `… set token …`; exec-форма (`["redis-server", "--requirepass", "…"]`, `["CMD-SHELL", "redis-cli -a …"]`), список YAML построчно, команда в строке кода и во встроенном коде Markdown;
|
|
16
|
+
- base64: `auth` Docker `config.json`, `*-data` kubeconfig, схема `Basic` — декодируются и судятся по содержимому (закрытый ключ PEM или «логин:пароль»); base64 PEM (`LS0tLS1CRUdJTi…`) где угодно;
|
|
17
|
+
- литерал по умолчанию: подстановки `${VAR:-литерал}` и в коде — `process.env.X ?? 'литерал'`, `|| 'литерал'`, `config.get('DB_PASSWORD', 'литерал')`, `os.getenv("KEY", "литерал")`, `.default('литерал')`, `Buffer.from('литерал', 'hex')`;
|
|
18
|
+
- токены по форме: GitHub, GitLab (`glpat-`, `glrt-`, `gldt-` и др.), Slack, AWS, Google, Stripe `sk_live_`, npm, OpenAI, Anthropic, JWT, Yandex Cloud (`y0_`, `t1.`, `AQVN`), ключ age;
|
|
19
|
+
- пароль в адресе, закрытый ключ PEM и PGP, блок YAML `ключ: |` в одну строку, тег `!!str`;
|
|
20
|
+
- файлы UTF-16 (с BOM и без) — текст, а не двоичные.
|
|
21
|
+
|
|
22
|
+
Не находка — заглушки (полное совпадение со списком, а не префикс), подстановки и **зашифрованное хранение**: SOPS `ENC[AES256_GCM,…]`, SealedSecret `encryptedData`, шифротекст age, Maven `{…}`. Потребитель, хранящий секреты правильно, включает гейт без исключений.
|
|
23
|
+
|
|
24
|
+
Список файлов — у git (`.env` хоста не в git, и секреты в нём законны). **Значение не выводится нигде** — ни в тексте, ни в JSON, SARIF и отчёте GitLab, ни в base64-, ни в декодированном виде: в отчёт попадают ключ, длина и отпечаток.
|
|
25
|
+
|
|
26
|
+
## Установка
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pnpm add -D @hoshinotatsuya/committed-secrets
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Node.js **24 и новее** и `git` в `PATH`. Зависимостей рантайма нет. Пакет — только CLI (программного входа нет: карта `exports` закрывает `dist/*`).
|
|
33
|
+
|
|
34
|
+
## Быстрый старт
|
|
35
|
+
|
|
36
|
+
**1.** `committed-secrets.json` в корне проекта (без него — отказ: значения по умолчанию судили бы чужой репозиторий чужим порогом):
|
|
37
|
+
|
|
38
|
+
```json
|
|
39
|
+
{
|
|
40
|
+
"minFiles": 50,
|
|
41
|
+
"requiredKinds": [".ts", ".json", ".yml", ".md"],
|
|
42
|
+
"fixturesPath": "committed-secret-fixtures.json",
|
|
43
|
+
"deliveryPattern": "^(deploy/|docker-compose[^/]*\\.ya?ml$|(?:[^/]*/)*Dockerfile[^/]*$|\\.github/workflows/|\\.env\\.example$)",
|
|
44
|
+
"serviceCodeRoot": "src/"
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
**2.** Законные тестовые секреты (пароли одноразовых контейнеров) — в перечень фикстур по пути `fixturesPath`, или `[]`:
|
|
49
|
+
|
|
50
|
+
```json
|
|
51
|
+
[
|
|
52
|
+
{
|
|
53
|
+
"file": "src/testing/postgres.harness.ts",
|
|
54
|
+
"keys": ["POSTGRES_PASSWORD"],
|
|
55
|
+
"reason": "one-off password of the throwaway test container on 127.0.0.1"
|
|
56
|
+
}
|
|
57
|
+
]
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
**3.** Запуск:
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
pnpm exec committed-secrets # CI: все файлы git в рабочем дереве
|
|
64
|
+
pnpm exec committed-secrets --staged # хук коммита: то, что уйдёт в коммит
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Обе настройки выше — файлы [`examples/`](examples), процитированные дословно; спека пакета запускает собранный CLI ровно с ними во временном репозитории git: фикстура из перечня — код 0, новый литерал `apiKey` в `src/` — код 1 в обоих режимах, и значения в выводе нет.
|
|
68
|
+
|
|
69
|
+
## Настройка
|
|
70
|
+
|
|
71
|
+
Каждое поле проверяется по типу: `minFiles` — целое число от 0 (`"1,500"` — отказ, прежде молча выключало порог), неизвестный ключ — отказ (опечатка не действует молча; `$schema` и `$comment` разрешены), `deliveryPattern` — регулярное выражение.
|
|
72
|
+
|
|
73
|
+
| ключ | обязателен | смысл |
|
|
74
|
+
|---|---|---|
|
|
75
|
+
| `minFiles` | да | нижняя граница числа просмотренных файлов: «нет находок» на выродившейся выборке ничего не доказывает |
|
|
76
|
+
| `requiredKinds` | да | классы файлов, которые обязаны быть в выборке (нет класса — выборка выродилась) |
|
|
77
|
+
| `fixturesPath` | да | перечень фикстур (ниже) |
|
|
78
|
+
| `deliveryPattern` | да | регулярное выражение файлов поставки (манифесты выкатки, compose, Dockerfile, CI): секрет в них — секрет прода, перечень фикстур их не освобождает |
|
|
79
|
+
| `serviceCodeRoot` | да | корень кода сервиса: перечень фикстур освобождает код под ним, только если он подходит под `testCodePatterns` |
|
|
80
|
+
| `extraPlaceholders` | нет | заглушки проекта, полное совпадение без учёта регистра (например, локальный дефолт дев-окружения `${POSTGRES_PASSWORD:-local-dev-only}`) |
|
|
81
|
+
| `testCodePatterns` | нет | регулярные выражения тестового кода под `serviceCodeRoot`; по умолчанию `["spec\\.ts$", "/testing/"]` |
|
|
82
|
+
| `baselinePath` | нет | файл базовой линии (ниже) |
|
|
83
|
+
|
|
84
|
+
## Режимы
|
|
85
|
+
|
|
86
|
+
| команда | что проверяется | где |
|
|
87
|
+
|---|---|---|
|
|
88
|
+
| `committed-secrets` | файлы git в рабочем дереве | CI |
|
|
89
|
+
| `committed-secrets --staged` | изменённое в ИНДЕКСЕ относительно HEAD — то, что уйдёт в коммит | хук коммита |
|
|
90
|
+
| `committed-secrets --staged --full` | весь индекс | хук, если нужен полный |
|
|
91
|
+
| `committed-secrets --history` / `--since <коммит>` | блобы истории (все ссылки / после коммита до HEAD) | первичный аудит |
|
|
92
|
+
| `committed-secrets <пути…>` | только эти файлы, без перечня фикстур и порога | разово |
|
|
93
|
+
|
|
94
|
+
`--format text|json|sarif|gitlab` (по умолчанию `text`), `--output <файл>` — документ машинного формата в файл (без него — в stdout, итог тогда в stderr): SARIF 2.1.0 и отчёт GitLab Secret Detection.
|
|
95
|
+
|
|
96
|
+
GitHub Actions (SARIF — в code scanning):
|
|
97
|
+
|
|
98
|
+
```yaml
|
|
99
|
+
secrets:
|
|
100
|
+
runs-on: ubuntu-latest
|
|
101
|
+
permissions: { contents: read, security-events: write }
|
|
102
|
+
steps:
|
|
103
|
+
- uses: actions/checkout@v5
|
|
104
|
+
- uses: pnpm/action-setup@v4
|
|
105
|
+
- uses: actions/setup-node@v5
|
|
106
|
+
with: { node-version: 24, cache: pnpm }
|
|
107
|
+
- run: pnpm install --frozen-lockfile
|
|
108
|
+
- run: pnpm exec committed-secrets --format sarif --output committed-secrets.sarif
|
|
109
|
+
- if: always()
|
|
110
|
+
uses: github/codeql-action/upload-sarif@v3
|
|
111
|
+
with: { sarif_file: committed-secrets.sarif }
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
MR в GitLab: `--format gitlab --output gl-secret-detection-report.json` и отчёт в `artifacts.reports.secret_detection`. Хук коммита (husky, lefthook, обычный `.git/hooks/pre-commit`): `pnpm exec committed-secrets --staged`.
|
|
115
|
+
|
|
116
|
+
Из подкаталога монорепозитория `--staged` и `--history` судят каталог запуска и печатают пути от него, как `git ls-files`.
|
|
117
|
+
|
|
118
|
+
Тексты сообщений — на русском; коды выхода, структура JSON/SARIF/GitLab и ключи находок стабильны.
|
|
119
|
+
|
|
120
|
+
`--staged` судит индекс мерилом ИЗ ИНДЕКСА: конфигурация, перечень фикстур и базовая линия берутся из индекса, а не с диска — запись фикстуры, добавленная на диск и не добавленная в коммит, его не освобождает. Читаются только изменённые блобы (потоком, `git cat-file --batch`); неизменённое уже прошло гейт при своём коммите, полный скан — в CI. Правка самого гейта (конфигурации, перечня, линии) в индексе включает полный скан индекса; файлы перечня фикстур читаются всегда. Порог выборки в этом режиме считается по записям индекса.
|
|
121
|
+
|
|
122
|
+
Коды выхода: `0` — секретов нет; `1` — находки или нарушения перечня фикстур; `2` — гейт не смог проверить (нет конфигурации или git, неверный аргумент или поле конфигурации, битый JSON, выборка выродилась, вывод git не поместился в буфер — с причиной ENOBUFS, а не «нет git»). «Не смог проверить» отличается и от успеха, и от находки.
|
|
123
|
+
|
|
124
|
+
## Перечень фикстур
|
|
125
|
+
|
|
126
|
+
`fixturesPath` — `[{ file, keys, reason, count? }]`: одноразовые пароли тестовых контейнеров и т.п. Запись освобождает `count` находок КАЖДОГО ключа в файле (по умолчанию одну): второй секрет под тем же ключом — снова находка. Файл поставки (`deliveryPattern`) и код сервиса вне `testCodePatterns` записью не освобождаются; запись, которой соответствует меньше находок, чем она освобождает, — отказ. Ключи находок: имя ключа, `адрес` (пароль в адресе), `PEM`, `PGP`, `токен <вид>`, флаг команды (`redis-cli -a`, `--requirepass`).
|
|
127
|
+
|
|
128
|
+
## Базовая линия
|
|
129
|
+
|
|
130
|
+
Включить гейт в репозитории с историей, не чиня всё сразу: `baselinePath` в конфигурации и `committed-secrets --write-baseline` — текущие находки записываются отпечатками (файл, ключ, отпечаток значения; значений в файле нет). Дальше гейт падает только на НОВЫХ находках; сдвиг строки находку не обновляет, новое значение под тем же ключом — новая находка. Запись линии без находки — не отказ, о ней говорится в итоге.
|
|
131
|
+
|
|
132
|
+
Отпечаток — scrypt (N=1024) от значения с солью «файл + ключ»: он лежит в отчётах CI, и подбор слабого пароля по быстрому хэшу стоил бы секунды; у scrypt — порядка миллисекунды на попытку. Отпечаток не защищает от подбора совсем слабого пароля — значение, попавшее в git, всё равно ротируется.
|
|
133
|
+
|
|
134
|
+
## Гарантии и ограничения
|
|
135
|
+
|
|
136
|
+
- **Описательное значение считается заглушкой** (решение 0.1.1): `super-secret-jwt-token` в поле секрета — слова значения называют секрет, и это не находка. Настоящий секрет в такой форме гейт пропустит; цена обратного — шум на именах полей и членах перечислений.
|
|
137
|
+
- `--staged` по изменённому не видит секрета, закоммиченного в обход хука: его находит CI (рабочее дерево) или `--history`.
|
|
138
|
+
- Онлайн-проверки валидности токена нет и не будет: это отправка секрета наружу.
|
|
139
|
+
- Файлы `.http`/`.rest` (заголовки запросов строками) как класс файла не распознаются: `Authorization: …` в них не судится.
|
|
140
|
+
- Литерал по умолчанию с переносом строки (`=` ⏎ `env.X ?? '…'`) не виден.
|
|
141
|
+
- Случайный литерал из одних строчных букв и цифр с расширением из перечня форматов данных (`x7k2m9q4.json`) читается как имя файла.
|
|
142
|
+
|
|
143
|
+
## Поведение при отказе
|
|
144
|
+
|
|
145
|
+
Fail-closed: нет конфигурации или она неверна, нет git, битый JSON конфигурации или перечня, выборка меньше `minFiles` или без обязательного класса, явный путь не существует, вывод git больше буфера (причина `ENOBUFS`, а не «нет git») — код 2 с причиной одной строкой. Прерванное чтение блобов (`EPIPE`) обработано, а не `uncaughtException`, который выглядел бы как «найдены секреты». Устаревшая запись перечня — отказ: освобождение не переживает то, что освобождало.
|
|
146
|
+
|
|
147
|
+
## Совместимость
|
|
148
|
+
|
|
149
|
+
- Node.js ≥ 24 и git в `PATH` (вызываются `ls-files`, `cat-file --batch`, `diff --cached --relative`, `log`); проверено на git 2.50 локально и на git раннера CI, нижняя граница версии не установлена.
|
|
150
|
+
- Любая раскладка репозитория, в том числе подкаталог монорепозитория; Windows не проверялся (в CI нет Windows-раннера).
|
|
151
|
+
|
|
152
|
+
## Предел
|
|
153
|
+
|
|
154
|
+
Замер `bench/capacity.cjs` (`pnpm build && node bench/capacity.cjs [корень …]`), Node 24 на ноутбуке; 0.4.0 и 0.5.0 — в одном прогоне (исторический замер).
|
|
155
|
+
|
|
156
|
+
| вход | 0.4.0 | 0.5.0 |
|
|
157
|
+
|---|---|---|
|
|
158
|
+
| код TS, 16.6 МБ | 39 МБ/с | 54 МБ/с |
|
|
159
|
+
| `.env.example`, 9.5 МБ | 24 МБ/с | 17 МБ/с |
|
|
160
|
+
| минифицированная строка 1 МБ | 92 МБ/с | 110 МБ/с |
|
|
161
|
+
| base64 одной строкой 2 МБ | 136 МБ/с | 141 МБ/с |
|
|
162
|
+
| `key=` × 260 тыс. в одной строке | 146 МБ/с | 40 МБ/с |
|
|
163
|
+
| `password: ` × 100 тыс. в одной строке | 17 МБ/с (50 тыс. находок) | 24 МБ/с (одна: литерал строки называется один раз) |
|
|
164
|
+
|
|
165
|
+
Весь гейт на синтетическом монорепозитории (16 тыс. файлов, 500 МБ текста; в индексе — один изменённый файл):
|
|
166
|
+
|
|
167
|
+
| режим | 0.4.0 | 0.5.0 |
|
|
168
|
+
|---|---|---|
|
|
169
|
+
| `--staged` (хук) | 20.9 с, пик памяти 1147 МБ | **0.22 с, 69 МБ** |
|
|
170
|
+
| рабочее дерево (CI) | 21.2 с, 879 МБ | 22.2 с, 200 МБ |
|
|
171
|
+
|
|
172
|
+
- `--staged` прежде читал весь индекс одним буфером (потолок 1 ГиБ — дальше отказ с неверной причиной «нет git»). Теперь — только изменённые блобы, потоком: цена хука не растёт с размером репозитория.
|
|
173
|
+
- Рабочее дерево и история читаются по одному файлу: память — один файл, а не репозиторий.
|
|
174
|
+
- Конфигурация сканируется медленнее (17 МБ/с против 24): каждая строка проходит правила команд и структуру YAML. Формы токенов отсекаются подстрокой до регулярного выражения.
|
|
175
|
+
- Катастрофического отката регулярных выражений на длинных строках нет: худшие входы (мегабайтная строка, повтор ключа без значения) линейны.
|
|
176
|
+
|
|
177
|
+
## Разработка и тесты
|
|
178
|
+
|
|
179
|
+
```bash
|
|
180
|
+
pnpm install
|
|
181
|
+
pnpm run typecheck
|
|
182
|
+
pnpm run lint # biome
|
|
183
|
+
pnpm test # сборка, затем jest последовательными группами не больше 300 тестов, 2 воркера
|
|
184
|
+
pnpm run build
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
Набору нужен только git: спеки поднимают временные репозитории и запускают собранный CLI. Ложные находки на строках кода (`fixtures/code-forms/`) — синтетические строки той же формы, что встретились в реальной эксплуатации, вместе с комментариями и JSDoc вокруг, которые влияют на разбор.
|
|
188
|
+
|
|
189
|
+
Что покрыто:
|
|
190
|
+
|
|
191
|
+
- корпус: 36 форм утечки и 12 безопасных форм, у каждой пара «находит ровно одну, с ключом / та же форма без секрета — тишина» (`corpus.spec.ts`), плюс 56 форм 0.5.0 с той же парой (`forms.spec.ts`);
|
|
192
|
+
- формы токенов: у каждого вида полная длина — находка, на символ короче — тишина;
|
|
193
|
+
- встроенные заглушки — каждая сама по себе, рядом — она же с хвостом;
|
|
194
|
+
- класс файла, перечень фикстур (причина, форма записи, код сервиса, `count`), аргументы и порог выборки, ошибки git, ссылки, подмодули, двоичные файлы, UTF-16;
|
|
195
|
+
- `--staged` (мерило из индекса, скан изменённого), история, базовая линия, форматы;
|
|
196
|
+
- значение не встречается в выводе ни в каком формате: ни сырое, ни base64, ни hex, ни пароль, декодированный из base64.
|
|
197
|
+
|
|
198
|
+
Мутации — по одной (замена в исходнике, прогон, откат копией файла): 33 мутанта на прежние пробелы (пустые списки заглушек, длина причины, исключение спек и `testing/`, квантификаторы форм токенов, граница `minFiles`, явный путь, класс Dockerfile и файла без точки, блок кода Markdown, ссылки, подмодули, ошибки git, двоичный файл) и 57 на новые правила — все красные по числу упавших тестов.
|
|
199
|
+
|
|
200
|
+
## Лицензия
|
|
201
|
+
|
|
202
|
+
[MIT](LICENSE) © 2026 Hoshino Tatsuya
|