@ihelpee/prumo-plugin-php-laravel 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 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,58 @@
1
- # Temporary Holding Version
1
+ # @ihelpee/prumo-plugin-php-laravel
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Invariantes PHP/Laravel para o [Prumo](https://github.com/ihelpee/prumo). Analisa, nunca executa: o subprocesso PHP apenas tokeniza com `token_get_all` (stdlib) e serializa a AST canônica em JSON — nenhuma linha do código analisado roda, e o gate nunca toca `vendor/` do projeto-alvo.
4
+
5
+ ## Instalação
6
+
7
+ ```bash
8
+ npm install -D @ihelpee/prumo-plugin-php-laravel
9
+ ```
10
+
11
+ Requer `php >= 8.1` no host do gate (não no projeto analisado). Sem `php`, o gate reporta `php-runtime-missing` (warn) em vez de fingir que fiscalizou.
12
+
13
+ ## Uso
14
+
15
+ ```ts
16
+ // prumo.config.ts do consumidor Laravel
17
+ import { defineConfig } from '@ihelpee/prumo';
18
+ import { phpLaravel } from '@ihelpee/prumo-plugin-php-laravel';
19
+
20
+ export default defineConfig({
21
+ layout: {
22
+ src: ['app'],
23
+ oracle: ['tests/Oracle'],
24
+ contract: ['.prumo/contract'],
25
+ invariants: ['.prumo/invariants'],
26
+ intent: ['.prumo/intent'],
27
+ waivers: ['.prumo/waivers'],
28
+ },
29
+ invariants: [phpLaravel({
30
+ oracleDirs: ['tests/Oracle'], // convenção de oráculo (default: tests/Oracle, tests/Feature/Oracle, oracle)
31
+ authSymbols: ['2fa'], // R2.2: símbolos ADICIONAIS que contam como auth (exato ou glob `*`)
32
+ publicSymbols: ['public'], // R2.3: convenção opt-in de rota intencionalmente pública
33
+ srcDirs: ['app'], // R3.2: prefixos de produção p/ fronteira reversa
34
+ testNamespaces: ['Tests'], // R3.2: namespaces que são código de teste
35
+ })],
36
+ testFilePatterns: ['tests/**/*.php', 'tests/**/*Test.php', 'tests/**/*_test.php'],
37
+ });
38
+ ```
39
+
40
+ ## Invariantes
41
+
42
+ | Regra | Sev | Pega | Não pega |
43
+ |---|---|---|---|
44
+ | `mutation-routes-guarded` | error | `Route::post/put/patch/delete` sem auth na rota, no grupo aninhado ou no controller; `throttle:api` NÃO conta como auth | middleware global do stack `web`/`api` (leia `bootstrap/app.php`/`Kernel` você mesmo); GET |
45
+ | `form-request-validated` | error | `Request` cru com `all()/input()/json()` sem `validate()`; payload cru + `unguard()` | `$request->validate([...])` inline; FormRequest com `rules()` |
46
+ | `form-request-hollow` | warn | FormRequest sem `rules()` preenchido | — |
47
+ | `no-raw-queries` | error | `DB::raw/whereRaw/selectRaw/DB::select...` interpolado ou sem bindings | SQL bruto com `?`/named bindings |
48
+ | `oracle-no-src` | error | `use App\...` **ou service-locator `app(FQCN::class)`/`resolve`/`->make`/`Container::make\|get`** dentro de `oracleDirs` (anti-burla: import dinâmico é import) | entrypoint (`bootstrap/app.php`) |
49
+ | `src-no-oracle` | error | `app/**` com `use Tests\...` (fixture de teste vazando para produção) | — |
50
+ | `oracle-no-auth-forge` | error | `withoutMiddleware()`/`actingAs()` no oráculo | login real via kernel HTTP (waiver para o caso legítimo) |
51
+ | `oracle-no-container-fake` | error | `mock/partialMock/swap/fake/Container::set` no oráculo | — |
52
+ | `test-mock-only` | warn | teste só com `expects/assertCalled` sem asserção de domínio | — |
53
+ | `php-parse-error` | error | arquivo que o tokenizador não leu (sintaxe inválida detectada via `TOKEN_PARSE`) | — |
54
+ | `php-runtime-missing` | warn | `php` ausente no host | — |
55
+
56
+ ## Por que subprocesso PHP e não `nikic/php-parser`?
57
+
58
+ `npx prumo gate` num repo Laravel precisa funcionar sem `composer install` do parser. O script `php/ast_extractor.php` é stdlib-only e embutido no pacote npm (`files: ["php"]`). `nikic/php-parser` empacotado no plugin é o upgrade path declarado para a fase de `fix`/`prune` — nunca o `vendor/` do consumidor. A lei mora no core Node; o PHP é só parser.
package/dist/ast.d.ts ADDED
@@ -0,0 +1,114 @@
1
+ /**
2
+ * AST Extractor PHP — ponte Node ↔ subprocesso PHP isolado.
3
+ *
4
+ * DECISÃO D2/D3 da spec: a LEI mora no core Node; o PHP é só um serializador.
5
+ * Este módulo invoca `php <pkg>/php/ast_extractor.php` via subprocesso com
6
+ * timeout, lê o JSON canônico v1 do stdout e o tipa. Nenhuma heurística de
7
+ * violação acontece aqui — só transporte e tipagem.
8
+ *
9
+ * R1.4: `php` ausente no host → retorna `null` (o check vira `skip` com
10
+ * motivo explícito no rules.ts). Nunca lança: gate que crasha é gate morto.
11
+ */
12
+ export interface PhpImport {
13
+ fqcn: string;
14
+ line: number;
15
+ use: boolean;
16
+ }
17
+ export interface PhpRoute {
18
+ method: string;
19
+ path: string;
20
+ handler: string;
21
+ controller: string | null;
22
+ handlerMethod: string | null;
23
+ routeMiddleware: string[];
24
+ groupMiddleware: string[];
25
+ line: number;
26
+ }
27
+ export interface PhpControllerMethod {
28
+ name: string;
29
+ line: number;
30
+ requestParam: string | null;
31
+ rawPayloadCalls: string[];
32
+ validatesInline: boolean;
33
+ unguard: boolean;
34
+ }
35
+ export interface PhpController {
36
+ class: string;
37
+ middleware: string[];
38
+ methods: PhpControllerMethod[];
39
+ }
40
+ export interface PhpFormRequest {
41
+ class: string;
42
+ authorize: boolean;
43
+ authorizeRaw: string;
44
+ hasRules: boolean;
45
+ line: number;
46
+ }
47
+ export interface PhpRawQuery {
48
+ call: string;
49
+ interpolated: boolean;
50
+ hasBindings: boolean;
51
+ line: number;
52
+ }
53
+ export interface PhpServiceLocator {
54
+ fqcn: string;
55
+ line: number;
56
+ }
57
+ export interface PhpTestMethod {
58
+ name: string;
59
+ line: number;
60
+ withoutMiddleware: boolean;
61
+ actingAs: boolean;
62
+ containerFakes: string[];
63
+ mockOnly: boolean;
64
+ importsApp: string[];
65
+ /** Anti-burla (spec §6.4): `app(FQCN::class)`/`resolve`/`make`/`Container::*` — import dinâmico. */
66
+ serviceLocator: PhpServiceLocator[];
67
+ }
68
+ export interface PhpTestClass {
69
+ class: string;
70
+ traits: string[];
71
+ methods: PhpTestMethod[];
72
+ }
73
+ export interface PhpFile {
74
+ path: string;
75
+ kind: 'routes' | 'controller' | 'formrequest' | 'test' | 'model' | 'other';
76
+ error?: string;
77
+ imports?: PhpImport[];
78
+ routes?: PhpRoute[];
79
+ controllers?: PhpController[];
80
+ formRequests?: PhpFormRequest[];
81
+ rawQueries?: PhpRawQuery[];
82
+ tests?: PhpTestClass[];
83
+ /** Anti-burla (spec §6.4): service-locators do arquivo inteiro (setUp, helpers de topo). */
84
+ serviceLocator?: PhpServiceLocator[];
85
+ }
86
+ export interface PhpModel {
87
+ version: 1;
88
+ files: PhpFile[];
89
+ }
90
+ /**
91
+ * Walk determinístico de arquivos `.php` sob `root`, ordenado por caminho.
92
+ * O core só faz glob `.ts/.tsx`, então o plugin anda pelos `.php` ele mesmo
93
+ * (R1.6). Ordem importa: o report precisa ser byte-idêntico entre execuções.
94
+ */
95
+ export declare function walkPhp(root: string, dir?: string): Promise<string[]>;
96
+ export interface PhpExtractorOptions {
97
+ /** Binário php (default `php`). */
98
+ phpBin?: string;
99
+ /** Timeout do subprocesso em ms (default 15000 — R1.5). */
100
+ timeoutMs?: number;
101
+ }
102
+ /**
103
+ * Executa o extractor PHP e retorna o modelo canônico, ou `null` quando o
104
+ * binário `php` está ausente (R1.4). Timeout estourado lança — o rules.ts
105
+ * captura e reporta `php-parse-timeout` (R1.5).
106
+ */
107
+ export declare function runPhpExtractor(root: string, files: string[], opts?: PhpExtractorOptions): Promise<PhpModel | null>;
108
+ /**
109
+ * Extrator registrado no motor via `definePlugin`. O motor chama com o
110
+ * `RuleContext`; aqui andamos pelos `.php` do root e invocamos o subprocesso.
111
+ * Retorna `null` quando `php` está ausente — as regras tratam `null` como skip.
112
+ */
113
+ export declare function extractPhpModel(root: string): Promise<PhpModel | null>;
114
+ //# sourceMappingURL=ast.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["../src/ast.ts"],"names":[],"mappings":"AAKA;;;;;;;;;;GAUG;AAEH,MAAM,WAAW,SAAS;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,OAAO,CAAC;CACd;AAED,MAAM,WAAW,QAAQ;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,eAAe,EAAE,MAAM,EAAE,CAAC;IAC1B,eAAe,EAAE,MAAM,EAAE,CAAC;IAC1B,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,mBAAmB;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,eAAe,EAAE,MAAM,EAAE,CAAC;IAC1B,eAAe,EAAE,OAAO,CAAC;IACzB,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,OAAO,EAAE,mBAAmB,EAAE,CAAC;CAChC;AAED,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,OAAO,CAAC;IACnB,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,EAAE,OAAO,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,EAAE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B,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,SAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAsBxE;AAUD,MAAM,WAAW,mBAAmB;IAClC,mCAAmC;IACnC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,2DAA2D;IAC3D,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;;;GAIG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,EAAE,EACf,IAAI,GAAE,mBAAwB,GAC7B,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAqB1B;AAkDD;;;;GAIG;AACH,wBAAsB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAG5E"}
package/dist/ast.js ADDED
@@ -0,0 +1,126 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { readdir, stat } from 'node:fs/promises';
3
+ import { join, extname, dirname, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ /** Diretórios que o extractor NUNCA toca (R1.2). */
6
+ const SKIP_DIRS = new Set([
7
+ 'node_modules',
8
+ 'vendor',
9
+ 'storage',
10
+ 'dist',
11
+ 'build',
12
+ '.git',
13
+ '.idea',
14
+ 'bootstrap',
15
+ ]);
16
+ /**
17
+ * Walk determinístico de arquivos `.php` sob `root`, ordenado por caminho.
18
+ * O core só faz glob `.ts/.tsx`, então o plugin anda pelos `.php` ele mesmo
19
+ * (R1.6). Ordem importa: o report precisa ser byte-idêntico entre execuções.
20
+ */
21
+ export async function walkPhp(root, dir = '.') {
22
+ const abs = join(root, dir);
23
+ const out = [];
24
+ let entries;
25
+ try {
26
+ entries = await readdir(abs);
27
+ }
28
+ catch {
29
+ return out;
30
+ }
31
+ for (const name of entries.sort()) {
32
+ if (SKIP_DIRS.has(name))
33
+ continue;
34
+ const full = join(abs, name);
35
+ const rel = dir === '.' ? name : `${dir}/${name}`;
36
+ const st = await stat(full).catch(() => null);
37
+ if (!st)
38
+ continue;
39
+ if (st.isDirectory()) {
40
+ out.push(...(await walkPhp(root, rel)));
41
+ }
42
+ else if (extname(name) === '.php') {
43
+ out.push(rel);
44
+ }
45
+ }
46
+ return out;
47
+ }
48
+ /** Caminho absoluto do script PHP embutido, válido em src (dev) e dist (prod). */
49
+ function extractorScriptPath() {
50
+ // src/ast.ts e dist/ast.js estão ambos a um nível da raiz do pacote, então
51
+ // `../php/ast_extractor.php` resolve nos dois casos.
52
+ const here = dirname(fileURLToPath(import.meta.url));
53
+ return resolve(here, '..', 'php', 'ast_extractor.php');
54
+ }
55
+ /**
56
+ * Executa o extractor PHP e retorna o modelo canônico, ou `null` quando o
57
+ * binário `php` está ausente (R1.4). Timeout estourado lança — o rules.ts
58
+ * captura e reporta `php-parse-timeout` (R1.5).
59
+ */
60
+ export async function runPhpExtractor(root, files, opts = {}) {
61
+ if (files.length === 0)
62
+ return { version: 1, files: [] };
63
+ const phpBin = opts.phpBin ?? process.env['PRUMO_PHP_BIN'] ?? 'php';
64
+ const timeoutMs = opts.timeoutMs ?? 15000;
65
+ const script = extractorScriptPath();
66
+ const { stdout, code, timedOut, notFound } = await spawnPhp(phpBin, script, root, files, timeoutMs);
67
+ if (notFound)
68
+ return null; // R1.4 — php ausente: skip com motivo.
69
+ if (timedOut)
70
+ throw new Error('php-parse-timeout'); // R1.5
71
+ if (code !== 0) {
72
+ // O script sempre sai 0; saída não-zero é ambiente quebrado → skip honesto.
73
+ return null;
74
+ }
75
+ try {
76
+ const parsed = JSON.parse(stdout);
77
+ if (parsed.version !== 1)
78
+ return { version: 1, files: [] };
79
+ return parsed;
80
+ }
81
+ catch {
82
+ throw new Error('php-parse-error');
83
+ }
84
+ }
85
+ function spawnPhp(phpBin, script, root, files, timeoutMs) {
86
+ return new Promise((res) => {
87
+ const child = spawn(phpBin, [script, '--root', root, '--files', ...files], {
88
+ stdio: ['ignore', 'pipe', 'pipe'],
89
+ });
90
+ let stdout = '';
91
+ let stderr = '';
92
+ let timedOut = false;
93
+ const timer = setTimeout(() => {
94
+ timedOut = true;
95
+ child.kill('SIGKILL');
96
+ }, timeoutMs);
97
+ child.stdout.on('data', (b) => {
98
+ stdout += b.toString('utf8');
99
+ });
100
+ child.stderr.on('data', (b) => {
101
+ stderr += b.toString('utf8');
102
+ });
103
+ child.on('error', (err) => {
104
+ clearTimeout(timer);
105
+ res({ stdout: '', code: -1, timedOut: false, notFound: err.code === 'ENOENT' });
106
+ });
107
+ child.on('close', (code) => {
108
+ clearTimeout(timer);
109
+ if (timedOut) {
110
+ res({ stdout: '', code: -1, timedOut: true, notFound: false });
111
+ return;
112
+ }
113
+ void stderr; // stderr é diagnóstico; nunca entra no JSON.
114
+ res({ stdout, code: code ?? -1, timedOut: false, notFound: false });
115
+ });
116
+ });
117
+ }
118
+ /**
119
+ * Extrator registrado no motor via `definePlugin`. O motor chama com o
120
+ * `RuleContext`; aqui andamos pelos `.php` do root e invocamos o subprocesso.
121
+ * Retorna `null` quando `php` está ausente — as regras tratam `null` como skip.
122
+ */
123
+ export async function extractPhpModel(root) {
124
+ const files = await walkPhp(root);
125
+ return runPhpExtractor(root, files);
126
+ }
@@ -0,0 +1,4 @@
1
+ export * from './ast.js';
2
+ export * from './rules.js';
3
+ export { phpLaravel as default } from './rules.js';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -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
@@ -0,0 +1,3 @@
1
+ export * from './ast.js';
2
+ export * from './rules.js';
3
+ export { phpLaravel as default } from './rules.js';
@@ -0,0 +1,120 @@
1
+ import { type RuleDef, type PrumoPlugin } from '@ihelpee/prumo/invariants';
2
+ export interface PhpLaravelOptions {
3
+ /** Caminhos (prefixos relativos) tratados como layout.oracle. */
4
+ oracleDirs?: string[];
5
+ /** R2.2 — símbolos ADICIONAIS que contam como auth (exato ou glob `*`). */
6
+ authSymbols?: string[];
7
+ /** R2.3 — convenção opt-in de rota intencionalmente pública. Default: []. */
8
+ publicSymbols?: string[];
9
+ /** Prefixos de caminho de produção p/ `src-no-oracle` (R3.2). Default: ['app']. */
10
+ srcDirs?: string[];
11
+ /** Prefixos de namespace que são código de teste (R3.2). Default: ['Tests']. */
12
+ testNamespaces?: string[];
13
+ }
14
+ /**
15
+ * I1 / R2.1–R2.4 — rota de mutação (`POST/PUT/PATCH/DELETE`) sem middleware
16
+ * de autenticação/autorização em NENHUMA camada efetiva: middleware da rota,
17
+ * middleware do grupo aninhado, ou middleware do controller resolvido.
18
+ *
19
+ * R2.2/R2.3 (preset §5.2): `authSymbols` acrescenta símbolos de proteção ao
20
+ * piso estrutural; `publicSymbols` marca rota pública intencional (opt-in do
21
+ * consumidor) — sem convenção declarada, rota de mutação sem auth é sempre
22
+ * finding.
23
+ *
24
+ * Não pega: middleware global do stack web/api (exigiria ler
25
+ * bootstrap/app.php/Kernel — fronteira declarada; cubra via authSymbols no
26
+ * controller). Rotas GET nunca são alvo.
27
+ */
28
+ export declare function makeMutationRoutesGuarded(authSymbols: string[], publicSymbols: string[]): RuleDef;
29
+ /**
30
+ * I2 / R2.5–R2.6 — método de controller com `Request` cru consumindo payload
31
+ * via all()/input()/json() sem validação inline; ou payload cru com
32
+ * `unguard()` no corpo (mass assignment forçado, mesmo com FormRequest).
33
+ *
34
+ * Não pega: `$request->validate([...])` inline (satisfaz, R2.8) e
35
+ * FormRequest tipado com rules() real.
36
+ */
37
+ export declare const formRequestValidated: RuleDef;
38
+ /**
39
+ * R2.7 — FormRequest oco: classe gerada por `php artisan make:request` sem
40
+ * rules() preenchido (o agente faz isso constantemente) — autorização
41
+ * decorativa sobre rota que parece protegida. `warn`: a classe pode ser
42
+ * legítima em migração progressiva.
43
+ */
44
+ export declare const formRequestHollow: RuleDef;
45
+ /**
46
+ * I3 / R2.9–R2.11 — SQL bruto com interpolação/concatenação de variável é
47
+ * injeção; SQL bruto estático ou com bindings (`?`/named) é aceitável.
48
+ *
49
+ * False-positive guard (R2.11): interpolação de constante `self::`/`::CONST`
50
+ * e `config(...)` não é input externo — o extractor só marca T_VARIABLE, e
51
+ * constantes não são variáveis. Calibrado por fixture.
52
+ */
53
+ export declare const noRawQueries: RuleDef;
54
+ /**
55
+ * R3.1 — `use App\...` dentro de layout.oracle: o teste importa a unidade que
56
+ * deveria fiscalizar de fora. É espelho, não oráculo.
57
+ *
58
+ * Anti-burla (R3.3 / spec §6.4 / card F1): `app(Service::class)`,
59
+ * `resolve(...)`, `->make(...)`, `Container::make/get(...)` são IMPORT
60
+ * DINÂMICO — o teste que não escreveu `use App\...` ainda alcança a unidade.
61
+ * O extractor emite a aresta `serviceLocator` (método + arquivo inteiro);
62
+ * cada FQCN sob `App\` no oráculo é finding, exatamente como o `use` estático.
63
+ * Sem isto, o service-locator é a burla que vira a lei de cabeça para baixo.
64
+ */
65
+ export declare function makeOracleNoSrc(oracleDirs: string[]): RuleDef;
66
+ /**
67
+ * R3.2 — fronteira reversa: `app/**` importando `tests/**` (espelho indireto
68
+ * vazando para produção). O core resolve só imports TS; o extractor PHP dá a
69
+ * aresta (`imports[].fqcn`), e esta regra espelha a do core TS e a do plugin
70
+ * python (srcNoOracle): arquivo sob `srcDirs` cujo import resolve para um
71
+ * namespace de teste (`Tests\...`) é finding.
72
+ */
73
+ export declare function makeSrcNoOracle(srcDirs: string[], testNamespaces: string[]): RuleDef;
74
+ /**
75
+ * R3.3 / I4 — a regra-assinatura do plugin: dentro do oráculo,
76
+ * `withoutMiddleware()` remove e `actingAs()` forja exatamente a camada de
77
+ * autorização que I1 fiscaliza. O teste passa porque a proteção foi
78
+ * desligada, não porque a autorização funciona.
79
+ *
80
+ * Fronteira honesta: `actingAs` para obter token via fluxo real de login é
81
+ * aceitável (spec §4.2); o MVP marca o sinal e o alvo nomeia o método — o
82
+ * waiver existe para o caso legítimo, nunca o skip silencioso.
83
+ */
84
+ export declare function makeOracleNoAuthForge(oracleDirs: string[]): RuleDef;
85
+ /**
86
+ * R3.4 / I5 — fakes de container dentro do oráculo substituem unidades por
87
+ * crença do agente: espelho por construção.
88
+ */
89
+ export declare function makeOracleNoContainerFake(oracleDirs: string[]): RuleDef;
90
+ /**
91
+ * I6 / R3.5 — teste cujo corpo é só mock + assertCalled, sem asserção de
92
+ * domínio, é teste-espelho: verifica que o mock foi chamado, não que o
93
+ * negócio aconteceu. `warn` no MVP (heurística de corpo é frágil).
94
+ */
95
+ export declare const testMockOnly: RuleDef;
96
+ /**
97
+ * R1.3 — arquivo que o tokenizador não leu (sintaxe ilegível) é finding
98
+ * `error`, nunca skip silencioso: gate que pula mudo reporta mais saúde do
99
+ * que existe.
100
+ */
101
+ export declare const phpParseError: RuleDef;
102
+ /**
103
+ * R1.4 — `php` ausente no host: o extractor retornou null. O gate NÃO pode
104
+ * fingir que fiscalizou PHP: finding `warn` nomeia o runtime ausente e o
105
+ * `prumo doctor`/CI deve instalar o binário. Skip silencioso é a falsa
106
+ * sensação que a spec §8 lista como risco grave.
107
+ */
108
+ export declare const phpRuntimeMissing: RuleDef;
109
+ /**
110
+ * O plugin oficial PHP/Laravel do Prumo.
111
+ *
112
+ * Analisa, nunca executa: o subprocesso PHP só tokeniza (stdlib
113
+ * `token_get_all`); nenhuma linha do código analisado roda. `php` ausente →
114
+ * skip honesto com finding `php-runtime-missing`, nunca gate mudo.
115
+ */
116
+ export declare function phpLaravel(options?: PhpLaravelOptions): PrumoPlugin;
117
+ /** Preset com a convenção padrão de oráculo (usa em invariants/rules.ts). */
118
+ export declare const phpLaravelPreset: RuleDef[];
119
+ export default phpLaravel;
120
+ //# sourceMappingURL=rules.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rules.d.ts","sourceRoot":"","sources":["../src/rules.ts"],"names":[],"mappings":"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