@critiq/rules 0.0.1 → 0.0.2

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.
Files changed (3) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +211 -143
  3. package/package.json +2 -1
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 [yyyy] [name of copyright owner]
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.md CHANGED
@@ -1,169 +1,237 @@
1
- # @critiq/rules
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/critiq-dev/critiq-rules/main/docs/assets/banner-rules-simple-transparent.png" alt="critiq.dev" style="max-height:400px" />
3
+ </p>
2
4
 
3
- `@critiq/rules` is the default public OSS catalog used by `critiq check`.
5
+ <h1 align="center">Critiq OSS Rules</h1>
6
+ <p align="center">
7
+ <strong>Open source static analysis rules for deterministic code review.<br/>High-signal rules for security, correctness, performance, and code quality.</strong>
8
+ </p>
9
+ <p align="center">
10
+ <a href="https://www.npmjs.com/package/@critiq/rules"><img src="https://img.shields.io/npm/v/%40critiq%2Frules" alt="npm version" /></a>
11
+ <a href="https://github.com/critiq-dev/critiq-rules/tree/main/libs/rules/catalog"><img src="https://img.shields.io/badge/source-GitHub-181717?logo=github" alt="Source" /></a>
12
+ <a href="https://github.com/critiq-dev/critiq-rules/blob/main/libs/rules/catalog/LICENSE"><img src="https://img.shields.io/badge/license-Apache%202.0-blue.svg" alt="License" /></a>
13
+ </p>
4
14
 
5
- It ships:
6
15
 
7
- - `catalog.yaml`
8
- - rule YAML files under `rules/`
9
- - preset membership for `recommended`, `strict`, `security`, and `experimental`
10
16
 
11
- The current catalog is still TypeScript-heavy, but the shared security baseline
12
- also runs across Go and Python. Some rules are pure AST matches, and others
13
- depend on adapter facts such as control-flow, async, structural, and data-flow
14
- observations. A smaller set now depends on check-runner project heuristics for
15
- cross-file auth, coupling, and testing checks.
17
+ Think of Critiq as an extra code reviewer that scans your project for bugs, security issues, performance problems, and risky changes before they turn into production incidents. Instead of only checking style, it focuses on the kinds of problems that usually slip through review and cause real trouble later. You run it locally or in CI, and it gives you deterministic findings you can act on before merging code.
16
18
 
17
- ## What Gets Checked
18
19
 
19
- Representative examples of patterns the catalog flags today:
20
+ It does this by parsing your code, matching it against a curated catalog of explicit rules, and reporting findings with concrete evidence tied to the code that triggered them. That means the output is based on repeatable checks for things like unsafe SQL, missing authorization, repeated IO in loops, and untested critical logic changes, not vague heuristics or style-only linting.
20
21
 
21
- ```ts
22
- console.log('hello');
23
- console.error(error);
24
- debugger;
25
- ```
22
+ <p align="center">
23
+ <img
24
+ src="https://raw.githubusercontent.com/critiq-dev/critiq-core/main/docs/assets/languages.png"
25
+ alt="TypeScript, JavaScript, Node.js, Go, Java, Python, PHP, Ruby, and Rust support"
26
+ />
27
+ </p>
28
+ `@critiq/rules` is the default open source rule catalog for Critiq. It ships `catalog.yaml`, preset membership, and rule YAML files for high-signal checks across TypeScript, JavaScript, Node.js, Go, Java, Python, PHP, Ruby and Rust.
26
29
 
27
- ```ts
28
- async function load() {
29
- fetch('/users');
30
- }
30
+ Use it with [`@critiq/cli`](https://www.npmjs.com/package/@critiq/cli):
31
31
 
32
- async function callApi() {
33
- return fetch('/users');
34
- }
32
+ ```bash
33
+ npm install -D @critiq/cli @critiq/rules
34
+ npx critiq check .
35
35
  ```
36
36
 
37
- ```ts
38
- function read(req: { body: any }) {
39
- const payload = req.body;
40
- return payload.user.profile.city;
41
- }
37
+ Run against a diff:
42
38
 
