@ihelpee/prumo-plugin-node-next 0.0.0-stage → 0.8.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/LICENSE +202 -0
- package/README.md +113 -2
- package/dist/ast.d.ts +68 -0
- package/dist/ast.d.ts.map +1 -0
- package/dist/ast.js +418 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/rules.d.ts +48 -0
- package/dist/rules.d.ts.map +1 -0
- package/dist/rules.js +238 -0
- package/package.json +34 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,114 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @ihelpee/prumo-plugin-node-next 🚦
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<p align="center">
|
|
4
|
+
<a href="https://www.npmjs.com/package/@ihelpee/prumo-plugin-node-next"><img src="https://img.shields.io/npm/v/@ihelpee/prumo-plugin-node-next?logo=npm&color=cb3837&label=npm" alt="npm version" /></a>
|
|
5
|
+
<a href="https://www.apache.org/licenses/LICENSE-2.0"><img src="https://img.shields.io/badge/license-Apache--2.0-blue?logo=apache&logoColor=white" alt="Apache 2.0 license" /></a>
|
|
6
|
+
<a href="https://github.com/ihelpee/prumo"><img src="https://img.shields.io/badge/telemetry-zero-brightgreen?logo=ghost&logoColor=white" alt="Zero telemetry" /></a>
|
|
7
|
+
<a href="https://nodejs.org/"><img src="https://img.shields.io/badge/node-%3E%3D20.11-339933?logo=node.js&logoColor=white" alt="Node >= 20.11" /></a>
|
|
8
|
+
</p>
|
|
9
|
+
|
|
10
|
+
> Official Next.js **App Router** architectural invariant plugin for [Prumo](https://www.npmjs.com/package/@ihelpee/prumo) — the deterministic gatekeeper and business guardrails for AI-assisted engineering.
|
|
11
|
+
|
|
12
|
+
No App Router, a **Server Action é um endpoint HTTP público que se disfarça de função interna** e `"use client"` marca um **entry point de bundle**, não um arquivo. Um agente que gera código por IA escreve a action como se fosse uma chamada interna confiável; o compilador transforma cada `export` de `"use server"` num `POST` alcançável por qualquer um. Este plugin fiscaliza essa fronteira com AST estática pura — **sem boot do Next, sem `react`, sem `next build`**.
|
|
13
|
+
|
|
14
|
+
## Invariantes
|
|
15
|
+
|
|
16
|
+
| id | sev. | o footgun | fronteira honesta (o que NÃO pega) |
|
|
17
|
+
|---|---|---|---|
|
|
18
|
+
| `server-action-mutation-guarded` | error | Server Action / Route Handler de mutação escreve no banco sem re-verificar auth **no próprio corpo, antes da escrita** | leitura pura (`GET`); guard delegado a um DAL `server-only` que faz o auth dentro |
|
|
19
|
+
| `client-boundary-leak-prevented` | error | o grafo do cliente (alcançável de um `"use client"`) importa ORM/cliente de banco, módulo de segredo ou lê `process.env` não-`NEXT_PUBLIC_` | módulo compartilhado sem ORM/segredo; `await import(nomeVariavel)` (limitação declarada) |
|
|
20
|
+
| `server-action-input-validated` | error | Server Action muta estado sem validar input por schema (Zod/Valibot) **antes** do banco | schema valida **shape, não posse** — IDOR é checagem separada, nunca reportada como "seguro" |
|
|
21
|
+
| `middleware-not-sole-auth` | error | autorização sustentada **só** por `middleware.ts`/`proxy.ts`, sem re-verificação nas actions/handlers | endpoints que re-verificam auth dentro do próprio corpo |
|
|
22
|
+
| `next-public-env-not-secret` | error | `NEXT_PUBLIC_*` com nome de segredo (`KEY`/`SECRET`/`TOKEN`/`DATABASE_URL`/...) é inlined no bundle em build time | `NEXT_PUBLIC_*` genuinamente público (ex.: `NEXT_PUBLIC_SITE_URL`) |
|
|
23
|
+
|
|
24
|
+
Compatível com **Next 14 / 15 / 16**: o extractor reconhece `middleware.ts` **e** `proxy.ts` (Next 16 renomeou middleware→proxy) como a mesma classe, e aceita `cookies()` e `await cookies()` (Next 15 assíncrono).
|
|
25
|
+
|
|
26
|
+
## Instalação
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pnpm add -D @ihelpee/prumo-plugin-node-next @ihelpee/prumo
|
|
30
|
+
# ou
|
|
31
|
+
npm install --save-dev @ihelpee/prumo-plugin-node-next @ihelpee/prumo
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Uso
|
|
35
|
+
|
|
36
|
+
No `prumo.config.ts` do seu app Next:
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
import { defineConfig } from '@ihelpee/prumo';
|
|
40
|
+
|
|
41
|
+
export default defineConfig({
|
|
42
|
+
layout: {
|
|
43
|
+
src: ['app', 'lib', 'middleware.ts', 'proxy.ts'],
|
|
44
|
+
oracle: ['test', 'oracle'],
|
|
45
|
+
invariants: ['.prumo/invariants'],
|
|
46
|
+
intent: ['.prumo/intent'],
|
|
47
|
+
waivers: ['.prumo/waivers'],
|
|
48
|
+
},
|
|
49
|
+
});
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Em `.prumo/invariants/rules.ts`, aplique o preset:
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
import { withWaivers } from '@ihelpee/prumo';
|
|
56
|
+
import { nextPreset } from '@ihelpee/prumo-plugin-node-next';
|
|
57
|
+
|
|
58
|
+
// Waiver estreito é dívida visível; largo é o gate desligado com nome bonito.
|
|
59
|
+
export default withWaivers(nextPreset, '.prumo/waivers/legacy.json', [
|
|
60
|
+
'server-action-mutation-guarded',
|
|
61
|
+
]);
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Ou registre o plugin inteiro (extractor + regras) via contrato:
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
import next from '@ihelpee/prumo-plugin-node-next';
|
|
68
|
+
// prumo plugin node-next → mostra o catálogo e o snippet de config
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Rode o gate:
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
npx prumo gate
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Exemplo — o achado que o teste unitário com mock nunca vê
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
// app/posts/[id]/page.tsx (Server Component)
|
|
81
|
+
export default async function PostPage({ params }) {
|
|
82
|
+
const { id } = await params;
|
|
83
|
+
async function deletePost(formData: FormData) {
|
|
84
|
+
'use server'; // ← vira POST público
|
|
85
|
+
const postId = String(formData.get('id'));
|
|
86
|
+
await db.post.delete({ where: { id: postId } }); // ← sem auth(), sem schema
|
|
87
|
+
}
|
|
88
|
+
return <form action={deletePost}>…</form>;
|
|
89
|
+
}
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
O teste feliz ("logado → clica → 200") **confirma a crença do agente**. O gate nega:
|
|
93
|
+
|
|
94
|
+
```
|
|
95
|
+
server-action-mutation-guarded app/posts/[id]/page.tsx:6 deletePost
|
|
96
|
+
server-action-input-validated app/posts/[id]/page.tsx:6 deletePost
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Oráculo: a action é um endpoint, não uma função
|
|
100
|
+
|
|
101
|
+
Um teste que `import { deletePost } from '@/app/actions'` e a chama como JS **contorna o POST público** — é espelho, não oráculo, e o `oracle-isolation` do core o marca como tal (não conta para o OII). O oráculo canônico é o **teste negativo**: `POST` na action **sem cookie de sessão** deve falhar. Cookies forjados não valem como evidência.
|
|
102
|
+
|
|
103
|
+
## Autor & Maintainer
|
|
104
|
+
|
|
105
|
+
**Alex Gotardi**
|
|
106
|
+
- 📧 Email: [alexgotardi@gmail.com](mailto:alexgotardi@gmail.com)
|
|
107
|
+
- 🐙 GitHub: [@alexgotardi](https://github.com/alexgotardi)
|
|
108
|
+
- 💼 LinkedIn: [linkedin.com/in/alexgotardi](https://www.linkedin.com/in/alexgotardi/)
|
|
109
|
+
|
|
110
|
+
## Corporate Ownership & License
|
|
111
|
+
|
|
112
|
+
Copyright © 2026 **IHELPEE TECNOLOGIA LTDA** (<https://ihelpee.com>). Created and authored by [Alex Gotardi](https://github.com/alexgotardi).
|
|
113
|
+
|
|
114
|
+
Licensed under the [Apache License, Version 2.0](https://github.com/ihelpee/prumo/blob/main/LICENSE). Free for commercial and private use; attribution and the [`NOTICE`](https://github.com/ihelpee/prumo/blob/main/NOTICE) file must be preserved. The **"Prumo"** name and logo are trademarks of IHELPEE TECNOLOGIA LTDA and are not licensed under Apache 2.0 — see [Brand Protection](https://github.com/ihelpee/prumo#-corporate-ownership-licensing--brand-protection).
|
package/dist/ast.d.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { Node, type SourceFile } from 'ts-morph';
|
|
2
|
+
import { type ImportEdge } from '@ihelpee/prumo/invariants';
|
|
3
|
+
/**
|
|
4
|
+
* AST Extractor do App Router — produz o `NextModel` canônico (spec
|
|
5
|
+
* `docs/especificacao-prumo-node-next.md` §1.5, shape congelado, version 1).
|
|
6
|
+
*
|
|
7
|
+
* O modelo é extraído uma única vez pelo motor (`needsData('next')`) e
|
|
8
|
+
* consumido pelas regras via `ctx.get<NextModel>('next')`. Estático,
|
|
9
|
+
* determinístico, sem boot de app: o gate nunca roda `next`/`react`.
|
|
10
|
+
*/
|
|
11
|
+
export interface NextModel {
|
|
12
|
+
version: 1;
|
|
13
|
+
files: NextFile[];
|
|
14
|
+
/** Arestas de import (do core) para BFS de fronteira de cliente. */
|
|
15
|
+
edges: ImportEdge[];
|
|
16
|
+
/** Existe proxy/middleware com lógica de auth (CA-4/CA-8). */
|
|
17
|
+
proxyHasAuth: boolean;
|
|
18
|
+
}
|
|
19
|
+
export interface NextFile {
|
|
20
|
+
path: string;
|
|
21
|
+
boundary: 'server' | 'client';
|
|
22
|
+
isRouteHandler: boolean;
|
|
23
|
+
isProxy: boolean;
|
|
24
|
+
routeHandlers: RouteHandlerInfo[];
|
|
25
|
+
serverActions: ServerActionInfo[];
|
|
26
|
+
serverComponents: string[];
|
|
27
|
+
envReads: EnvRead[];
|
|
28
|
+
importsServerOnly: boolean;
|
|
29
|
+
/** Import dinâmico/require de string literal que casa ORM_PACKAGES (tripwire §7). */
|
|
30
|
+
dynamicOrmImports: string[];
|
|
31
|
+
}
|
|
32
|
+
export interface RouteHandlerInfo {
|
|
33
|
+
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
|
|
34
|
+
handler: string;
|
|
35
|
+
line: number;
|
|
36
|
+
authCallLine: number | null;
|
|
37
|
+
mutationLine: number | null;
|
|
38
|
+
inputValidated: boolean;
|
|
39
|
+
/** Guard delegado: corpo chama módulo `server-only` que contém AUTH_CALLS (§7). */
|
|
40
|
+
delegatedGuard: boolean;
|
|
41
|
+
}
|
|
42
|
+
export interface ServerActionInfo {
|
|
43
|
+
name: string;
|
|
44
|
+
file: string;
|
|
45
|
+
line: number;
|
|
46
|
+
inline: boolean;
|
|
47
|
+
takesFormData: boolean;
|
|
48
|
+
authCallLine: number | null;
|
|
49
|
+
mutationLine: number | null;
|
|
50
|
+
inputValidated: boolean;
|
|
51
|
+
returnsRawRecord: boolean;
|
|
52
|
+
delegatedGuard: boolean;
|
|
53
|
+
}
|
|
54
|
+
export interface EnvRead {
|
|
55
|
+
name: string;
|
|
56
|
+
isPublic: boolean;
|
|
57
|
+
line: number;
|
|
58
|
+
}
|
|
59
|
+
export declare const AUTH_CALLS: Set<string>;
|
|
60
|
+
export declare const ORM_PACKAGES: string[];
|
|
61
|
+
export declare function fileDirective(sf: SourceFile): string | null;
|
|
62
|
+
/** `"use server"` inline: directive prologue no corpo da própria função (§1.4). */
|
|
63
|
+
export declare function bodyHasUseServer(fn: Node): boolean;
|
|
64
|
+
export declare function isOrmSpecifier(spec: string): boolean;
|
|
65
|
+
export declare function extractNextFile(root: string, sf: SourceFile, delegatedModuleFiles: Set<string>, resolveSymbolFile: (name: string) => string | null): NextFile;
|
|
66
|
+
export declare function extractNextModel(root: string, sourceFiles: SourceFile[]): NextModel;
|
|
67
|
+
export declare function relOf(root: string, sf: SourceFile): string;
|
|
68
|
+
//# sourceMappingURL=ast.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["../src/ast.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAmC,KAAK,UAAU,EAAE,MAAM,UAAU,CAAC;AAElF,OAAO,EAAkB,KAAK,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAE5E;;;;;;;GAOG;AAEH,MAAM,WAAW,SAAS;IACxB,OAAO,EAAE,CAAC,CAAC;IACX,KAAK,EAAE,QAAQ,EAAE,CAAC;IAClB,oEAAoE;IACpE,KAAK,EAAE,UAAU,EAAE,CAAC;IACpB,8DAA8D;IAC9D,YAAY,EAAE,OAAO,CAAC;CACvB;AAED,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,QAAQ,GAAG,QAAQ,CAAC;IAC9B,cAAc,EAAE,OAAO,CAAC;IACxB,OAAO,EAAE,OAAO,CAAC;IACjB,aAAa,EAAE,gBAAgB,EAAE,CAAC;IAClC,aAAa,EAAE,gBAAgB,EAAE,CAAC;IAClC,gBAAgB,EAAE,MAAM,EAAE,CAAC;IAC3B,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,iBAAiB,EAAE,OAAO,CAAC;IAC3B,qFAAqF;IACrF,iBAAiB,EAAE,MAAM,EAAE,CAAC;CAC7B;AAED,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,OAAO,GAAG,QAAQ,GAAG,MAAM,GAAG,SAAS,CAAC;IACzE,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,cAAc,EAAE,OAAO,CAAC;IACxB,mFAAmF;IACnF,cAAc,EAAE,OAAO,CAAC;CACzB;AAED,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,OAAO,CAAC;IAChB,aAAa,EAAE,OAAO,CAAC;IACvB,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,cAAc,EAAE,OAAO,CAAC;IACxB,gBAAgB,EAAE,OAAO,CAAC;IAC1B,cAAc,EAAE,OAAO,CAAC;CACzB;AAED,MAAM,WAAW,OAAO;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,OAAO,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;CACd;AAMD,eAAO,MAAM,UAAU,aAQrB,CAAC;AAmBH,eAAO,MAAM,YAAY,UAexB,CAAC;AAkDF,wBAAgB,aAAa,CAAC,EAAE,EAAE,UAAU,GAAG,MAAM,GAAG,IAAI,CAE3D;AAED,mFAAmF;AACnF,wBAAgB,gBAAgB,CAAC,EAAE,EAAE,IAAI,GAAG,OAAO,CASlD;AA0HD,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEpD;AAED,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,UAAU,EAAE,oBAAoB,EAAE,GAAG,CAAC,MAAM,CAAC,EAAE,iBAAiB,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,GAAG,IAAI,GAAG,QAAQ,CA0H7J;AAMD,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,GAAG,SAAS,CAsDnF;AAwBD,wBAAgB,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,UAAU,GAAG,MAAM,CAI1D"}
|
package/dist/ast.js
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
import { Node, SyntaxKind } from 'ts-morph';
|
|
2
|
+
import { norm } from '@ihelpee/prumo/core';
|
|
3
|
+
import { extractImports } from '@ihelpee/prumo/invariants';
|
|
4
|
+
// ---------------------------------------------------------------------------
|
|
5
|
+
// Vocabulários determinísticos (spec §1.5) — listas nomeadas, não regex solto.
|
|
6
|
+
// ---------------------------------------------------------------------------
|
|
7
|
+
export const AUTH_CALLS = new Set([
|
|
8
|
+
'auth',
|
|
9
|
+
'getSession',
|
|
10
|
+
'verifySession',
|
|
11
|
+
'requireUser',
|
|
12
|
+
'currentUser',
|
|
13
|
+
'getServerSession',
|
|
14
|
+
'verifyToken',
|
|
15
|
+
]);
|
|
16
|
+
const DB_WRITE_METHODS = new Set([
|
|
17
|
+
'create',
|
|
18
|
+
'createMany',
|
|
19
|
+
'update',
|
|
20
|
+
'updateMany',
|
|
21
|
+
'upsert',
|
|
22
|
+
'delete',
|
|
23
|
+
'deleteMany',
|
|
24
|
+
'insert',
|
|
25
|
+
'save',
|
|
26
|
+
'remove',
|
|
27
|
+
]);
|
|
28
|
+
const DB_WRITE_PREFIX = /^(create|update|delete|insert|upsert|save|remove|mutate|write)([A-Z]|Many$)/;
|
|
29
|
+
const VALIDATOR_METHODS = new Set(['parse', 'safeParse', 'decode', 'assert']);
|
|
30
|
+
export const ORM_PACKAGES = [
|
|
31
|
+
'@prisma/client',
|
|
32
|
+
'@prisma/adapter-',
|
|
33
|
+
'drizzle-orm',
|
|
34
|
+
'drizzle-kit',
|
|
35
|
+
'pg',
|
|
36
|
+
'mysql2',
|
|
37
|
+
'mariadb',
|
|
38
|
+
'sqlite3',
|
|
39
|
+
'better-sqlite3',
|
|
40
|
+
'mongoose',
|
|
41
|
+
'knex',
|
|
42
|
+
'@neondatabase/serverless',
|
|
43
|
+
'@planetscale/database',
|
|
44
|
+
'mongodb',
|
|
45
|
+
];
|
|
46
|
+
const SECRET_MODULE_HINT = /(secret|credential|private[-_]?key|secrets?|vault|kms)(\/|$|\.)/;
|
|
47
|
+
const HTTP_METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
|
|
48
|
+
const SERVER_COMPONENT_NAMES = new Set([
|
|
49
|
+
'page',
|
|
50
|
+
'layout',
|
|
51
|
+
'template',
|
|
52
|
+
'error',
|
|
53
|
+
'global-error',
|
|
54
|
+
'loading',
|
|
55
|
+
'not-found',
|
|
56
|
+
'default',
|
|
57
|
+
'sitemap',
|
|
58
|
+
'robots',
|
|
59
|
+
]);
|
|
60
|
+
// ---------------------------------------------------------------------------
|
|
61
|
+
// Directive prologue (spec §1.4, CA-6, TypeScript issue #64033)
|
|
62
|
+
// ---------------------------------------------------------------------------
|
|
63
|
+
/**
|
|
64
|
+
* Lê o Directive Prologue real do arquivo (spec §1.4, CA-6, TS issue #64033):
|
|
65
|
+
* sequência inicial CONTÍGUA de `ExpressionStatement` cujo `expression` é
|
|
66
|
+
* `StringLiteral`/`NoSubstitutionTemplateLiteral`, parando no primeiro
|
|
67
|
+
* statement que não é directive. Consequências canônicas:
|
|
68
|
+
*
|
|
69
|
+
* - comentários (`//`, `/* *\/`) são trivia: tolerados;
|
|
70
|
+
* - `"use strict"` acima da diretiva é directive válida: tolerada;
|
|
71
|
+
* - `import type` / `type X = ...` TERMINAM o prologue: um `"use client"`
|
|
72
|
+
* depois deles NÃO é diretiva efetiva (caso #64033);
|
|
73
|
+
* - zero regex/substring sobre o texto (proibido pela spec).
|
|
74
|
+
*/
|
|
75
|
+
function readPrologue(statements) {
|
|
76
|
+
for (const st of statements) {
|
|
77
|
+
if (Node.isExpressionStatement(st)) {
|
|
78
|
+
const expr = st.getExpression();
|
|
79
|
+
if (Node.isStringLiteral(expr) || Node.isNoSubstitutionTemplateLiteral(expr)) {
|
|
80
|
+
const text = expr.getLiteralText();
|
|
81
|
+
if (text === 'use client' || text === 'use server')
|
|
82
|
+
return text;
|
|
83
|
+
if (text === 'use strict')
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
export function fileDirective(sf) {
|
|
92
|
+
return readPrologue(sf.getStatements());
|
|
93
|
+
}
|
|
94
|
+
/** `"use server"` inline: directive prologue no corpo da própria função (§1.4). */
|
|
95
|
+
export function bodyHasUseServer(fn) {
|
|
96
|
+
const body = (Node.isFunctionDeclaration(fn) || Node.isFunctionExpression(fn) || Node.isMethodDeclaration(fn)) && fn.getBody()
|
|
97
|
+
? fn.getBody()
|
|
98
|
+
: Node.isArrowFunction(fn)
|
|
99
|
+
? fn.getBody()
|
|
100
|
+
: null;
|
|
101
|
+
if (!body || !Node.isBlock(body))
|
|
102
|
+
return false;
|
|
103
|
+
return readPrologue(body.getStatements()) === 'use server';
|
|
104
|
+
}
|
|
105
|
+
// ---------------------------------------------------------------------------
|
|
106
|
+
// Heurísticas de corpo (auth / mutação / validação)
|
|
107
|
+
// ---------------------------------------------------------------------------
|
|
108
|
+
function calleeName(call) {
|
|
109
|
+
const expr = call.getExpression();
|
|
110
|
+
if (Node.isIdentifier(expr))
|
|
111
|
+
return expr.getText();
|
|
112
|
+
if (Node.isPropertyAccessExpression(expr))
|
|
113
|
+
return expr.getName();
|
|
114
|
+
return '';
|
|
115
|
+
}
|
|
116
|
+
function isAuthCall(call, fileImportsNextHeaders) {
|
|
117
|
+
const name = calleeName(call);
|
|
118
|
+
if (AUTH_CALLS.has(name))
|
|
119
|
+
return true;
|
|
120
|
+
if (fileImportsNextHeaders && (name === 'cookies' || name === 'headers'))
|
|
121
|
+
return true;
|
|
122
|
+
return false;
|
|
123
|
+
}
|
|
124
|
+
function isMutationCall(call) {
|
|
125
|
+
const name = calleeName(call);
|
|
126
|
+
if (!name)
|
|
127
|
+
return false;
|
|
128
|
+
if (AUTH_CALLS.has(name))
|
|
129
|
+
return false;
|
|
130
|
+
if (DB_WRITE_METHODS.has(name))
|
|
131
|
+
return true;
|
|
132
|
+
return DB_WRITE_PREFIX.test(name);
|
|
133
|
+
}
|
|
134
|
+
function isSchemaValidatorCall(call) {
|
|
135
|
+
const expr = call.getExpression();
|
|
136
|
+
if (!Node.isPropertyAccessExpression(expr))
|
|
137
|
+
return false;
|
|
138
|
+
const method = expr.getName();
|
|
139
|
+
if (!VALIDATOR_METHODS.has(method))
|
|
140
|
+
return false;
|
|
141
|
+
const obj = expr.getExpression();
|
|
142
|
+
const objText = Node.isIdentifier(obj) ? obj.getText() : obj.getText().slice(0, 40);
|
|
143
|
+
return /^(z|v)$/.test(objText) || /[Ss]chema/.test(objText);
|
|
144
|
+
}
|
|
145
|
+
function analyzeBody(fn, fileImportsNextHeaders, delegatedModuleFiles, resolveSymbolFile) {
|
|
146
|
+
const out = {
|
|
147
|
+
authCallLine: null,
|
|
148
|
+
mutationLine: null,
|
|
149
|
+
validatorLine: null,
|
|
150
|
+
callsDelegatedGuard: false,
|
|
151
|
+
returnsRawRecord: false,
|
|
152
|
+
};
|
|
153
|
+
const calls = fn.getDescendantsOfKind(SyntaxKind.CallExpression);
|
|
154
|
+
for (const call of calls) {
|
|
155
|
+
const line = call.getStartLineNumber();
|
|
156
|
+
if (out.authCallLine === null && isAuthCall(call, fileImportsNextHeaders)) {
|
|
157
|
+
out.authCallLine = line;
|
|
158
|
+
}
|
|
159
|
+
if (out.mutationLine === null && isMutationCall(call)) {
|
|
160
|
+
out.mutationLine = line;
|
|
161
|
+
}
|
|
162
|
+
if (out.validatorLine === null && isSchemaValidatorCall(call)) {
|
|
163
|
+
out.validatorLine = line;
|
|
164
|
+
}
|
|
165
|
+
if (!out.callsDelegatedGuard) {
|
|
166
|
+
const name = calleeName(call);
|
|
167
|
+
if (name) {
|
|
168
|
+
const file = resolveSymbolFile(name);
|
|
169
|
+
if (file && delegatedModuleFiles.has(file))
|
|
170
|
+
out.callsDelegatedGuard = true;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
// Heurística de retorno cru: `return db.post.delete(...)` sem shape próprio.
|
|
175
|
+
for (const ret of fn.getDescendantsOfKind(SyntaxKind.ReturnStatement)) {
|
|
176
|
+
const expr = ret.getExpression();
|
|
177
|
+
if (expr && Node.isCallExpression(expr) && isMutationCall(expr)) {
|
|
178
|
+
out.returnsRawRecord = true;
|
|
179
|
+
break;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return out;
|
|
183
|
+
}
|
|
184
|
+
function takesFormData(fn) {
|
|
185
|
+
if (!Node.isFunctionDeclaration(fn) && !Node.isFunctionExpression(fn) && !Node.isArrowFunction(fn)) {
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
188
|
+
for (const param of fn.getParameters()) {
|
|
189
|
+
const typeText = param.getTypeNode()?.getText() ?? '';
|
|
190
|
+
if (/FormData|Promise<FormData>/.test(typeText))
|
|
191
|
+
return true;
|
|
192
|
+
}
|
|
193
|
+
// Parâmetro sem anotação em Server Action = entrada arbitrária não tipada.
|
|
194
|
+
const params = fn.getParameters();
|
|
195
|
+
return params.length > 0 && params.every((p) => !p.getTypeNode());
|
|
196
|
+
}
|
|
197
|
+
// ---------------------------------------------------------------------------
|
|
198
|
+
// Extração por arquivo
|
|
199
|
+
// ---------------------------------------------------------------------------
|
|
200
|
+
function baseName(p) {
|
|
201
|
+
const leaf = norm(p).split('/').pop() ?? '';
|
|
202
|
+
return leaf.replace(/\.(tsx|ts|mts|cts|jsx|js)$/, '');
|
|
203
|
+
}
|
|
204
|
+
function inAppDir(p) {
|
|
205
|
+
return /(^|\/)app\//.test(norm(p));
|
|
206
|
+
}
|
|
207
|
+
function isProxyPath(p) {
|
|
208
|
+
const n = norm(p);
|
|
209
|
+
const leaf = n.split('/').pop() ?? '';
|
|
210
|
+
return /^(middleware|proxy)\.(ts|tsx|js)$/.test(leaf);
|
|
211
|
+
}
|
|
212
|
+
export function isOrmSpecifier(spec) {
|
|
213
|
+
return ORM_PACKAGES.some((pkg) => spec === pkg || spec.startsWith(pkg));
|
|
214
|
+
}
|
|
215
|
+
export function extractNextFile(root, sf, delegatedModuleFiles, resolveSymbolFile) {
|
|
216
|
+
const path = norm(sf.getFilePath()).startsWith(norm(root))
|
|
217
|
+
? norm(sf.getFilePath()).slice(norm(root).replace(/\/+$/, '').length + 1)
|
|
218
|
+
: norm(sf.getFilePath());
|
|
219
|
+
const directive = fileDirective(sf);
|
|
220
|
+
const boundary = directive === 'use client' ? 'client' : 'server';
|
|
221
|
+
const fileImportsNextHeaders = sf
|
|
222
|
+
.getImportDeclarations()
|
|
223
|
+
.some((imp) => imp.getModuleSpecifierValue() === 'next/headers');
|
|
224
|
+
const importsServerOnly = sf
|
|
225
|
+
.getImportDeclarations()
|
|
226
|
+
.some((imp) => /^server-only(-turbo)?$/.test(imp.getModuleSpecifierValue()));
|
|
227
|
+
const envReads = [];
|
|
228
|
+
for (const m of sf.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression)) {
|
|
229
|
+
const text = m.getText();
|
|
230
|
+
const match = text.match(/^process\.env\.([A-Za-z0-9_]+)$/);
|
|
231
|
+
if (match?.[1]) {
|
|
232
|
+
envReads.push({ name: match[1], isPublic: match[1].startsWith('NEXT_PUBLIC_'), line: m.getStartLineNumber() });
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
const dynamicOrmImports = [];
|
|
236
|
+
const text = sf.getFullText();
|
|
237
|
+
const dynRe = /(?:require\(|import\()\s*['"]([^'"]+)['"]/g;
|
|
238
|
+
let dm;
|
|
239
|
+
while ((dm = dynRe.exec(text)) !== null) {
|
|
240
|
+
const spec = dm[1];
|
|
241
|
+
if (isOrmSpecifier(spec))
|
|
242
|
+
dynamicOrmImports.push(spec);
|
|
243
|
+
}
|
|
244
|
+
const serverComponents = [];
|
|
245
|
+
if (boundary === 'server' && inAppDir(path) && SERVER_COMPONENT_NAMES.has(baseName(path))) {
|
|
246
|
+
for (const fn of sf.getFunctions()) {
|
|
247
|
+
const n = fn.getName();
|
|
248
|
+
if (n && (n === 'default' || SERVER_COMPONENT_NAMES.has(n)))
|
|
249
|
+
serverComponents.push(n);
|
|
250
|
+
}
|
|
251
|
+
if (sf.getDefaultExportSymbol())
|
|
252
|
+
serverComponents.push('default');
|
|
253
|
+
}
|
|
254
|
+
const routeHandlers = [];
|
|
255
|
+
const isRouteHandler = inAppDir(path) && baseName(path) === 'route';
|
|
256
|
+
if (isRouteHandler) {
|
|
257
|
+
for (const fn of sf.getFunctions()) {
|
|
258
|
+
const name = fn.getName();
|
|
259
|
+
if (!name || !HTTP_METHODS.has(name))
|
|
260
|
+
continue;
|
|
261
|
+
if (!fn.isExported())
|
|
262
|
+
continue;
|
|
263
|
+
const signals = analyzeBody(fn, fileImportsNextHeaders, delegatedModuleFiles, resolveSymbolFile);
|
|
264
|
+
routeHandlers.push({
|
|
265
|
+
method: name,
|
|
266
|
+
handler: name,
|
|
267
|
+
line: fn.getStartLineNumber(),
|
|
268
|
+
authCallLine: signals.authCallLine,
|
|
269
|
+
mutationLine: signals.mutationLine,
|
|
270
|
+
inputValidated: signals.mutationLine === null
|
|
271
|
+
? true
|
|
272
|
+
: signals.validatorLine !== null && signals.validatorLine < signals.mutationLine,
|
|
273
|
+
delegatedGuard: signals.callsDelegatedGuard,
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
const serverActions = [];
|
|
278
|
+
const fileIsServerModule = directive === 'use server';
|
|
279
|
+
const pushAction = (fn, name, inline) => {
|
|
280
|
+
const signals = analyzeBody(fn, fileImportsNextHeaders, delegatedModuleFiles, resolveSymbolFile);
|
|
281
|
+
serverActions.push({
|
|
282
|
+
name,
|
|
283
|
+
file: path,
|
|
284
|
+
line: fn.getStartLineNumber(),
|
|
285
|
+
inline,
|
|
286
|
+
takesFormData: takesFormData(fn),
|
|
287
|
+
authCallLine: signals.authCallLine,
|
|
288
|
+
mutationLine: signals.mutationLine,
|
|
289
|
+
inputValidated: signals.mutationLine === null
|
|
290
|
+
? true
|
|
291
|
+
: signals.validatorLine !== null && signals.validatorLine < signals.mutationLine,
|
|
292
|
+
returnsRawRecord: signals.returnsRawRecord,
|
|
293
|
+
delegatedGuard: signals.callsDelegatedGuard,
|
|
294
|
+
});
|
|
295
|
+
};
|
|
296
|
+
// Server Actions de arquivo: `export async function` num módulo `"use server"`.
|
|
297
|
+
for (const fn of sf.getFunctions()) {
|
|
298
|
+
if (fileIsServerModule && fn.isExported())
|
|
299
|
+
pushAction(fn, fn.getName() ?? '(anon)', false);
|
|
300
|
+
}
|
|
301
|
+
// Server Actions inline: `"use server"` no topo do CORPO da função (§1.4),
|
|
302
|
+
// inclusive funções aninhadas em Server Components (padrão `form action={}`).
|
|
303
|
+
const inlineSeen = new Set();
|
|
304
|
+
const inlineCandidates = [
|
|
305
|
+
...sf.getDescendantsOfKind(SyntaxKind.FunctionDeclaration),
|
|
306
|
+
...sf.getDescendantsOfKind(SyntaxKind.FunctionExpression),
|
|
307
|
+
...sf.getDescendantsOfKind(SyntaxKind.ArrowFunction),
|
|
308
|
+
];
|
|
309
|
+
for (const fn of inlineCandidates) {
|
|
310
|
+
if (inlineSeen.has(fn))
|
|
311
|
+
continue;
|
|
312
|
+
inlineSeen.add(fn);
|
|
313
|
+
if (!bodyHasUseServer(fn))
|
|
314
|
+
continue;
|
|
315
|
+
const name = Node.isFunctionDeclaration(fn)
|
|
316
|
+
? (fn.getName() ?? '(anon)')
|
|
317
|
+
: Node.isFunctionExpression(fn)
|
|
318
|
+
? (fn.getName() ?? '(anon)')
|
|
319
|
+
: (fn.getParent()?.getParent()?.asKind(SyntaxKind.VariableDeclaration)?.getName() ?? '(anon)');
|
|
320
|
+
pushAction(fn, name, true);
|
|
321
|
+
}
|
|
322
|
+
return {
|
|
323
|
+
path,
|
|
324
|
+
boundary,
|
|
325
|
+
isRouteHandler,
|
|
326
|
+
isProxy: isProxyPath(path),
|
|
327
|
+
routeHandlers,
|
|
328
|
+
serverActions,
|
|
329
|
+
serverComponents: [...new Set(serverComponents)],
|
|
330
|
+
envReads,
|
|
331
|
+
importsServerOnly,
|
|
332
|
+
dynamicOrmImports,
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
// ---------------------------------------------------------------------------
|
|
336
|
+
// NextModel completo
|
|
337
|
+
// ---------------------------------------------------------------------------
|
|
338
|
+
export function extractNextModel(root, sourceFiles) {
|
|
339
|
+
// Módulo delegado (DAL): importa `server-only` E contém chamada de auth.
|
|
340
|
+
const delegatedModuleFiles = new Set();
|
|
341
|
+
const declaredByFile = new Map();
|
|
342
|
+
for (const sf of sourceFiles) {
|
|
343
|
+
const rel = relOf(root, sf);
|
|
344
|
+
const names = sf
|
|
345
|
+
.getFunctions()
|
|
346
|
+
.map((f) => f.getName())
|
|
347
|
+
.filter((n) => Boolean(n));
|
|
348
|
+
for (const cls of sf.getClasses()) {
|
|
349
|
+
const n = cls.getName();
|
|
350
|
+
if (n)
|
|
351
|
+
names.push(n);
|
|
352
|
+
}
|
|
353
|
+
declaredByFile.set(rel, names);
|
|
354
|
+
}
|
|
355
|
+
const fileByPath = new Map();
|
|
356
|
+
for (const sf of sourceFiles)
|
|
357
|
+
fileByPath.set(relOf(root, sf), sf);
|
|
358
|
+
const edges = sourceFiles
|
|
359
|
+
.flatMap((sf) => extractImports(sf, root))
|
|
360
|
+
.map((e) => ({ ...e, resolved: resolveToModelPath(e.resolved, fileByPath) }));
|
|
361
|
+
for (const sf of sourceFiles) {
|
|
362
|
+
const rel = relOf(root, sf);
|
|
363
|
+
const importsServerOnly = sf
|
|
364
|
+
.getImportDeclarations()
|
|
365
|
+
.some((imp) => /^server-only(-turbo)?$/.test(imp.getModuleSpecifierValue()));
|
|
366
|
+
if (!importsServerOnly)
|
|
367
|
+
continue;
|
|
368
|
+
const text = sf.getFullText();
|
|
369
|
+
if ([...AUTH_CALLS].some((a) => new RegExp(`\\b${a}\\s*\\(`).test(text))) {
|
|
370
|
+
delegatedModuleFiles.add(rel);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
// Símbolo -> arquivo que o declara (para o guard delegado).
|
|
374
|
+
const symbolFile = new Map();
|
|
375
|
+
for (const [rel, names] of declaredByFile) {
|
|
376
|
+
for (const n of names)
|
|
377
|
+
if (!symbolFile.has(n))
|
|
378
|
+
symbolFile.set(n, rel);
|
|
379
|
+
}
|
|
380
|
+
const resolveSymbolFile = (name) => symbolFile.get(name) ?? null;
|
|
381
|
+
const modelFiles = sourceFiles.map((sf) => extractNextFile(root, sf, delegatedModuleFiles, resolveSymbolFile));
|
|
382
|
+
const proxyHasAuth = modelFiles.some((f) => {
|
|
383
|
+
if (!f.isProxy)
|
|
384
|
+
return false;
|
|
385
|
+
const sf = fileByPath.get(f.path);
|
|
386
|
+
if (!sf)
|
|
387
|
+
return false;
|
|
388
|
+
const text = sf.getFullText();
|
|
389
|
+
return [...AUTH_CALLS].some((a) => new RegExp(`\\b${a}\\s*\\(`).test(text)) || /\bcookies\s*\(/.test(text);
|
|
390
|
+
});
|
|
391
|
+
return { version: 1, files: modelFiles, edges, proxyHasAuth };
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Normaliza o `resolved` de um ImportEdge para o caminho EXATO de um arquivo
|
|
395
|
+
* do modelo. O core resolve specifier relativo sem extensão (`../lib/db`);
|
|
396
|
+
* o BFS da fronteira precisa casar com `lib/db.ts`. Specifier externo
|
|
397
|
+
* (`@prisma/client`) passa sem mudança.
|
|
398
|
+
*/
|
|
399
|
+
function resolveToModelPath(resolved, fileByPath) {
|
|
400
|
+
const n = norm(resolved);
|
|
401
|
+
if (fileByPath.has(n))
|
|
402
|
+
return n;
|
|
403
|
+
for (const ext of ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx']) {
|
|
404
|
+
if (fileByPath.has(n + ext))
|
|
405
|
+
return n + ext;
|
|
406
|
+
}
|
|
407
|
+
for (const ext of ['.ts', '.tsx']) {
|
|
408
|
+
const idx = `${n}/index${ext}`;
|
|
409
|
+
if (fileByPath.has(idx))
|
|
410
|
+
return idx;
|
|
411
|
+
}
|
|
412
|
+
return n;
|
|
413
|
+
}
|
|
414
|
+
export function relOf(root, sf) {
|
|
415
|
+
const nRoot = norm(root).replace(/\/+$/, '');
|
|
416
|
+
const nAbs = norm(sf.getFilePath());
|
|
417
|
+
return nAbs.startsWith(nRoot + '/') ? nAbs.slice(nRoot.length + 1) : nAbs;
|
|
418
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,YAAY,CAAC;AAC3B,OAAO,EAAE,UAAU,IAAI,OAAO,EAAE,MAAM,YAAY,CAAC"}
|
package/dist/index.js
ADDED
package/dist/rules.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { type RuleDef } from '@ihelpee/prumo/invariants';
|
|
2
|
+
/**
|
|
3
|
+
* CA-1 — Server Action ou Route Handler de mutação que escreve no banco sem
|
|
4
|
+
* re-verificar sessão/autenticação ANTES da escrita. Auth depois da escrita é
|
|
5
|
+
* achado (ordem importa). Guard delegado (DAL `server-only` com auth) não é
|
|
6
|
+
* achado — fronteira honesta da heurística §7.
|
|
7
|
+
*/
|
|
8
|
+
export declare const serverActionMutationGuarded: RuleDef;
|
|
9
|
+
/**
|
|
10
|
+
* CA-2 — O grafo do cliente (alcançável de um `"use client"`, direta ou
|
|
11
|
+
* transitivamente) importa ORM/cliente de banco, módulo de segredo, ou lê
|
|
12
|
+
* `process.env` não-`NEXT_PUBLIC_`. Reporta a TRILHA para ser acionável.
|
|
13
|
+
*
|
|
14
|
+
* Não pega: módulo compartilhado sem ORM/segredo importado por client.
|
|
15
|
+
* Limitação declarada: `await import(nomeVariavel)` não resolve (tripwire só
|
|
16
|
+
* para string literal de ORM).
|
|
17
|
+
*/
|
|
18
|
+
export declare const clientBoundaryLeakPrevented: RuleDef;
|
|
19
|
+
/**
|
|
20
|
+
* CA-3 — Server Action que muta estado sem validação estrutural de schema
|
|
21
|
+
* (Zod/Valibot) ANTES do acesso ao banco. Valida depois de mutar é achado.
|
|
22
|
+
*
|
|
23
|
+
* Fronteira crítica (spec §2.3): schema valida SHAPE, não posse. Este
|
|
24
|
+
* invariante NÃO cobre IDOR e não vende validação como autorização.
|
|
25
|
+
*/
|
|
26
|
+
export declare const serverActionInputValidated: RuleDef;
|
|
27
|
+
/**
|
|
28
|
+
* CA-4 — Autorização sustentada exclusivamente por middleware/proxy. Se o
|
|
29
|
+
* proxy tem lógica de auth e alguma action/handler de mutação não tem auth
|
|
30
|
+
* próprio, o par é achado: proxy roda por matcher, nunca é ponto de
|
|
31
|
+
* enforcement (Next 16: middleware→proxy, ambos reconhecidos — CA-8).
|
|
32
|
+
*/
|
|
33
|
+
export declare const middlewareNotSoleAuth: RuleDef;
|
|
34
|
+
/**
|
|
35
|
+
* CA-5 — `NEXT_PUBLIC_*` com nome de segredo. O prefixo inlina o valor
|
|
36
|
+
* literal no bundle em build time: não é lookup de runtime e não é
|
|
37
|
+
* rotacionável depois de publicado.
|
|
38
|
+
*/
|
|
39
|
+
export declare const nextPublicEnvNotSecret: RuleDef;
|
|
40
|
+
/**
|
|
41
|
+
* O Plugin oficial do Next.js App Router para o Prumo.
|
|
42
|
+
*
|
|
43
|
+
* Analisa, nunca executa: zero dependência de `next`/`react`. Compat
|
|
44
|
+
* Next 14/15/16 (middleware.ts e proxy.ts; `cookies()` e `await cookies()`).
|
|
45
|
+
*/
|
|
46
|
+
export declare const nextPlugin: import("@ihelpee/prumo/invariants").PrumoPlugin;
|
|
47
|
+
export declare const nextPreset: RuleDef[];
|
|
48
|
+
//# sourceMappingURL=rules.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rules.d.ts","sourceRoot":"","sources":["../src/rules.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,OAAO,EAGb,MAAM,2BAA2B,CAAC;AAsCnC;;;;;GAKG;AACH,eAAO,MAAM,2BAA2B,SAuB9B,CAAC;AAEX;;;;;;;;GAQG;AACH,eAAO,MAAM,2BAA2B,SA6D9B,CAAC;AAKX;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B,SAmB7B,CAAC;AAEX;;;;;GAKG;AACH,eAAO,MAAM,qBAAqB,SAsBxB,CAAC;AAEX;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,SAoBzB,CAAC;AAEX;;;;;GAKG;AACH,eAAO,MAAM,UAAU,iDAerB,CAAC;AAEH,eAAO,MAAM,UAAU,EAAE,OAAO,EAAqB,CAAC"}
|
package/dist/rules.js
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import { rule, definePlugin, } from '@ihelpee/prumo/invariants';
|
|
2
|
+
import { extractNextModel, isOrmSpecifier, } from './ast.js';
|
|
3
|
+
/**
|
|
4
|
+
* Invariantes do App Router (spec §2). Os cinco ids são canônicos e
|
|
5
|
+
* congelados: nenhum card filho pode renomeá-los sem voltar à especificação.
|
|
6
|
+
*
|
|
7
|
+
* Fronteiras honestas (Art. IV): cada regra declara o que NÃO pega.
|
|
8
|
+
*/
|
|
9
|
+
const MUTATING = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
|
|
10
|
+
const SECRET_ENV_HINT = /(KEY|SECRET|TOKEN|PASSWORD|PASS|PRIVATE|DATABASE_URL|DB_|API_)/;
|
|
11
|
+
function model(ctx) {
|
|
12
|
+
return (ctx.get('next') ?? { version: 1, files: [], edges: [], proxyHasAuth: false });
|
|
13
|
+
}
|
|
14
|
+
function endpoints(m) {
|
|
15
|
+
const out = [];
|
|
16
|
+
for (const file of m.files) {
|
|
17
|
+
for (const a of file.serverActions)
|
|
18
|
+
out.push({ kind: 'action', file, ep: a, method: 'POST' });
|
|
19
|
+
for (const r of file.routeHandlers)
|
|
20
|
+
out.push({ kind: 'route', file, ep: r, method: r.method });
|
|
21
|
+
}
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* CA-1 — Server Action ou Route Handler de mutação que escreve no banco sem
|
|
26
|
+
* re-verificar sessão/autenticação ANTES da escrita. Auth depois da escrita é
|
|
27
|
+
* achado (ordem importa). Guard delegado (DAL `server-only` com auth) não é
|
|
28
|
+
* achado — fronteira honesta da heurística §7.
|
|
29
|
+
*/
|
|
30
|
+
export const serverActionMutationGuarded = rule('server-action-mutation-guarded')
|
|
31
|
+
.needsData('next')
|
|
32
|
+
.message('Server Action/Route Handler de mutação escreve no banco sem re-verificar auth no próprio corpo antes da escrita (a action é um endpoint HTTP público; gate de página não se propaga)')
|
|
33
|
+
.assert((ctx) => {
|
|
34
|
+
const m = model(ctx);
|
|
35
|
+
const out = [];
|
|
36
|
+
for (const { kind, file, ep, method } of endpoints(m)) {
|
|
37
|
+
if (!MUTATING.has(method))
|
|
38
|
+
continue;
|
|
39
|
+
if (ep.mutationLine === null)
|
|
40
|
+
continue; // leitura pura: outro invariante (fora de escopo §8)
|
|
41
|
+
if (ep.delegatedGuard)
|
|
42
|
+
continue; // DAL faz o guard dentro (heurística §7)
|
|
43
|
+
const unguarded = ep.authCallLine === null || ep.authCallLine > ep.mutationLine;
|
|
44
|
+
if (!unguarded)
|
|
45
|
+
continue;
|
|
46
|
+
const label = kind === 'action' ? ep.name : ep.handler;
|
|
47
|
+
const order = ep.authCallLine !== null ? ' (auth DEPOIS da escrita)' : '';
|
|
48
|
+
out.push({
|
|
49
|
+
target: `${file.path}:${ep.line} ${label}${order}`,
|
|
50
|
+
location: `${file.path}:${ep.line}`,
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
return out;
|
|
54
|
+
})
|
|
55
|
+
.build();
|
|
56
|
+
/**
|
|
57
|
+
* CA-2 — O grafo do cliente (alcançável de um `"use client"`, direta ou
|
|
58
|
+
* transitivamente) importa ORM/cliente de banco, módulo de segredo, ou lê
|
|
59
|
+
* `process.env` não-`NEXT_PUBLIC_`. Reporta a TRILHA para ser acionável.
|
|
60
|
+
*
|
|
61
|
+
* Não pega: módulo compartilhado sem ORM/segredo importado por client.
|
|
62
|
+
* Limitação declarada: `await import(nomeVariavel)` não resolve (tripwire só
|
|
63
|
+
* para string literal de ORM).
|
|
64
|
+
*/
|
|
65
|
+
export const clientBoundaryLeakPrevented = rule('client-boundary-leak-prevented')
|
|
66
|
+
.needsData('next')
|
|
67
|
+
.message('"use client" é entry point de bundle: o grafo do cliente alcança ORM/segredo/env não-público que será enviado ao navegador')
|
|
68
|
+
.assert((ctx) => {
|
|
69
|
+
const m = model(ctx);
|
|
70
|
+
const byPath = new Map(m.files.map((f) => [f.path, f]));
|
|
71
|
+
const out = [];
|
|
72
|
+
const reported = new Set();
|
|
73
|
+
const adjacency = new Map();
|
|
74
|
+
for (const e of m.edges) {
|
|
75
|
+
const list = adjacency.get(e.from) ?? [];
|
|
76
|
+
list.push(e.resolved);
|
|
77
|
+
adjacency.set(e.from, list);
|
|
78
|
+
}
|
|
79
|
+
const leakOf = (f) => {
|
|
80
|
+
if (f.importsServerOnly)
|
|
81
|
+
return null; // protegido: o build falha, não o bundle
|
|
82
|
+
for (const e of m.edges) {
|
|
83
|
+
if (e.from !== f.path)
|
|
84
|
+
continue;
|
|
85
|
+
if (isOrmSpecifier(e.specifier))
|
|
86
|
+
return `importa ${e.specifier}`;
|
|
87
|
+
}
|
|
88
|
+
if (f.dynamicOrmImports.length > 0)
|
|
89
|
+
return `import dinâmico de ${f.dynamicOrmImports[0]}`;
|
|
90
|
+
for (const er of f.envReads) {
|
|
91
|
+
if (!er.isPublic)
|
|
92
|
+
return `lê process.env.${er.name} (não-NEXT_PUBLIC)`;
|
|
93
|
+
}
|
|
94
|
+
if (SECRET_MODULE_HINT_PATH(f.path))
|
|
95
|
+
return 'módulo de segredo/credencial';
|
|
96
|
+
return null;
|
|
97
|
+
};
|
|
98
|
+
for (const seed of m.files) {
|
|
99
|
+
if (seed.boundary !== 'client')
|
|
100
|
+
continue;
|
|
101
|
+
// BFS com trilha; reporta por par (seed, nó vazado) — cada entry point
|
|
102
|
+
// de cliente que alcança o segredo é uma violação própria.
|
|
103
|
+
const queue = [{ path: seed.path, trail: [seed.path] }];
|
|
104
|
+
const seen = new Set([seed.path]);
|
|
105
|
+
while (queue.length > 0) {
|
|
106
|
+
const cur = queue.shift();
|
|
107
|
+
const node = byPath.get(cur.path);
|
|
108
|
+
if (node) {
|
|
109
|
+
const leak = leakOf(node);
|
|
110
|
+
const key = `${seed.path}=>${node.path}`;
|
|
111
|
+
if (leak && !reported.has(key)) {
|
|
112
|
+
reported.add(key);
|
|
113
|
+
out.push({
|
|
114
|
+
target: `${cur.trail.join(' → ')} (${leak})`,
|
|
115
|
+
location: `${seed.path}`,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
for (const next of adjacency.get(cur.path) ?? []) {
|
|
120
|
+
if (seen.has(next))
|
|
121
|
+
continue;
|
|
122
|
+
seen.add(next);
|
|
123
|
+
queue.push({ path: next, trail: [...cur.trail, next] });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return out;
|
|
128
|
+
})
|
|
129
|
+
.build();
|
|
130
|
+
const SECRET_MODULE_HINT_PATH = (p) => /(secret|credential|private[-_]?key|secrets?|vault|kms)(\/|\.)/.test(p.split('/').slice(-2).join('/'));
|
|
131
|
+
/**
|
|
132
|
+
* CA-3 — Server Action que muta estado sem validação estrutural de schema
|
|
133
|
+
* (Zod/Valibot) ANTES do acesso ao banco. Valida depois de mutar é achado.
|
|
134
|
+
*
|
|
135
|
+
* Fronteira crítica (spec §2.3): schema valida SHAPE, não posse. Este
|
|
136
|
+
* invariante NÃO cobre IDOR e não vende validação como autorização.
|
|
137
|
+
*/
|
|
138
|
+
export const serverActionInputValidated = rule('server-action-input-validated')
|
|
139
|
+
.needsData('next')
|
|
140
|
+
.message('Server Action muta estado sem validar input por schema (Zod/Valibot) antes do banco; schema valida shape, não posse (IDOR é checagem separada)')
|
|
141
|
+
.assert((ctx) => {
|
|
142
|
+
const m = model(ctx);
|
|
143
|
+
const out = [];
|
|
144
|
+
for (const { kind, file, ep } of endpoints(m)) {
|
|
145
|
+
if (kind !== 'action')
|
|
146
|
+
continue;
|
|
147
|
+
if (ep.mutationLine === null)
|
|
148
|
+
continue;
|
|
149
|
+
if (ep.inputValidated)
|
|
150
|
+
continue;
|
|
151
|
+
out.push({
|
|
152
|
+
target: `${file.path}:${ep.line} ${ep.name}`,
|
|
153
|
+
location: `${file.path}:${ep.line}`,
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
return out;
|
|
157
|
+
})
|
|
158
|
+
.build();
|
|
159
|
+
/**
|
|
160
|
+
* CA-4 — Autorização sustentada exclusivamente por middleware/proxy. Se o
|
|
161
|
+
* proxy tem lógica de auth e alguma action/handler de mutação não tem auth
|
|
162
|
+
* próprio, o par é achado: proxy roda por matcher, nunca é ponto de
|
|
163
|
+
* enforcement (Next 16: middleware→proxy, ambos reconhecidos — CA-8).
|
|
164
|
+
*/
|
|
165
|
+
export const middlewareNotSoleAuth = rule('middleware-not-sole-auth')
|
|
166
|
+
.needsData('next')
|
|
167
|
+
.message('autorização apoiada só em middleware.ts/proxy.ts: Server Actions e Route Handlers invocados direto contornam o matcher; re-verifique dentro de cada endpoint')
|
|
168
|
+
.assert((ctx) => {
|
|
169
|
+
const m = model(ctx);
|
|
170
|
+
if (!m.proxyHasAuth)
|
|
171
|
+
return [];
|
|
172
|
+
const out = [];
|
|
173
|
+
for (const { kind, file, ep, method } of endpoints(m)) {
|
|
174
|
+
if (!MUTATING.has(method))
|
|
175
|
+
continue;
|
|
176
|
+
if (ep.mutationLine === null)
|
|
177
|
+
continue;
|
|
178
|
+
if (ep.authCallLine !== null && ep.authCallLine <= ep.mutationLine)
|
|
179
|
+
continue;
|
|
180
|
+
if (ep.delegatedGuard)
|
|
181
|
+
continue;
|
|
182
|
+
const label = kind === 'action' ? ep.name : ep.handler;
|
|
183
|
+
out.push({
|
|
184
|
+
target: `${file.path}:${ep.line} ${label} (proxy é o único guard)`,
|
|
185
|
+
location: `${file.path}:${ep.line}`,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
return out;
|
|
189
|
+
})
|
|
190
|
+
.build();
|
|
191
|
+
/**
|
|
192
|
+
* CA-5 — `NEXT_PUBLIC_*` com nome de segredo. O prefixo inlina o valor
|
|
193
|
+
* literal no bundle em build time: não é lookup de runtime e não é
|
|
194
|
+
* rotacionável depois de publicado.
|
|
195
|
+
*/
|
|
196
|
+
export const nextPublicEnvNotSecret = rule('next-public-env-not-secret')
|
|
197
|
+
.needsData('next')
|
|
198
|
+
.message('NEXT_PUBLIC_* com nome de segredo é inlined no bundle do cliente em build time; use nome sem prefixo para valor não público')
|
|
199
|
+
.assert((ctx) => {
|
|
200
|
+
const m = model(ctx);
|
|
201
|
+
const out = [];
|
|
202
|
+
for (const file of m.files) {
|
|
203
|
+
for (const er of file.envReads) {
|
|
204
|
+
if (!er.isPublic)
|
|
205
|
+
continue;
|
|
206
|
+
if (!SECRET_ENV_HINT.test(er.name))
|
|
207
|
+
continue;
|
|
208
|
+
out.push({
|
|
209
|
+
target: `${file.path}:${er.line} process.env.${er.name}`,
|
|
210
|
+
location: `${file.path}:${er.line}`,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return out;
|
|
215
|
+
})
|
|
216
|
+
.build();
|
|
217
|
+
/**
|
|
218
|
+
* O Plugin oficial do Next.js App Router para o Prumo.
|
|
219
|
+
*
|
|
220
|
+
* Analisa, nunca executa: zero dependência de `next`/`react`. Compat
|
|
221
|
+
* Next 14/15/16 (middleware.ts e proxy.ts; `cookies()` e `await cookies()`).
|
|
222
|
+
*/
|
|
223
|
+
export const nextPlugin = definePlugin({
|
|
224
|
+
name: 'node-next',
|
|
225
|
+
version: '0.1.0',
|
|
226
|
+
description: 'Next.js App Router invariants: Server Action auth guards, client boundary leaks, input validation, proxy-not-sole-auth, NEXT_PUBLIC secret hygiene.',
|
|
227
|
+
extractors: {
|
|
228
|
+
next: (ctx) => extractNextModel(ctx.root, (ctx.sourceFiles ?? [])),
|
|
229
|
+
},
|
|
230
|
+
rules: [
|
|
231
|
+
serverActionMutationGuarded,
|
|
232
|
+
clientBoundaryLeakPrevented,
|
|
233
|
+
serverActionInputValidated,
|
|
234
|
+
middlewareNotSoleAuth,
|
|
235
|
+
nextPublicEnvNotSecret,
|
|
236
|
+
],
|
|
237
|
+
});
|
|
238
|
+
export const nextPreset = nextPlugin.rules;
|
package/package.json
CHANGED
|
@@ -1,6 +1,37 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ihelpee/prumo-plugin-node-next",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.8.3",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Next.js App Router plugin for Prumo: Server Action guards, client boundary leaks, and input validation invariants.",
|
|
6
|
+
"author": "Alex Gotardi <alexgotardi@gmail.com> (https://github.com/alexgotardi)",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js",
|
|
13
|
+
"require": "./dist/index.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist",
|
|
18
|
+
"package.json",
|
|
19
|
+
"README.md"
|
|
20
|
+
],
|
|
21
|
+
"sideEffects": false,
|
|
22
|
+
"license": "Apache-2.0",
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "https://github.com/ihelpee/prumo.git"
|
|
26
|
+
},
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=20.11"
|
|
29
|
+
},
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"@ihelpee/prumo": "0.8.3",
|
|
35
|
+
"ts-morph": "^24.0.0"
|
|
36
|
+
}
|
|
6
37
|
}
|