@openreachtech/mentsu-npm-audit-gate 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Open Reach Tech Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.ja.md ADDED
@@ -0,0 +1,91 @@
1
+ # @openreachtech/mentsu-npm-audit-gate
2
+
3
+ `npm audit` の結果を判定するゲートです。
4
+
5
+ ## コンセプト
6
+
7
+ `npm audit` は見つけた advisory をすべて報告しますが、パッチ版のない advisory を抱えたまま進めざるを得ないことがあります。このパッケージは `npm audit` を実行し、あなたが挙げた advisory だけを通し、それ以外は重大度を問わず失敗とします。
8
+
9
+ リストの各項目は、通す理由と、外す条件を持ちます。リストに挙がっているのにもうレポートされない項目も失敗とするので、リストが理由より長生きすることはありません。
10
+
11
+ ## インストール
12
+
13
+ Node.js 24.19.0 以上が必要です。
14
+
15
+ ```sh
16
+ npm install @openreachtech/mentsu-npm-audit-gate
17
+ ```
18
+
19
+ ES モジュール(`"type": "module"`)です。ESM の `import` 構文でインポートしてください。
20
+
21
+ ## 使い方
22
+
23
+ リストを `NpmAuditGate` に渡すスクリプトを書き、`npm audit` を判定したいプロジェクトで実行します。
24
+
25
+ リストの項目を検査するには、型ファイルをプロジェクトで 1 度だけ取り込みます。そのうえで、リストに `NpmAuditType.IgnoredAdvisory` を付けます。
26
+
27
+ ```js
28
+ // types/npm-audit-gate.d.ts
29
+ import '@openreachtech/mentsu-npm-audit-gate/types/npm-audit-gate.d.ts'
30
+ ```
31
+
32
+ ```js
33
+ import {
34
+ NpmAuditGate,
35
+ } from '@openreachtech/mentsu-npm-audit-gate'
36
+
37
+ /**
38
+ * @type {Array<NpmAuditType.IgnoredAdvisory>}
39
+ */
40
+ const IGNORED_ADVISORIES = [
41
+ {
42
+ id: 'GHSA-aaaa-bbbb-cccc',
43
+ package: 'alpha-package',
44
+ path: 'beta-package > alpha-package',
45
+ reason: 'No patched release exists, and the package is reached through a development dependency only',
46
+ removeWhen: 'alpha-package publishes a release outside the affected range',
47
+ },
48
+ ]
49
+
50
+ const alphaGate = NpmAuditGate.create({
51
+ ignoredAdvisories: IGNORED_ADVISORIES,
52
+ })
53
+
54
+ process.exitCode = alphaGate.auditAdvisories()
55
+ ```
56
+
57
+ リストに挙がっていない advisory がレポートされたとき、リストの項目がレポートされなくなったとき、`npm audit` がレポートを返さなかったときは、終了コード 1 で終わります。それ以外は 0 で終わります。
58
+
59
+ `NpmAuditType` のほかの型(`Gate`、`Fetcher`、`ReportResponse`、`Logger` と、それぞれの `Ctor`)は、このパッケージの JSDoc を読むので、使うプロジェクトでは、`jsconfig.json` に `allowJs: true` と、3 以上の `maxNodeModuleJsDepth` が必要です。
60
+
61
+ ## API
62
+
63
+ [API リファレンス](https://github.com/openreachtech/mentsu-npm-audit-gate/blob/main/docs/ja/api/index.ja.md)
64
+
65
+ ## コントリビューション
66
+
67
+ バグ報告・機能要望・コード貢献を歓迎します。
68
+
69
+ GitHub Issues からお気軽にご連絡ください。
70
+
71
+ ```sh
72
+ git clone https://github.com/openreachtech/mentsu-npm-audit-gate.git
73
+ cd mentsu-npm-audit-gate
74
+ npm install
75
+ npm run lint
76
+ npm test
77
+ ```
78
+
79
+ ## ライセンス
80
+
81
+ 本プロジェクトは Apache License 2.0 で公開されています。
82
+
83
+ 詳細は [LICENSE ファイル](./LICENSE) を参照してください。
84
+
85
+ ## 開発者
86
+
87
+ [Open Reach Tech Inc.](https://openreach.tech)
88
+
89
+ ## 著作権
90
+
91
+ © 2026 Open Reach Tech Inc.
package/README.md CHANGED
@@ -1,3 +1,91 @@
1
- # Temporary Holding Version
1
+ # @openreachtech/mentsu-npm-audit-gate
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Gate that checks the result of `npm audit`.
4
+
5
+ ## Concept
6
+
7
+ `npm audit` reports every advisory it finds, and a project sometimes has to live with one that has no patched release. This package runs `npm audit`, lets through only the advisories you list, and fails on everything else, at any severity.
8
+
9
+ Each entry of the list carries its reason and the condition for removing it. An entry whose advisory is no longer reported fails the audit too, so the list cannot outlive the reasons it was written for.
10
+
11
+ ## Installation
12
+
13
+ Requires Node.js 24.19.0 or later.
14
+
15
+ ```sh
16
+ npm install @openreachtech/mentsu-npm-audit-gate
17
+ ```
18
+
19
+ It is an ES module (`"type": "module"`); import it with ESM `import` syntax.
20
+
21
+ ## Usage
22
+
23
+ Write a script that hands the list to `NpmAuditGate`, and run it in the project whose `npm audit` it should judge.
24
+
25
+ To check the entries of the list, import the type file once in your project. Then annotate the list with `NpmAuditType.IgnoredAdvisory`.
26
+
27
+ ```js
28
+ // types/npm-audit-gate.d.ts
29
+ import '@openreachtech/mentsu-npm-audit-gate/types/npm-audit-gate.d.ts'
30
+ ```
31
+
32
+ ```js
33
+ import {
34
+ NpmAuditGate,
35
+ } from '@openreachtech/mentsu-npm-audit-gate'
36
+
37
+ /**
38
+ * @type {Array<NpmAuditType.IgnoredAdvisory>}
39
+ */
40
+ const IGNORED_ADVISORIES = [
41
+ {
42
+ id: 'GHSA-aaaa-bbbb-cccc',
43
+ package: 'alpha-package',
44
+ path: 'beta-package > alpha-package',
45
+ reason: 'No patched release exists, and the package is reached through a development dependency only',
46
+ removeWhen: 'alpha-package publishes a release outside the affected range',
47
+ },
48
+ ]
49
+
50
+ const alphaGate = NpmAuditGate.create({
51
+ ignoredAdvisories: IGNORED_ADVISORIES,
52
+ })
53
+
54
+ process.exitCode = alphaGate.auditAdvisories()
55
+ ```
56
+
57
+ The process ends with exit code 1 when an advisory the list does not name is reported, when an entry of the list is no longer reported, or when `npm audit` answers with no report. Otherwise it ends with 0.
58
+
59
+ The other types of `NpmAuditType` (`Gate`, `Fetcher`, `ReportResponse`, `Logger` and their `Ctor`) read the JSDoc of this package, so a project that uses them needs `allowJs: true` and `maxNodeModuleJsDepth` of 3 or more in its `jsconfig.json`.
60
+
61
+ ## API
62
+
63
+ [API reference](https://github.com/openreachtech/mentsu-npm-audit-gate/blob/main/docs/en/api/index.md)
64
+
65
+ ## Contribution
66
+
67
+ Bug reports, feature requests, and code contributions are welcome.
68
+
69
+ Feel free to contact us through GitHub Issues.
70
+
71
+ ```sh
72
+ git clone https://github.com/openreachtech/mentsu-npm-audit-gate.git
73
+ cd mentsu-npm-audit-gate
74
+ npm install
75
+ npm run lint
76
+ npm test
77
+ ```
78
+
79
+ ## License
80
+
81
+ This project is released under the Apache License 2.0.
82
+
83
+ For more details, please see [in the LICENSE file](./LICENSE).
84
+
85
+ ## Developer
86
+
87
+ [Open Reach Tech Inc.](https://openreach.tech)
88
+
89
+ ## Copyright
90
+
91
+ © 2026 Open Reach Tech Inc.
@@ -0,0 +1,134 @@
1
+ import nodeChildProcess from 'node:child_process'
2
+
3
+ import ProcessLogger from './ProcessLogger.js'
4
+
5
+ /**
6
+ * Largest output `npm audit` may produce, in bytes.
7
+ *
8
+ * @type {number}
9
+ */
10
+ const MAX_AUDIT_OUTPUT_BYTES = 64 * 1024 * 1024
11
+
12
+ /**
13
+ * Fetch the report `npm audit --json` prints.
14
+ */
15
+ export default class AuditFetcher {
16
+ /**
17
+ * @param {{
18
+ * childProcess: typeof nodeChildProcess
19
+ * processLogger: ProcessLogger
20
+ * }} params - Parameters of this constructor.
21
+ */
22
+ constructor ({
23
+ childProcess,
24
+ processLogger,
25
+ }) {
26
+ this.childProcess = childProcess
27
+ this.processLogger = processLogger
28
+ }
29
+
30
+ /**
31
+ * Factory method.
32
+ *
33
+ * @template {X extends typeof AuditFetcher ? X : never} T, X
34
+ * @param {{
35
+ * childProcess?: typeof nodeChildProcess
36
+ * processLogger?: ProcessLogger
37
+ * }} [params] - Parameters for the factory method.
38
+ * @returns {InstanceType<T>} Instance of this class.
39
+ * @this {T}
40
+ * @public
41
+ */
42
+ static create ({
43
+ childProcess = this.childProcess,
44
+ processLogger = this.createProcessLogger(),
45
+ } = {}) {
46
+ return /** @type {InstanceType<T>} */ (
47
+ new this({
48
+ childProcess,
49
+ processLogger,
50
+ })
51
+ )
52
+ }
53
+
54
+ /**
55
+ * get: `node:child_process` module.
56
+ *
57
+ * @returns {typeof nodeChildProcess} `node:child_process` module.
58
+ */
59
+ static get childProcess () {
60
+ return nodeChildProcess
61
+ }
62
+
63
+ /**
64
+ * get: Constructor of `ProcessLogger`.
65
+ *
66
+ * @returns {typeof ProcessLogger} Constructor of `ProcessLogger`.
67
+ */
68
+ static get ProcessLoggerCtor () {
69
+ return ProcessLogger
70
+ }
71
+
72
+ /**
73
+ * Create a `ProcessLogger`.
74
+ *
75
+ * @returns {ProcessLogger} Instance of `ProcessLogger`.
76
+ */
77
+ static createProcessLogger () {
78
+ return this.ProcessLoggerCtor.create()
79
+ }
80
+
81
+ /**
82
+ * Fetch the report `npm audit --json` prints.
83
+ *
84
+ * @returns {AuditReport | null} Report, or null when npm printed none.
85
+ * @public
86
+ */
87
+ fetchReport () {
88
+ const auditResult = this.childProcess.spawnSync(
89
+ 'npm',
90
+ [
91
+ 'audit',
92
+ '--json',
93
+ ],
94
+ {
95
+ encoding: 'utf8',
96
+ maxBuffer: MAX_AUDIT_OUTPUT_BYTES,
97
+ }
98
+ )
99
+
100
+ // npm exits 1 whenever it finds an advisory, so only its stdout says whether a report came back.
101
+ try {
102
+ return JSON.parse(auditResult.stdout)
103
+ } catch {
104
+ this.processLogger.logError({
105
+ text: auditResult.stderr,
106
+ })
107
+
108
+ return null
109
+ }
110
+ }
111
+ }
112
+
113
+ /**
114
+ * @typedef {{
115
+ * name: string
116
+ * severity: string
117
+ * range: string
118
+ * title: string
119
+ * url: string
120
+ * }} AuditAdvisory
121
+ */
122
+
123
+ /**
124
+ * @typedef {{
125
+ * error?: *
126
+ * vulnerabilities?: Record<string, {
127
+ * via: Array<string | AuditAdvisory>
128
+ * }>
129
+ * }} AuditReport
130
+ */
131
+
132
+ /**
133
+ * @typedef {*} BooleanLike
134
+ */
@@ -0,0 +1,343 @@
1
+ /**
2
+ * Judge an `npm audit` report, deliberately letting through the advisories
3
+ * the caller lists, as a stopgap until a release fixes them.
4
+ *
5
+ * It fails on an advisory the list does not name, at any severity,
6
+ * on an advisory the list names that is no longer reported,
7
+ * and on an `npm audit` that answers with an error instead of a report.
8
+ */
9
+ export default class AuditReportResponse {
10
+ /**
11
+ * @param {{
12
+ * ignoredAdvisories: Array<NpmAuditType.IgnoredAdvisory>
13
+ * report: AuditReport | null
14
+ * }} params - Parameters of this constructor.
15
+ */
16
+ constructor ({
17
+ ignoredAdvisories,
18
+ report,
19
+ }) {
20
+ this.ignoredAdvisories = ignoredAdvisories
21
+ this.report = report
22
+ }
23
+
24
+ /**
25
+ * Factory method.
26
+ *
27
+ * @template {X extends typeof AuditReportResponse ? X : never} T, X
28
+ * @param {{
29
+ * ignoredAdvisories: Array<NpmAuditType.IgnoredAdvisory>
30
+ * report: AuditReport | null
31
+ * }} params - Parameters for the factory method.
32
+ * @returns {InstanceType<T>} Instance of this class.
33
+ * @this {T}
34
+ * @public
35
+ */
36
+ static create ({
37
+ ignoredAdvisories,
38
+ report,
39
+ }) {
40
+ return /** @type {InstanceType<T>} */ (
41
+ new this({
42
+ ignoredAdvisories,
43
+ report,
44
+ })
45
+ )
46
+ }
47
+
48
+ /**
49
+ * get: Name of the file listing the advisories to let through.
50
+ *
51
+ * @returns {string} File name.
52
+ */
53
+ static get ignoredAdvisoriesFileName () {
54
+ return 'IGNORED_ADVISORIES.js'
55
+ }
56
+
57
+ /**
58
+ * get: Pattern picking a GHSA id off the end of an advisory url.
59
+ *
60
+ * @returns {RegExp} Pattern with the named group `id`.
61
+ */
62
+ static get advisoryIdPattern () {
63
+ return /(?<id>GHSA(?:-[0-9a-z]{4}){3})$/u
64
+ }
65
+
66
+ /**
67
+ * Extract the GHSA id of an advisory.
68
+ *
69
+ * @param {{
70
+ * advisory: AuditAdvisory
71
+ * }} params - Parameters.
72
+ * @returns {string} GHSA id, or the whole url where it carries none.
73
+ */
74
+ static extractAdvisoryId ({
75
+ advisory,
76
+ }) {
77
+ const matched = advisory.url.match(this.advisoryIdPattern)
78
+
79
+ return matched?.groups
80
+ ?.id
81
+ ?? advisory.url
82
+ }
83
+
84
+ /**
85
+ * get: Constructor of this class.
86
+ *
87
+ * @returns {typeof AuditReportResponse} Constructor of this class.
88
+ */
89
+ get Ctor () {
90
+ return /** @type {typeof AuditReportResponse} */ (this.constructor)
91
+ }
92
+
93
+ /**
94
+ * Check whether the report can be judged.
95
+ *
96
+ * @returns {BooleanLike} Whether the report carries vulnerabilities and no error.
97
+ * @public
98
+ */
99
+ hasUsableReport () {
100
+ if (
101
+ !this.report
102
+ || this.report.error
103
+ ) {
104
+ return false
105
+ }
106
+
107
+ return this.report.vulnerabilities
108
+ ?? false
109
+ }
110
+
111
+ /**
112
+ * Build the line saying no report came back.
113
+ *
114
+ * @returns {string} Line to print.
115
+ * @public
116
+ */
117
+ buildNoReportMessage () {
118
+ const error = this.report?.error
119
+ ?? null
120
+
121
+ return `🤔 npm audit answered with no report, so nothing was checked: ${JSON.stringify(error)}`
122
+ }
123
+
124
+ /**
125
+ * Build the lines naming each listed advisory that is still reported.
126
+ *
127
+ * @returns {Array<string>} Lines to print.
128
+ * @public
129
+ */
130
+ buildIgnoredLines () {
131
+ return this.collectMetIgnores()
132
+ .flatMap(it => [
133
+ `⚠️ ignored: ${it.id} (${it.package}) via ${it.path}`,
134
+ ` reason: ${it.reason}`,
135
+ ` remove when: ${it.removeWhen}`,
136
+ ])
137
+ }
138
+
139
+ /**
140
+ * Collect the listed advisories that are still reported.
141
+ *
142
+ * @returns {Array<NpmAuditType.IgnoredAdvisory>} Advisories of the list.
143
+ */
144
+ collectMetIgnores () {
145
+ return this.ignoredAdvisories
146
+ .filter(it => this.isReported({
147
+ id: it.id,
148
+ }))
149
+ }
150
+
151
+ /**
152
+ * Check whether the report names an advisory.
153
+ *
154
+ * @param {{
155
+ * id: string
156
+ * }} params - Parameters.
157
+ * @returns {BooleanLike} Whether the advisory is reported.
158
+ */
159
+ isReported ({
160
+ id,
161
+ }) {
162
+ return this.collectAdvisoryIds()
163
+ .includes(id)
164
+ }
165
+
166
+ /**
167
+ * Collect the ids of the advisories the report names, each once.
168
+ *
169
+ * @returns {Array<string>} GHSA ids in the order they first appear.
170
+ */
171
+ collectAdvisoryIds () {
172
+ const advisoryIds = this.collectAdvisories()
173
+ .map(it => this.Ctor.extractAdvisoryId({
174
+ advisory: it,
175
+ }))
176
+
177
+ return [
178
+ ...new Set(advisoryIds),
179
+ ]
180
+ }
181
+
182
+ /**
183
+ * Collect the advisories the report names, as often as it names them.
184
+ *
185
+ * @returns {Array<AuditAdvisory>} Advisories of the report.
186
+ */
187
+ collectAdvisories () {
188
+ const vulnerabilities = this.report?.vulnerabilities
189
+ ?? {}
190
+
191
+ return Object.values(vulnerabilities)
192
+ .flatMap(it => it.via)
193
+ .filter(it => typeof it === 'object')
194
+ }
195
+
196
+ /**
197
+ * Build the lines naming each failure.
198
+ *
199
+ * @returns {Array<string>} Lines to print.
200
+ * @public
201
+ */
202
+ buildFailureLines () {
203
+ return [
204
+ ...this.buildUnignoredLines(),
205
+ ...this.buildStaleLines(),
206
+ ]
207
+ }
208
+
209
+ /**
210
+ * Build the lines naming each reported advisory the list does not name.
211
+ *
212
+ * @returns {Array<string>} Lines to print.
213
+ */
214
+ buildUnignoredLines () {
215
+ return this.collectAdvisoryIds()
216
+ .filter(it => !this.isIgnored({
217
+ id: it,
218
+ }))
219
+ .map(it => this.buildUnignoredLine({
220
+ id: it,
221
+ }))
222
+ }
223
+
224
+ /**
225
+ * Check whether the list names an advisory.
226
+ *
227
+ * @param {{
228
+ * id: string
229
+ * }} params - Parameters.
230
+ * @returns {BooleanLike} Whether the advisory is listed.
231
+ */
232
+ isIgnored ({
233
+ id,
234
+ }) {
235
+ return this.ignoredAdvisories
236
+ .some(it => it.id === id)
237
+ }
238
+
239
+ /**
240
+ * Build the line naming a reported advisory the list does not name.
241
+ *
242
+ * @param {{
243
+ * id: string
244
+ * }} params - Parameters.
245
+ * @returns {string} Line to print.
246
+ */
247
+ buildUnignoredLine ({
248
+ id,
249
+ }) {
250
+ // The id comes from the report itself, so the advisory is always found.
251
+ const advisory = /** @type {AuditAdvisory} */ (
252
+ this.findAdvisory({
253
+ id,
254
+ })
255
+ )
256
+
257
+ return `🚨 not ignored: ${id} ${advisory.severity} ${advisory.name} ${advisory.range} — ${advisory.title}`
258
+ }
259
+
260
+ /**
261
+ * Find the advisory of an id, taking the last one the report names under it.
262
+ *
263
+ * @param {{
264
+ * id: string
265
+ * }} params - Parameters.
266
+ * @returns {AuditAdvisory | null} Advisory, or null where the report names none.
267
+ */
268
+ findAdvisory ({
269
+ id,
270
+ }) {
271
+ return this.collectAdvisories()
272
+ .findLast(it => this.Ctor.extractAdvisoryId({
273
+ advisory: it,
274
+ }) === id)
275
+ ?? null
276
+ }
277
+
278
+ /**
279
+ * Build the lines naming each listed advisory that is no longer reported.
280
+ *
281
+ * @returns {Array<string>} Lines to print.
282
+ */
283
+ buildStaleLines () {
284
+ return this.ignoredAdvisories
285
+ .filter(it => !this.isReported({
286
+ id: it.id,
287
+ }))
288
+ .map(it => `🗑️ stale ignore: ${it.id} (${it.package}) is no longer reported; remove it from ${this.Ctor.ignoredAdvisoriesFileName}`)
289
+ }
290
+
291
+ /**
292
+ * Build the line summing up the check.
293
+ *
294
+ * @returns {string} Line to print.
295
+ * @public
296
+ */
297
+ buildSummaryLine () {
298
+ const advisoryCount = this.countAdvisories()
299
+ const metIgnoreCount = this.countMetIgnores()
300
+ const failureCount = this.countFailures()
301
+
302
+ return `checked ${advisoryCount} advisory(ies), ${metIgnoreCount} ignored, ${failureCount} failure(s)`
303
+ }
304
+
305
+ /**
306
+ * Count the advisories the report names, each once.
307
+ *
308
+ * @returns {number} Number of advisories.
309
+ */
310
+ countAdvisories () {
311
+ return this.collectAdvisoryIds().length
312
+ }
313
+
314
+ /**
315
+ * Count the listed advisories that are still reported.
316
+ *
317
+ * @returns {number} Number of advisories.
318
+ */
319
+ countMetIgnores () {
320
+ return this.collectMetIgnores().length
321
+ }
322
+
323
+ /**
324
+ * Count the failures.
325
+ *
326
+ * @returns {number} Number of failures.
327
+ * @public
328
+ */
329
+ countFailures () {
330
+ return this.buildFailureLines().length
331
+ }
332
+ }
333
+
334
+ /**
335
+ * @typedef {*} BooleanLike
336
+ */
337
+
338
+ /**
339
+ * @import {
340
+ * AuditAdvisory,
341
+ * AuditReport,
342
+ * } from './AuditFetcher.js'
343
+ */
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Exit codes a process running `NpmAuditGate` ends with.
3
+ *
4
+ * @type {{
5
+ * SUCCESS: number
6
+ * FAILURE: number
7
+ * }}
8
+ */
9
+ const EXIT_CODE = {
10
+ SUCCESS: 0,
11
+ FAILURE: 1,
12
+ }
13
+
14
+ export default EXIT_CODE
@@ -0,0 +1,179 @@
1
+ import AuditFetcher from './AuditFetcher.js'
2
+ import AuditReportResponse from './AuditReportResponse.js'
3
+ import EXIT_CODE from './EXIT_CODE.js'
4
+ import ProcessLogger from './ProcessLogger.js'
5
+
6
+ /**
7
+ * Fetch an `npm audit` report, judge it against the advisories
8
+ * the caller lists, and print the outcome.
9
+ */
10
+ export default class NpmAuditGate {
11
+ /**
12
+ * @param {{
13
+ * ignoredAdvisories: Array<NpmAuditType.IgnoredAdvisory>
14
+ * auditFetcher: AuditFetcher
15
+ * processLogger: ProcessLogger
16
+ * }} params - Parameters of this constructor.
17
+ */
18
+ constructor ({
19
+ ignoredAdvisories,
20
+ auditFetcher,
21
+ processLogger,
22
+ }) {
23
+ this.ignoredAdvisories = ignoredAdvisories
24
+ this.auditFetcher = auditFetcher
25
+ this.processLogger = processLogger
26
+ }
27
+
28
+ /**
29
+ * Factory method.
30
+ *
31
+ * @template {X extends typeof NpmAuditGate ? X : never} T, X
32
+ * @param {{
33
+ * ignoredAdvisories: Array<NpmAuditType.IgnoredAdvisory>
34
+ * auditFetcher?: AuditFetcher
35
+ * processLogger?: ProcessLogger
36
+ * }} params - Parameters for the factory method.
37
+ * @returns {InstanceType<T>} Instance of this class.
38
+ * @this {T}
39
+ * @public
40
+ */
41
+ static create ({
42
+ ignoredAdvisories,
43
+ auditFetcher = this.createAuditFetcher(),
44
+ processLogger = this.createProcessLogger(),
45
+ }) {
46
+ return /** @type {InstanceType<T>} */ (
47
+ new this({
48
+ ignoredAdvisories,
49
+ auditFetcher,
50
+ processLogger,
51
+ })
52
+ )
53
+ }
54
+
55
+ /**
56
+ * get: Constructor of `AuditFetcher`.
57
+ *
58
+ * @returns {typeof AuditFetcher} Constructor of `AuditFetcher`.
59
+ */
60
+ static get AuditFetcherCtor () {
61
+ return AuditFetcher
62
+ }
63
+
64
+ /**
65
+ * get: Constructor of `AuditReportResponse`.
66
+ *
67
+ * @returns {typeof AuditReportResponse} Constructor of `AuditReportResponse`.
68
+ */
69
+ static get AuditReportResponseCtor () {
70
+ return AuditReportResponse
71
+ }
72
+
73
+ /**
74
+ * get: Constructor of `ProcessLogger`.
75
+ *
76
+ * @returns {typeof ProcessLogger} Constructor of `ProcessLogger`.
77
+ */
78
+ static get ProcessLoggerCtor () {
79
+ return ProcessLogger
80
+ }
81
+
82
+ /**
83
+ * Create an `AuditFetcher`.
84
+ *
85
+ * @returns {AuditFetcher} Instance of `AuditFetcher`.
86
+ */
87
+ static createAuditFetcher () {
88
+ return this.AuditFetcherCtor.create()
89
+ }
90
+
91
+ /**
92
+ * Create an `AuditReportResponse`.
93
+ *
94
+ * @param {{
95
+ * ignoredAdvisories: Array<NpmAuditType.IgnoredAdvisory>
96
+ * report: AuditReport | null
97
+ * }} params - Parameters.
98
+ * @returns {AuditReportResponse} Instance of `AuditReportResponse`.
99
+ */
100
+ static createAuditReportResponse ({
101
+ ignoredAdvisories,
102
+ report,
103
+ }) {
104
+ return this.AuditReportResponseCtor.create({
105
+ ignoredAdvisories,
106
+ report,
107
+ })
108
+ }
109
+
110
+ /**
111
+ * Create a `ProcessLogger`.
112
+ *
113
+ * @returns {ProcessLogger} Instance of `ProcessLogger`.
114
+ */
115
+ static createProcessLogger () {
116
+ return this.ProcessLoggerCtor.create()
117
+ }
118
+
119
+ /**
120
+ * get: Constructor of this class.
121
+ *
122
+ * @returns {typeof NpmAuditGate} Constructor of this class.
123
+ */
124
+ get Ctor () {
125
+ return /** @type {typeof NpmAuditGate} */ (this.constructor)
126
+ }
127
+
128
+ /**
129
+ * Fetch the report, judge it against the list, and print the outcome.
130
+ *
131
+ * @returns {number} Exit code: `EXIT_CODE.SUCCESS` when nothing fails, otherwise `EXIT_CODE.FAILURE`.
132
+ * @public
133
+ */
134
+ auditAdvisories () {
135
+ const report = this.auditFetcher.fetchReport()
136
+ const auditReportResponse = this.Ctor.createAuditReportResponse({
137
+ ignoredAdvisories: this.ignoredAdvisories,
138
+ report,
139
+ })
140
+
141
+ if (!auditReportResponse.hasUsableReport()) {
142
+ this.processLogger.logError({
143
+ text: `${auditReportResponse.buildNoReportMessage()}\n`,
144
+ })
145
+
146
+ return EXIT_CODE.FAILURE
147
+ }
148
+
149
+ auditReportResponse.buildIgnoredLines()
150
+ .forEach(it => {
151
+ this.processLogger.logMessage({
152
+ text: `${it}\n`,
153
+ })
154
+ })
155
+ auditReportResponse.buildFailureLines()
156
+ .forEach(it => {
157
+ this.processLogger.logError({
158
+ text: `${it}\n`,
159
+ })
160
+ })
161
+ this.processLogger.logMessage({
162
+ text: `${auditReportResponse.buildSummaryLine()}\n`,
163
+ })
164
+
165
+ return auditReportResponse.countFailures() === 0
166
+ ? EXIT_CODE.SUCCESS
167
+ : EXIT_CODE.FAILURE
168
+ }
169
+ }
170
+
171
+ /**
172
+ * @typedef {*} BooleanLike
173
+ */
174
+
175
+ /**
176
+ * @import {
177
+ * AuditReport,
178
+ * } from './AuditFetcher.js'
179
+ */
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Write texts to the standard output and the standard error of the process.
3
+ */
4
+ export default class ProcessLogger {
5
+ /**
6
+ * @param {{
7
+ * processClient: typeof process
8
+ * }} params - Parameters of this constructor.
9
+ */
10
+ constructor ({
11
+ processClient,
12
+ }) {
13
+ this.processClient = processClient
14
+ }
15
+
16
+ /**
17
+ * Factory method.
18
+ *
19
+ * @template {X extends typeof ProcessLogger ? X : never} T, X
20
+ * @param {{
21
+ * processClient?: typeof process
22
+ * }} [params] - Parameters for the factory method.
23
+ * @returns {InstanceType<T>} Instance of this class.
24
+ * @this {T}
25
+ * @public
26
+ */
27
+ static create ({
28
+ processClient = this.processClient,
29
+ } = {}) {
30
+ return /** @type {InstanceType<T>} */ (
31
+ new this({
32
+ processClient,
33
+ })
34
+ )
35
+ }
36
+
37
+ /**
38
+ * get: Current process.
39
+ *
40
+ * @returns {typeof process} Current process.
41
+ */
42
+ static get processClient () {
43
+ return process
44
+ }
45
+
46
+ /**
47
+ * get: Standard output stream.
48
+ *
49
+ * @returns {typeof process.stdout} Standard output stream.
50
+ */
51
+ get stdout () {
52
+ return this.processClient.stdout
53
+ }
54
+
55
+ /**
56
+ * get: Standard error stream.
57
+ *
58
+ * @returns {typeof process.stderr} Standard error stream.
59
+ */
60
+ get stderr () {
61
+ return this.processClient.stderr
62
+ }
63
+
64
+ /**
65
+ * Write a text to the standard output stream.
66
+ *
67
+ * @param {{
68
+ * text: string
69
+ * }} params - Parameters.
70
+ * @returns {BooleanLike} Whether the stream accepted the text.
71
+ * @public
72
+ */
73
+ logMessage ({
74
+ text,
75
+ }) {
76
+ return this.stdout.write(text)
77
+ }
78
+
79
+ /**
80
+ * Write a text to the standard error stream.
81
+ *
82
+ * @param {{
83
+ * text: string
84
+ * }} params - Parameters.
85
+ * @returns {BooleanLike} Whether the stream accepted the text.
86
+ * @public
87
+ */
88
+ logError ({
89
+ text,
90
+ }) {
91
+ return this.stderr.write(text)
92
+ }
93
+ }
94
+
95
+ /**
96
+ * @typedef {*} BooleanLike
97
+ */
package/lib/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { default as AuditFetcher } from './AuditFetcher.js'
2
+ export { default as AuditReportResponse } from './AuditReportResponse.js'
3
+ export { default as EXIT_CODE } from './EXIT_CODE.js'
4
+ export { default as NpmAuditGate } from './NpmAuditGate.js'
5
+ export { default as ProcessLogger } from './ProcessLogger.js'
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@openreachtech/mentsu-npm-audit-gate",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.0",
4
+ "description": "Gate that checks the result of npm audit",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "files": [
8
+ "lib/",
9
+ "types/",
10
+ "!types/env/**"
11
+ ],
12
+ "types": "./types/index.d.ts",
13
+ "scripts": {
14
+ "l": "npm run lint",
15
+ "lint": "eslint .",
16
+ "test": "export NODE_OPTIONS=\"$NODE_OPTIONS --experimental-vm-modules\"; export NODE_ENV=development; jest"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/openreachtech/mentsu-npm-audit-gate.git"
21
+ },
22
+ "author": "Open Reach Tech Inc.",
23
+ "license": "Apache-2.0",
24
+ "bugs": {
25
+ "url": "https://github.com/openreachtech/mentsu-npm-audit-gate/issues"
26
+ },
27
+ "homepage": "https://github.com/openreachtech/mentsu-npm-audit-gate#readme",
28
+ "engines": {
29
+ "node": ">=24.19.0",
30
+ "npm": ">=11.17.0"
31
+ },
32
+ "dependencies": {
33
+ },
34
+ "devDependencies": {
35
+ "@openreachtech/eslint-config": "^4.5.0",
36
+ "@openreachtech/jest-constructor-spy": "^1.1.2",
37
+ "@openreachtech/jest-deep-containing": "^1.0.2",
38
+ "@openreachtech/jest-expect-each": "^1.0.3",
39
+ "@openreachtech/mentsu-rootpath": "^1.1.3",
40
+ "@openreachtech/renchan-env": "^1.0.6",
41
+ "@types/jest": "^30.0.0",
42
+ "eslint": "^9.39.5",
43
+ "jest": "^30.5.2"
44
+ },
45
+ "overrides": {
46
+ "brace-expansion@1": "^1.1.21",
47
+ "brace-expansion@5": "^5.0.12",
48
+ "glob": "^13.0.6"
49
+ },
50
+ "allowScripts": {
51
+ "@parcel/watcher": false,
52
+ "unrs-resolver": false
53
+ }
54
+ }
@@ -0,0 +1,5 @@
1
+ export { default as AuditFetcher } from '../lib/AuditFetcher.js'
2
+ export { default as AuditReportResponse } from '../lib/AuditReportResponse.js'
3
+ export { default as EXIT_CODE } from '../lib/EXIT_CODE.js'
4
+ export { default as NpmAuditGate } from '../lib/NpmAuditGate.js'
5
+ export { default as ProcessLogger } from '../lib/ProcessLogger.js'
@@ -0,0 +1,28 @@
1
+ import type AuditFetcher from '../lib/AuditFetcher.js'
2
+ import type AuditReportResponse from '../lib/AuditReportResponse.js'
3
+ import type NpmAuditGate from '../lib/NpmAuditGate.js'
4
+ import type ProcessLogger from '../lib/ProcessLogger.js'
5
+
6
+ declare global {
7
+ namespace NpmAuditType {
8
+ type Gate = NpmAuditGate
9
+ type GateCtor = typeof NpmAuditGate
10
+
11
+ type Fetcher = AuditFetcher
12
+ type FetcherCtor = typeof AuditFetcher
13
+
14
+ type ReportResponse = AuditReportResponse
15
+ type ReportResponseCtor = typeof AuditReportResponse
16
+
17
+ type Logger = ProcessLogger
18
+ type LoggerCtor = typeof ProcessLogger
19
+
20
+ type IgnoredAdvisory = {
21
+ id: string
22
+ package: string
23
+ path: string
24
+ reason: string
25
+ removeWhen: string
26
+ }
27
+ }
28
+ }