43
- function maybe(flag: boolean) {
44
- const user = flag ? { name: 'Ada' } : null;
45
- return user.name;
46
- }
39
+ ```bash
40
+ npx critiq check . --base origin/main --head HEAD
47
41
  ```
48
42
 
49
- ```ts
50
- function lookup(cacheMap: Map<string, string>, key: string) {
51
- return cacheMap.get(key);
52
- }
43
+ ## Catalog At A Glance
44
+
45
+ Today the catalog includes `112` rules across `10` categories, with `recommended`, `strict`, `security`, and `experimental` presets.
46
+
47
+ | Category | Rules | What it looks after |
48
+ | --- | ---: | --- |
49
+ | Security | 70 | Injection, auth and session gaps, unsafe transport, sensitive data exposure, unsafe file and HTML handling |
50
+ | Correctness | 15 | Async bugs, null access, control-flow mistakes, missing fallbacks, race conditions |
51
+ | Performance | 10 | Repeated IO, wasted async sequencing, hot-path loops, large retained objects, render churn |
52
+ | Quality | 10 | Error handling gaps, oversized functions, coupling, duplicated logic, and weak test coverage |
53
+ | Logging | 2 | Console usage and unsafe logging patterns |
54
+ | Config | 1 | Configuration access boundaries |
55
+ | Next | 1 | Server and client boundary leaks |
56
+ | Random | 1 | Unsafe randomness in core logic |
57
+ | React | 1 | Cascaded effect fetch patterns |
58
+ | Runtime | 1 | Debug-only statements left in shipped code |
59
+
60
+ ## High-Value Rules In This Catalog
61
+
62
+ | Rule title | Description |
63
+ | --- | --- |
64
+ | `Hardcoded API keys or credentials` | Source files should not embed credential-like string literals. |
65
+ | `Avoid raw or interpolated SQL` | Database query sinks must not receive request-driven or dynamically interpolated SQL text. |
66
+ | `Path traversal via user input` | File access calls must not use request-controlled paths directly. |
67
+ | `Protect deserialization trust boundaries` | Deserializers should not consume untrusted payloads directly across a trust boundary. |
68
+ | `Server-side request forgery` | Outbound requests should not use attacker-controlled targets or private hosts. |
69
+ | `Open redirect via request-controlled target` | Redirect and navigation sinks should not use request-controlled destinations without validation. |
70
+ | `Missing authorization before sensitive action` | Sensitive backend actions should be guarded by an authorization or permission check. |
71
+ | `Use authenticated encryption for secrets and tokens` | Session, cookie, and token encryption should provide integrity protection in the same helper. |
72
+ | `Missing await on async call` | Async functions should not drop direct async calls without awaiting them. |
73
+ | `Repeated IO call inside loop` | Database or network calls inside loops can multiply latency and load. |
74
+ | `Logic change without corresponding test updates` | Diffs that change critical logic should usually update the matching tests in the same change. |
75
+ | `Avoid server/client boundary leaks in Next.js` | Server components should not use browser-only APIs or client-only hooks without an explicit client boundary. |
76
+
77
+ ## Rule Methodology
78
+
79
+ Critiq keeps the OSS catalog intentionally high-signal.
80
+
81
+ - We add rules that change code review outcomes: security flaws, correctness bugs, performance regressions, and maintainability issues with real operational cost.
82
+ - We prefer rules that are deterministic, explainable, and backed by fixtures instead of vague heuristics.
83
+ - We avoid generic style rules that compilers and standard linters already handle well.
84
+ - Every rule should produce an actionable finding with evidence, not restate general guidance.
85
+
86
+ ## More Rules In This Catalog
87
+
88
+ The catalog also includes these `100` additional rules beyond the highlights above.
53
89
 
54
- function parseIdentity(req: { headers: Record<string, string | undefined> }) {
55
- const token = req.headers.authorization;
56
- return decode(token ?? '');
57
- }
58
- ```
90
+ ### Security
59
91
 
60
- ```ts
61
- const query = `SELECT * FROM users WHERE email = '${email}'`;
62
- element.innerHTML = req.body.html;
63
- document.write(userMarkup);
64
- execFile(req.query.command, []);
65
- JSON.parse(req.body.payload);
66
- ```
92
+ | Rule title | Description |
93
+ | --- | --- |
94
+ | `Eval or dynamic code execution` | Eval-like helpers, `vm` execution APIs, and string-evaluated timers should not execute dynamic code. |
95
+ | `Command execution using untrusted input` | Process execution helpers must not receive request-controlled executables or shell-interpreted arguments. |
96
+ | `Avoid unsafe DOM HTML insertion sinks` | `outerHTML`, `document.write*`, and `insertAdjacentHTML` should only receive fixed or explicitly sanitized HTML. |
97
+ | `` Avoid unsafe `dangerouslySetInnerHTML` `` | React `dangerouslySetInnerHTML` should only render fixed or explicitly sanitized HTML. |
98
+ | `` Avoid unsafe `innerHTML` assignment `` | `innerHTML` assignments should only use fixed or explicitly sanitized HTML. |
99
+ | `Missing ownership validation` | Resource identifiers from request input should be checked against the caller before sensitive actions run. |
100
+ | `Authorization enforced only on frontend` | Backend routes should enforce authorization directly instead of relying on frontend gating alone. |
101
+ | `Token or session not validated` | Session and token values from external input should be verified before authentication or identity use. |
102
+ | `Harden auth-bearing cookies` | Auth and session cookies should set HttpOnly, Secure, and SameSite. |
103
+ | `Remove sensitive claims from JWT payloads` | JWT payloads should avoid embedding PII or secrets unless absolutely required. |
104
+ | `Avoid browser token storage` | Access and session tokens should not be stored in long-lived browser storage. |
105
+ | `TLS verification disabled` | Transport clients should not disable certificate verification. |
106
+ | `Insecure HTTP transport` | Outbound transport should not use plain HTTP for sensitive requests. |
107
+ | `Require modern TLS minimum versions` | Transport clients should not explicitly allow SSLv3, TLS 1.0, or TLS 1.1. |
108
+ | `Sensitive data egress to third-party processors` | Sensitive values should not be sent to external processors or outbound SDKs without minimization or redaction. |
109
+ | `Avoid sensitive data in logs and telemetry` | Sensitive fields should not be sent to logging, tracing, or analytics sinks. |
110
+ | `Avoid binding to all interfaces` | Network-facing services should not explicitly bind to every interface unless public exposure is intentional and protected. |
111
+ | `Avoid weak hash algorithms` | Cryptographic hashing should use modern, collision-resistant algorithms. |
112
+ | `Avoid weak cipher algorithms and modes` | Cryptographic ciphers should use modern authenticated modes and approved algorithms. |
113
+ | `Avoid predictable token generation` | Tokens, reset links, and session secrets should be generated from cryptographically strong randomness. |
114
+ | `Use enough entropy for secrets and tokens` | Secret-bearing tokens and secrets should use at least 16 bytes of cryptographic entropy. |
115
+ | `Avoid weak key-generation strength` | Key-generation helpers should use current minimum strengths for RSA, AES, and HMAC keys. |
116
+ | `Validate untrusted input before parser construction` | Untrusted input should be validated before it is used to construct sensitive parsers or runtime objects. |
117
+ | `Missing request timeout or retry protection` | External calls should define timeout, cancellation, or retry behavior before they enter security-sensitive flows. |
118
+ | `Review Datadog RUM user interaction capture` | Datadog Browser RUM should not enable broad user interaction capture without a privacy review. |
119
+ | `Avoid request-driven DynamoDB queries` | DynamoDB query and scan inputs should not be built directly from request input. |
120
+ | `Avoid hardcoded auth secrets` | JWT, session, and strategy secrets should not be embedded directly in source code. |
121
+ | `Constrain module-loading trust boundaries` | `require()` and dynamic `import()` should not resolve modules from untrusted input. |
122
+ | `Do not reflect request origin into CORS policy` | `Access-Control-Allow-Origin` should not be set from request-controlled input. |
123
+ | `Do not allow every origin in CORS policy` | CORS should not fall back to wildcard or implicit allow-all origin settings. |
124
+ | `` Set `Secure` on Express session cookies `` | Express session and cookie-session configs should not disable the `Secure` flag. |
125
+ | `` Set `HttpOnly` on Express session cookies `` | Express session and cookie-session configs should not disable the `HttpOnly` flag. |
126
+ | `Avoid legacy Argon2 password hash modes` | Password hashing should not use `argon2i` or `argon2d` when safer modern modes are available. |
127
+ | `Use secure WebSocket transport` | WebSocket clients should not connect over cleartext `ws://` when sensitive application data is involved. |
128
+ | `Add a JWT revocation hook` | Express JWT middleware should check revocation state when bearer tokens can be invalidated early. |
129
+ | `Keep Handlebars escaping enabled at template trust boundaries` | Server-side Handlebars compilation should not disable HTML escaping with `noEscape: true`. |
130
+ | `Avoid ad hoc HTML sanitization` | Hand-rolled HTML escaping and sanitization should be replaced with vetted sanitizers or safe rendering paths. |
131
+ | `` Verify `message` event origins `` | `message` handlers should validate `event.origin` before trusting cross-window data. |
132
+ | `Avoid request-driven model queries` | Express handlers should not pass raw request objects into NoSQL filters, query helpers, or aggregation pipelines. |
133
+ | `Use constant-time secret comparison` | Secrets and tokens should not be compared with ordinary equality operators. |
134
+ | `Do not persist upload filenames directly` | Upload handlers should not store attacker-controlled filenames without generating or validating a safe local name. |
135
+ | `Constrain local file generation paths` | Local file writes should not derive their destination path from request or upload input. |
136
+ | `Avoid attacker-controlled filesystem read paths` | Direct filesystem read APIs should not consume request- or upload-controlled filenames. |
137
+ | `Avoid permissive file modes` | Files that can carry user or security data should not be created with world-accessible modes. |
138
+ | `` Avoid wildcard `postMessage` targets `` | `postMessage` calls should not use `*` as the target origin when they carry application data. |
139
+ | `Avoid raw HTML with request input` | Request-derived values should not be interpolated into raw HTML strings. |
140
+ | `Avoid sensitive data in thrown errors` | Exceptions and rejection payloads should not include raw secrets or personal data. |
141
+ | `Avoid writing sensitive data to files` | Data exports and local file writes should not persist raw secrets or personal fields. |
142
+ | `Avoid leaking sensitive or diagnostic state` | Logs, stdout or stderr, and direct response sinks should not expose sensitive fields or internal diagnostic detail. |
143
+ | `Do not derive anti-framing headers from request input` | Framing and CSP headers should not be set from request-controlled values. |
144
+ | `Avoid request-controlled format strings` | Logging and formatting helpers should not take request input as the format string itself. |
145
+ | `` Constrain `res.sendFile` to a trusted root `` | `res.sendFile()` should not resolve filenames or options from request input without a trusted root. |
146
+ | `` Constrain `res.render()` trust boundaries `` | Express view names should not cross into server-side rendering from untrusted input. |
147
+ | `Avoid exposed directory listings` | Directory listing middleware should not be enabled on public paths without a deliberate review. |
148
+ | `Override Express session defaults` | Express session middleware should not rely on default session naming and configuration. |
149
+ | `Override Express cookie defaults` | Express session cookie settings should not omit explicit lifetime, scope, and transport attributes. |
150
+ | `Avoid permissive Express session cookie scope` | Express session cookies should not explicitly opt into cross-site or wildcard-style scope. |
151
+ | `Serve static assets before session middleware` | Static assets should be mounted before session middleware when they do not need session state. |
152
+ | `Apply Helmet to Express apps` | Express apps should use Helmet or equivalent header hardening middleware. |
153
+ | `Reduce Express fingerprinting` | Express apps should disable `x-powered-by` or equivalent fingerprinting headers. |
154
+ | `Do not expose debug routes or middleware in production` | Debug handlers, stack-showing middleware, and diagnostic endpoints should stay behind explicit development-only guards. |
155
+ | `Avoid unsafe raw HTTP response output` | Raw response writers should not echo request data into HTML-capable responses without trusted escaping or sanitization. |
67
156
 
68
- ## Rule Register
157
+ ### Correctness
69
158
 
70
- Each entry lists the shipped rule id, its preset membership, and the main
71
- pattern it checks.
159
+ | Rule title | Description |
160
+ | --- | --- |
161
+ | `Always-true or always-false condition` | Flow-control conditions should not resolve to a constant boolean value. |
162
+ | `Implicit undefined return in function` | Functions that return a value on some paths must not fall through implicitly. |
163
+ | `Unhandled promise rejection or async error` | Promise chains started in a function should terminate with explicit rejection handling. |
164
+ | `Incorrect boolean logic (AND/OR misuse)` | Comparison chains on the same value must use the boolean operator that matches the intended logic. |
165
+ | `Blocking call inside async flow` | Async functions should not call synchronous blocking APIs on the hot path. |
166
+ | `Missing default case in switch or conditional dispatch` | Dispatch constructs should include an explicit default or final else path. |
167
+ | `Missing timeout on external call` | External HTTP calls should declare timeout or cancellation behavior. |
168
+ | `Possible null or undefined dereference` | Nullable values should be guarded before property access or invocation. |
169
+ | `Nested property access without existence check` | Deep property chains derived from external input should verify intermediate values before access. |
170
+ | `Unchecked map or dictionary key access` | Lookups should verify key presence before reading from maps or keyed objects. |
171
+ | `Optional value used without fallback` | Optional values should be normalized before arithmetic, concatenation, or other direct use. |
172
+ | `Off-by-one error in loop boundaries` | Index-based loops should not skip the first element or iterate one step past the collection boundary. |
173
+ | `Race condition on shared state` | Async functions that mutate shared state after an await boundary should be reviewed for races. |
174
+ | `Unreachable code after return or throw` | Statements after terminal exits should be removed or moved before the exit. |
72
175
 
73
- ### Logging And Runtime
176
+ ### Performance
74
177
 
75
- - `ts.logging.no-console-log` (`recommended`, `strict`): direct `console.log(...)` calls.
76
- - `ts.logging.no-console-error` (`recommended`, `strict`): direct `console.error(...)` calls.
77
- - `ts.runtime.no-debugger-statement` (`recommended`, `strict`): `debugger;` statements in committed code.
178
+ | Rule title | Description |
179
+ | --- | --- |
180
+ | `Sequential async calls that could run in parallel` | Independent awaited calls in the same block should not serialize unnecessarily. |
181
+ | `Repeated expensive computation` | Repeating the same expensive computation in one block should usually be cached. |
182
+ | `Inefficient data structure usage` | Linear membership checks or key projections should be reviewed for more suitable lookup structures. |
183
+ | `Nested loops in hot path (O(n²) risk)` | Nested loops in the same function should be reviewed for quadratic work on larger inputs. |
184
+ | `Missing batching of operations` | Repeated one-by-one operations inside loops should prefer available batch-style helpers. |
185
+ | `Large payload processing without streaming` | Whole-payload reads of likely large content should be reviewed for streaming alternatives. |
186
+ | `Potential memory leak from unbounded growth` | Shared collections that only grow should be reviewed for eviction or lifecycle boundaries. |
187
+ | `Unnecessarily retained large object` | Large payloads assigned into shared state should be reviewed for shorter lifetimes. |
188
+ | `Unnecessary re-renders from state misuse` | React state setters invoked directly during render should be reviewed for rerender loops. |
78
189
 
79
- ### Correctness
190
+ ### Quality
80
191
 
81
- - `ts.correctness.constant-condition` (`recommended`, `strict`): flow-control tests that resolve to a constant boolean.
82
- - `ts.correctness.missing-await-on-async-call` (`recommended`, `strict`): direct async work dropped inside async functions without `await`.
83
- - `ts.correctness.implicit-undefined-return` (`recommended`, `strict`): functions that return a value on some paths but fall through on others.
84
- - `ts.correctness.unhandled-async-error` (`recommended`, `strict`, `security`): promise chains without a terminal rejection handler.
85
- - `ts.correctness.incorrect-boolean-logic` (`recommended`, `strict`): same-discriminant comparison chains using the wrong boolean operator.
86
- - `ts.correctness.blocking-call-in-async-flow` (`recommended`, `strict`): blocking synchronous APIs inside async code paths.
87
- - `ts.correctness.missing-default-dispatch` (`recommended`, `strict`): `switch` or `if` dispatch chains without a default or final `else`.
88
- - `ts.correctness.missing-timeout-on-external-call` (`recommended`, `strict`, `security`): `fetch` or axios-style calls without timeout or cancellation configuration.
89
- - `ts.correctness.possible-null-dereference` (`recommended`, `strict`): nullable local aliases dereferenced or invoked without a guard.
90
- - `ts.correctness.nested-property-access-without-check` (`recommended`, `strict`): deep request-derived property chains without existence checks.
91
- - `ts.correctness.unchecked-map-key-access` (`recommended`, `strict`): dictionary-like `Map#get(...)` or keyed-object reads without a presence check.
92
- - `ts.correctness.optional-value-without-fallback` (`recommended`, `strict`): optional aliases used directly in expressions without `??`, `||`, or a guard.
93
- - `ts.correctness.off-by-one-loop-boundary` (`recommended`, `strict`): index-based loops that skip the first element or iterate past `.length`.
94
- - `ts.correctness.shared-state-race` (`experimental`): shared or outer-scope state mutated after an `await` boundary.
95
- - `ts.correctness.unreachable-statement` (`recommended`, `strict`): statements after `return` or `throw`.
96
-
97
- ### Quality, Config, And Determinism
98
-
99
- - `ts.quality.swallowed-error` (`recommended`, `strict`): `catch` blocks that drop errors silently.
100
- - `ts.quality.function-too-large-or-complex` (`strict`): oversized or high-complexity functions.
101
- - `ts.quality.duplicate-code-block` (`strict`): large near-identical function bodies duplicated across files.
102
- - `ts.quality.deep-nesting` (`strict`): deeply nested control flow.
103
- - `ts.quality.missing-error-context` (`strict`): `catch` paths that log or rethrow without preserving the original error.
104
- - `ts.quality.tight-module-coupling` (`strict`): direct local import cycles between modules.
105
- - `ts.quality.hardcoded-configuration-values` (`recommended`, `strict`): top-level config-like identifiers or properties bound to literals.
106
- - `ts.quality.magic-numbers-or-strings` (`strict`): non-trivial literals embedded directly in logic.
107
- - `ts.quality.missing-tests-for-critical-logic` (`strict`): critical auth or payment-like logic without a matching test file.
108
- - `ts.quality.logic-change-without-test-updates` (`strict`): changed critical logic in a diff without a changed matching test file.
109
- - `ts.config.no-process-env-outside-config` (`strict`): `process.env.*` access outside config modules.
110
- - `ts.random.no-math-random-in-core` (`strict`): `Math.random()` under `**/core/**`.
192
+ | Rule title | Description |
193
+ | --- | --- |
194
+ | `Errors swallowed silently` | Catch blocks must log, reject, or rethrow failures instead of dropping them silently. |
195
+ | `Function too large or too complex` | Oversized or overly complex functions should be split into smaller units. |
196
+ | `Duplicate code block` | Large duplicated function bodies across files make behavior harder to maintain safely. |
197
+ | `Deep nesting reducing readability` | Deeply nested control flow should be flattened where practical. |
198
+ | `Missing error context or logging` | Catch blocks should include the caught error when they log or rethrow. |
199
+ | `Tight coupling between modules` | Direct import cycles between modules increase coupling and make change boundaries harder to maintain. |
200
+ | `Hardcoded configuration values` | Config-like values should usually come from configuration sources rather than source literals. |
201
+ | `Magic numbers or magic strings` | Non-trivial literals in logic should be named to explain their meaning. |
202
+ | `Missing tests for critical logic` | Critical auth, payment, or similar business logic should have a matching test file. |
111
203
 
112
- ### Performance
204
+ ### Logging
113
205
 
114
- - `ts.performance.sequential-async-calls` (`recommended`, `strict`): independent awaited calls serialized in one block.
115
- - `ts.performance.repeated-io-in-loop` (`recommended`, `strict`): direct or one-hop local IO helpers invoked inside loops.
116
- - `ts.performance.repeated-expensive-computation` (`recommended`, `strict`): the same expensive computation repeated in a local block.
117
- - `ts.performance.inefficient-data-structure-usage` (`recommended`, `strict`): linear membership scans or key-projection checks where a better lookup structure fits.
118
- - `ts.performance.nested-loops-hot-path` (`strict`): loop nesting that creates quadratic hot paths.
119
- - `ts.performance.missing-batch-operations` (`strict`): looped one-by-one helper calls when a batch or bulk variant is available locally.
120
- - `ts.performance.large-payload-without-streaming` (`strict`): likely large file or response payloads loaded eagerly instead of streamed.
121
- - `ts.performance.unbounded-growth-memory-leak` (`strict`): shared collections that only grow and never evict.
122
- - `ts.performance.retained-large-object` (`experimental`): large payloads assigned into shared state and retained longer than needed.
123
- - `ts.performance.unnecessary-rerenders-from-state-misuse` (`experimental`): React state setters called directly during render.
206
+ | Rule title | Description |
207
+ | --- | --- |
208
+ | `Avoid console.log` | Use the project logger instead of console.log. |
209
+ | `Avoid console.error` | Route error logs through the project logger. |
124
210
 
125
- ### Security
211
+ ### Config
212
+
213
+ | Rule title | Description |
214
+ | --- | --- |
215
+ | `` Avoid direct `process.env` access outside config `` | Keep environment variable access inside config modules. |
216
+
217
+ ### Random
218
+
219
+ | Rule title | Description |
220
+ | --- | --- |
221
+ | `` Avoid `Math.random()` in core code `` | Core code should not depend on nondeterministic random generation. |
222
+
223
+ ### React
224
+
225
+ | Rule title | Description |
226
+ | --- | --- |
227
+ | `Avoid cascaded fetches inside React effects` | React effects should not serialize independent fetches that can run in parallel or move server-side. |
228
+
229
+ ### Runtime
230
+
231
+ | Rule title | Description |
232
+ | --- | --- |
233
+ | `` Remove `debugger;` `` | Remove debugger statements before committing source files. |
234
+
235
+ ## License
126
236
 
127
- - `security.no-sql-interpolation` (`recommended`, `strict`, `security`): raw or interpolated SQL text passed into query sinks.
128
- - `ts.security.no-dynamic-execution` (`recommended`, `strict`, `security`): `eval`, `Function`, `vm`, or string-evaluated timer execution.
129
- - `security.no-request-path-file-read` (`recommended`, `strict`, `security`): file reads using request-controlled paths.
130
- - `ts.security.non-literal-fs-filename` (`recommended`, `strict`, `security`): direct filesystem reads using request- or upload-controlled filenames.
131
- - `ts.security.file-generation` (`recommended`, `strict`, `security`): local file writes whose destination path is derived from external input.
132
- - `ts.security.external-file-upload` (`recommended`, `strict`, `security`): upload handlers that persist attacker-controlled filenames directly.
133
- - `security.no-command-execution-with-request-input` (`recommended`, `strict`, `security`): process execution helpers given request-controlled executables or shell-interpreted arguments.
134
- - `ts.security.dangerous-insert-html` (`recommended`, `strict`, `security`): unsafe `outerHTML`, `document.write*`, or `insertAdjacentHTML` use with non-literal, non-sanitized HTML.
135
- - `ts.security.dangerously-set-inner-html` (`recommended`, `strict`, `security`): React `dangerouslySetInnerHTML` given non-literal, non-sanitized HTML.
136
- - `ts.security.no-innerhtml-assignment` (`recommended`, `strict`, `security`): `innerHTML` assignment without fixed or explicitly sanitized HTML.
137
- - `security.no-hardcoded-credentials` (`recommended`, `strict`, `security`): credential-like literals embedded in source.
138
- - `ts.security.handlebars-no-escape` (`recommended`, `strict`, `security`): `Handlebars.compile(..., { noEscape: true })`.
139
- - `ts.security.missing-authorization-before-sensitive-action` (`strict`, `security`): backend-like sensitive handlers without a local authorization guard.
140
- - `ts.security.missing-ownership-validation` (`strict`, `security`): auth-gated handlers acting on caller-supplied resource ids without an ownership check.
141
- - `ts.security.frontend-only-authorization` (`experimental`): frontend-auth-gated literal route calls whose matching backend route lacks authorization.
142
- - `ts.security.token-or-session-not-validated` (`recommended`, `strict`, `security`): token or session values from external input used without same-function validation.
143
- - `security.tls-verification-disabled` (`recommended`, `strict`, `security`): transport clients configured to skip certificate verification.
144
- - `security.insecure-http-transport` (`recommended`, `strict`, `security`): outbound requests sent over plain HTTP to non-local endpoints.
145
- - `security.weak-hash-algorithm` (`recommended`, `strict`, `security`): MD5, SHA-1, or similar weak hashing primitives used in security-sensitive flows.
146
- - `ts.security.weak-cipher-or-mode` (`recommended`, `strict`, `security`): weak or obsolete cipher selections such as ECB mode, DES-family ciphers, RC4, Blowfish, or RSA no-padding.
147
- - `ts.security.predictable-token-generation` (`recommended`, `strict`, `security`): auth-like tokens, invite codes, or reset helpers derived from `Math.random`, timestamps, or other predictable sources.
148
- - `ts.security.insufficiently-random-values` (`recommended`, `strict`, `security`): secret-like values generated from cryptographic APIs with less than 16 bytes of entropy.
149
- - `ts.security.weak-key-strength` (`recommended`, `strict`, `security`): explicit RSA, AES, or HMAC key-generation settings below modern minimum sizes.
150
- - `ts.security.missing-integrity-check` (`recommended`, `strict`, `security`): token or secret encryption helpers using non-AEAD modes or predictable IVs without same-function integrity protection.
151
- - `ts.security.insecure-password-hash-configuration` (`recommended`, `strict`, `security`): legacy or obsolete password-hash configuration such as insecure Argon2 mode selections.
152
- - `ts.security.unvalidated-external-input` (`strict`, `security`): request-derived values used to construct `RegExp` or `URL` without validation.
153
- - `security.unsafe-deserialization` (`recommended`, `strict`, `security`): `JSON.parse`, `yaml.load`, `qs.parse`, or similar deserializers fed external input.
154
- - `ts.security.missing-request-timeout-or-retry` (`strict`, `security`): external calls with neither timeout or cancellation nor retry protection.
155
- - `ts.security.unsanitized-http-response` (`recommended`, `strict`, `security`): raw `res.send`, `res.write`, or `res.end` output of request-derived HTML without trusted escaping or sanitization.
156
- - `ts.security.permissive-file-permissions` (`recommended`, `strict`, `security`): world-accessible file or directory modes on creation helpers or `chmod`.
157
- - `ts.security.user-controlled-sendfile` (`recommended`, `strict`, `security`): `res.sendFile()` paths or options driven by external input without a trusted root.
158
- - `ts.security.exposed-directory-listing` (`recommended`, `strict`, `security`): explicit directory-listing middleware such as `serveIndex`.
159
-
160
- ## Notes
161
-
162
- - `recommended` is the baseline OSS preset.
163
- - `strict` adds higher-noise or more opinionated rules.
164
- - `security` is the security-focused slice of the catalog.
165
- - `experimental` holds narrower heuristics that are shipped but not enabled by
166
- default.
167
-
168
- For executable examples, see the sandbox scenarios under
169
- [`critiq-sandbox/scenarios`](</Users/aavanzyl/Documents/personal/critiq/critiq-sandbox/scenarios>).
237
+ `@critiq/rules` is licensed under [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0). See the package [LICENSE](https://github.com/critiq-dev/critiq-rules/blob/main/libs/rules/catalog/LICENSE).
package/package.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "name": "@critiq/rules",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
4
4
  "private": false,
5
5
  "description": "Public OSS Critiq rule catalog with catalog metadata, shipped rule YAML files, and preset membership.",
6
+ "license": "Apache-2.0",
6
7
  "type": "commonjs",
7
8
  "main": "./src/index.js",
8
9
  "types": "./src/index.d.ts",