wp-shakedown 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/LICENSE +340 -0
  2. package/README.md +62 -2
  3. package/dist/baseline.d.ts +6 -0
  4. package/dist/baseline.js +41 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +139 -0
  7. package/dist/diff.d.ts +7 -0
  8. package/dist/diff.js +24 -0
  9. package/dist/engines/config.d.ts +3 -0
  10. package/dist/engines/config.js +133 -0
  11. package/dist/engines/eslint.d.ts +8 -0
  12. package/dist/engines/eslint.js +96 -0
  13. package/dist/engines/index.d.ts +2 -0
  14. package/dist/engines/index.js +12 -0
  15. package/dist/engines/integrity.d.ts +2 -0
  16. package/dist/engines/integrity.js +108 -0
  17. package/dist/engines/php-compat.d.ts +2 -0
  18. package/dist/engines/php-compat.js +26 -0
  19. package/dist/engines/php-lint.d.ts +6 -0
  20. package/dist/engines/php-lint.js +41 -0
  21. package/dist/engines/phpstan.d.ts +11 -0
  22. package/dist/engines/phpstan.js +102 -0
  23. package/dist/engines/stylelint.d.ts +4 -0
  24. package/dist/engines/stylelint.js +63 -0
  25. package/dist/engines/updates.d.ts +4 -0
  26. package/dist/engines/updates.js +72 -0
  27. package/dist/engines/vulnerabilities.d.ts +22 -0
  28. package/dist/engines/vulnerabilities.js +128 -0
  29. package/dist/engines/wp-json.d.ts +18 -0
  30. package/dist/engines/wp-json.js +133 -0
  31. package/dist/engines/wpcs.d.ts +7 -0
  32. package/dist/engines/wpcs.js +60 -0
  33. package/dist/exec.d.ts +12 -0
  34. package/dist/exec.js +19 -0
  35. package/dist/fingerprint.d.ts +10 -0
  36. package/dist/fingerprint.js +29 -0
  37. package/dist/health/install.d.ts +16 -0
  38. package/dist/health/install.js +68 -0
  39. package/dist/home.d.ts +2 -0
  40. package/dist/home.js +6 -0
  41. package/dist/index.d.ts +38 -0
  42. package/dist/index.js +32 -0
  43. package/dist/js/files.d.ts +4 -0
  44. package/dist/js/files.js +47 -0
  45. package/dist/js/tools.d.ts +3 -0
  46. package/dist/js/tools.js +67 -0
  47. package/dist/mcp/server.d.ts +9 -0
  48. package/dist/mcp/server.js +91 -0
  49. package/dist/mcp/tools.d.ts +26 -0
  50. package/dist/mcp/tools.js +149 -0
  51. package/dist/net.d.ts +18 -0
  52. package/dist/net.js +68 -0
  53. package/dist/php/files.d.ts +3 -0
  54. package/dist/php/files.js +53 -0
  55. package/dist/php/php.d.ts +4 -0
  56. package/dist/php/php.js +25 -0
  57. package/dist/php/phpcs.d.ts +25 -0
  58. package/dist/php/phpcs.js +55 -0
  59. package/dist/php/tools.d.ts +3 -0
  60. package/dist/php/tools.js +66 -0
  61. package/dist/progress.d.ts +3 -0
  62. package/dist/progress.js +13 -0
  63. package/dist/report/escape.d.ts +1 -0
  64. package/dist/report/escape.js +4 -0
  65. package/dist/report/html.d.ts +2 -0
  66. package/dist/report/html.js +100 -0
  67. package/dist/report/json.d.ts +2 -0
  68. package/dist/report/json.js +3 -0
  69. package/dist/report/markdown.d.ts +5 -0
  70. package/dist/report/markdown.js +92 -0
  71. package/dist/report/sarif.d.ts +2 -0
  72. package/dist/report/sarif.js +44 -0
  73. package/dist/report/write.d.ts +9 -0
  74. package/dist/report/write.js +48 -0
  75. package/dist/runner.d.ts +11 -0
  76. package/dist/runner.js +152 -0
  77. package/dist/session.d.ts +19 -0
  78. package/dist/session.js +31 -0
  79. package/dist/target.d.ts +5 -0
  80. package/dist/target.js +114 -0
  81. package/dist/types.d.ts +135 -0
  82. package/dist/types.js +4 -0
  83. package/dist/ui/server.d.ts +13 -0
  84. package/dist/ui/server.js +295 -0
  85. package/dist/version.d.ts +1 -0
  86. package/dist/version.js +3 -0
  87. package/dist/versions.d.ts +9 -0
  88. package/dist/versions.js +35 -0
  89. package/js-tools/eslint.config.mjs +19 -0
  90. package/js-tools/package-lock.json +7004 -0
  91. package/js-tools/package.json +13 -0
  92. package/js-tools/stylelint.config.mjs +4 -0
  93. package/package.json +57 -4
  94. package/php-tools/composer.json +40 -0
  95. package/php-tools/composer.lock +868 -0
  96. package/ui/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  97. package/ui/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  98. package/ui/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  99. package/ui/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  100. package/ui/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  101. package/ui/dist/assets/index-7zN46ssH.js +54 -0
  102. package/ui/dist/assets/index-B1axZya5.css +2 -0
  103. package/ui/dist/index.html +14 -0
@@ -0,0 +1,133 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ /** Removes PHP comments and leaves quoted strings alone, so a salt with // or # in it stays whole. */
4
+ function stripComments(text) {
5
+ let out = '';
6
+ for (let i = 0; i < text.length; i++) {
7
+ const c = text[i];
8
+ if (c === "'" || c === '"') {
9
+ let j = i + 1;
10
+ while (j < text.length && text[j] !== c)
11
+ j += text[j] === '\\' ? 2 : 1;
12
+ out += text.slice(i, j + 1);
13
+ i = j;
14
+ }
15
+ else if (c === '#' || (c === '/' && text[i + 1] === '/')) {
16
+ while (i < text.length && text[i] !== '\n')
17
+ i++;
18
+ out += '\n';
19
+ }
20
+ else if (c === '/' && text[i + 1] === '*') {
21
+ const end = text.indexOf('*/', i + 2);
22
+ i = end < 0 ? text.length : end + 1;
23
+ out += ' ';
24
+ }
25
+ else
26
+ out += c;
27
+ }
28
+ return out;
29
+ }
30
+ const SALTS = ['AUTH_KEY', 'SECURE_AUTH_KEY', 'LOGGED_IN_KEY', 'NONCE_KEY', 'AUTH_SALT', 'SECURE_AUTH_SALT', 'LOGGED_IN_SALT', 'NONCE_SALT'];
31
+ const FILE = { file: 'wp-config.php' };
32
+ export function configFindings(text) {
33
+ const code = stripComments(text);
34
+ const define = (name) => new RegExp(`define\\(\\s*['"]${name}['"]\\s*,\\s*(.+?)\\s*\\)\\s*;`, 's').exec(code)?.[1];
35
+ const isOn = (v) => v !== undefined && /^(true|1)$/i.test(v);
36
+ const out = [];
37
+ if (isOn(define('WP_DEBUG'))) {
38
+ out.push({ rule: 'config.debug', severity: 'warning', category: 'security', message: 'WP_DEBUG is on.', hint: 'Turn it off on a live site. Error output can reveal paths and code.', location: FILE });
39
+ }
40
+ const weak = SALTS.some((k) => {
41
+ const v = define(k);
42
+ if (v === undefined)
43
+ return true;
44
+ const m = /^(['"])([\s\S]*)\1$/.exec(v);
45
+ return !!m && (m[2] === 'put your unique phrase here' || m[2].length < 32);
46
+ });
47
+ if (weak) {
48
+ out.push({
49
+ rule: 'config.salts', severity: 'error', category: 'security', message: 'The secret keys in wp-config.php are missing, short or still the default.',
50
+ hint: 'Generate new ones at https://api.wordpress.org/secret-key/1.1/salt/ and paste them in.', location: FILE,
51
+ });
52
+ }
53
+ if (!isOn(define('DISALLOW_FILE_EDIT'))) {
54
+ out.push({
55
+ rule: 'config.file-edit', severity: 'info', category: 'security', message: 'The theme and plugin editor in the dashboard is on.',
56
+ hint: "Add define( 'DISALLOW_FILE_EDIT', true ); to wp-config.php.", location: FILE,
57
+ });
58
+ }
59
+ return out;
60
+ }
61
+ const names = (dir) => {
62
+ try {
63
+ return readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile()).map((e) => e.name).sort();
64
+ }
65
+ catch {
66
+ return [];
67
+ }
68
+ };
69
+ function uploadsPhp(root, dir, out) {
70
+ let entries;
71
+ try {
72
+ entries = readdirSync(path.join(root, dir), { withFileTypes: true });
73
+ }
74
+ catch {
75
+ return;
76
+ }
77
+ for (const e of entries.sort((a, b) => (a.name < b.name ? -1 : 1))) {
78
+ const rel = `${dir}/${e.name}`;
79
+ if (e.isDirectory())
80
+ uploadsPhp(root, rel, out);
81
+ else if (e.isFile() && /\.(php|phtml|phar)$/i.test(e.name)) {
82
+ if (e.name.toLowerCase() === 'index.php' && statSync(path.join(root, rel)).size < 100)
83
+ continue;
84
+ out.push(rel);
85
+ }
86
+ }
87
+ }
88
+ export const config = {
89
+ id: 'config',
90
+ title: 'Configuration and risky files',
91
+ kinds: ['install'],
92
+ async run({ target, note }) {
93
+ const root = target.path;
94
+ const out = [];
95
+ const cfg = path.join(root, 'wp-config.php');
96
+ if (!existsSync(cfg)) {
97
+ note('No wp-config.php in this folder. Its settings were not checked.');
98
+ }
99
+ else {
100
+ out.push(...configFindings(readFileSync(cfg, 'utf8')));
101
+ if (process.platform !== 'win32' && statSync(cfg).mode & 0o002) {
102
+ out.push({ rule: 'config.writable', severity: 'error', category: 'security', message: 'Every user on the machine can write to wp-config.php.', hint: 'Set its mode to 640 or 600.', location: FILE });
103
+ }
104
+ }
105
+ const dump = /\.sql(\.gz|\.zip)?$/i;
106
+ const add = (rule, severity, message, hint, file) => out.push({ rule, severity, category: 'security', message, hint, location: { file } });
107
+ for (const n of names(root)) {
108
+ if (/^wp-config.*\.(bak|old|save|orig|txt|swp)$|^wp-config\.php~$/i.test(n))
109
+ add('leftover.config-copy', 'error', 'A copy of wp-config.php that a web server can send as plain text.', 'Delete it or move it out of the web folder.', n);
110
+ else if (dump.test(n))
111
+ add('leftover.dump', 'error', 'A database dump in a web folder.', 'Delete it or move it out of the web folder.', n);
112
+ else if (/^(phpinfo|info|adminer|installer|installer-backup)\.php$/i.test(n))
113
+ add('leftover.tool', 'warning', 'A setup or debug tool left in the web folder.', 'Delete it.', n);
114
+ else if (n === '.env')
115
+ add('leftover.env', 'warning', 'An .env file in the web folder.', 'Move it above the web folder or block it in the server config.', n);
116
+ }
117
+ for (const n of names(path.join(root, 'wp-content'))) {
118
+ if (dump.test(n))
119
+ add('leftover.dump', 'error', 'A database dump in a web folder.', 'Delete it or move it out of the web folder.', `wp-content/${n}`);
120
+ }
121
+ if (existsSync(path.join(root, 'wp-content', 'debug.log'))) {
122
+ add('leftover.debug-log', 'warning', 'wp-content/debug.log is readable from the web unless the server blocks it.', 'Delete it and turn off WP_DEBUG_LOG, or move the log.', 'wp-content/debug.log');
123
+ }
124
+ const php = [];
125
+ uploadsPhp(root, 'wp-content/uploads', php);
126
+ for (const file of php.slice(0, 50)) {
127
+ add('uploads.php', 'error', 'A PHP file in the uploads folder.', 'Uploads should hold media only. Check the file: malware often hides here.', file);
128
+ }
129
+ if (php.length > 50)
130
+ note(`${php.length} PHP files are in the uploads folder. The report lists the first 50.`);
131
+ return out;
132
+ },
133
+ };
@@ -0,0 +1,8 @@
1
+ import type { Category, Engine, RawFinding } from '../types.ts';
2
+ export declare function categoriseJs(ruleId: string): Category;
3
+ /** The tools print real paths, so a base behind a symlink (macOS /var) is resolved first. */
4
+ export declare function posixRelative(base: string, file: string): string;
5
+ export declare function parseEslint(json: string, base: string): RawFinding[];
6
+ export declare const firstLine: (s: string) => string;
7
+ export declare function chunks<T>(list: T[], size: number): T[][];
8
+ export declare const eslint: Engine;
@@ -0,0 +1,96 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { exec } from '../exec.js';
4
+ import { isGenerated, sourceFiles } from '../js/files.js';
5
+ import { jsTools } from '../js/tools.js';
6
+ export function categoriseJs(ruleId) {
7
+ if (/^jsx-a11y\//.test(ruleId))
8
+ return 'accessibility';
9
+ if (/^@wordpress\/i18n-/.test(ruleId))
10
+ return 'i18n';
11
+ if (/^(prettier\/|jsdoc\/|import\/order$|@wordpress\/dependency-group$|no-var$|prefer-|object-shorthand$|camelcase$|curly$|dot-notation$|quote-props$|one-var$|no-else-return$|no-lonely-if$|no-nested-ternary$|no-unneeded-ternary$|no-useless-|spaced-comment$|yoda$|no-console$|no-multi-str$)/.test(ruleId))
12
+ return 'standards';
13
+ return 'correctness';
14
+ }
15
+ /** The tools print real paths, so a base behind a symlink (macOS /var) is resolved first. */
16
+ export function posixRelative(base, file) {
17
+ let rel = path.relative(base, file);
18
+ if (rel.startsWith('..')) {
19
+ try {
20
+ rel = path.relative(realpathSync(base), file);
21
+ }
22
+ catch {
23
+ // Keep the first answer.
24
+ }
25
+ }
26
+ return rel.split(path.sep).join('/');
27
+ }
28
+ export function parseEslint(json, base) {
29
+ let data;
30
+ try {
31
+ data = JSON.parse(json);
32
+ }
33
+ catch {
34
+ data = null;
35
+ }
36
+ if (!Array.isArray(data))
37
+ throw new Error('ESLint returned output that is not JSON.');
38
+ const out = [];
39
+ for (const f of data) {
40
+ for (const m of f.messages ?? []) {
41
+ const location = {
42
+ file: posixRelative(base, f.filePath),
43
+ ...(m.line ? { line: m.line } : {}),
44
+ ...(m.column ? { column: m.column } : {}),
45
+ };
46
+ if (m.fatal) {
47
+ out.push({ rule: 'syntax', severity: 'error', category: 'correctness', message: m.message, location });
48
+ continue;
49
+ }
50
+ const rule = m.ruleId ?? 'eslint';
51
+ const category = categoriseJs(rule);
52
+ out.push({
53
+ rule,
54
+ severity: category === 'standards' ? 'info' : 'warning',
55
+ category,
56
+ message: m.message,
57
+ location,
58
+ ...(m.fix ? { hint: 'eslint --fix can fix this.' } : {}),
59
+ });
60
+ }
61
+ }
62
+ return out;
63
+ }
64
+ export const firstLine = (s) => s.split('\n').map((l) => l.trim()).find(Boolean) ?? '';
65
+ export function chunks(list, size) {
66
+ const out = [];
67
+ for (let i = 0; i < list.length; i += size)
68
+ out.push(list.slice(i, i + size));
69
+ return out;
70
+ }
71
+ export const eslint = {
72
+ id: 'eslint',
73
+ title: 'JavaScript',
74
+ kinds: ['theme', 'plugin'],
75
+ async run({ target, signal, note }) {
76
+ const files = sourceFiles(target.path, ['.js', '.jsx', '.mjs', '.cjs']).filter((f) => !isGenerated(f));
77
+ if (files.length === 0)
78
+ return [];
79
+ const tools = await jsTools(note);
80
+ const out = [];
81
+ for (const chunk of chunks(files, 200)) {
82
+ if (signal?.aborted)
83
+ break;
84
+ const r = await exec(process.execPath, [
85
+ path.join(tools, 'node_modules', 'eslint', 'bin', 'eslint.js'),
86
+ '--no-config-lookup', '-c', path.join(tools, 'eslint.config.mjs'),
87
+ '--format', 'json', '--no-error-on-unmatched-pattern', '--no-warn-ignored',
88
+ ...chunk.map((f) => posixRelative(target.path, f)),
89
+ ], { cwd: target.path, ...(signal ? { signal } : {}) });
90
+ if (r.code !== 0 && r.code !== 1)
91
+ throw new Error(`ESLint stopped: ${firstLine(r.stderr) || firstLine(r.stdout)}`);
92
+ out.push(...parseEslint(r.stdout, target.path));
93
+ }
94
+ return out;
95
+ },
96
+ };
@@ -0,0 +1,2 @@
1
+ import type { Engine } from '../types.ts';
2
+ export declare const engines: Engine[];
@@ -0,0 +1,12 @@
1
+ import { config } from './config.js';
2
+ import { eslint } from './eslint.js';
3
+ import { integrity } from './integrity.js';
4
+ import { phpCompat } from './php-compat.js';
5
+ import { phpLint } from './php-lint.js';
6
+ import { phpstan } from './phpstan.js';
7
+ import { stylelint } from './stylelint.js';
8
+ import { updates } from './updates.js';
9
+ import { vulnerabilities } from './vulnerabilities.js';
10
+ import { wpJson } from './wp-json.js';
11
+ import { wpcs } from './wpcs.js';
12
+ export const engines = [phpLint, wpcs, phpCompat, phpstan, wpJson, eslint, stylelint, integrity, updates, vulnerabilities, config];
@@ -0,0 +1,2 @@
1
+ import type { Engine } from '../types.ts';
2
+ export declare const integrity: Engine;
@@ -0,0 +1,108 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { coreVersion, packages, skipOnNetwork } from '../health/install.js';
5
+ import { getJson } from '../net.js';
6
+ import { EngineSkipped } from '../types.js';
7
+ const MONTH = 30 * 24 * 3600 * 1000;
8
+ const md5 = (file) => createHash('md5').update(readFileSync(file)).digest('hex');
9
+ const rec = (v) => (v && typeof v === 'object' ? v : undefined);
10
+ function walk(root, dir, out) {
11
+ let entries;
12
+ try {
13
+ entries = readdirSync(path.join(root, dir), { withFileTypes: true });
14
+ }
15
+ catch {
16
+ return;
17
+ }
18
+ for (const e of entries.sort((a, b) => (a.name < b.name ? -1 : 1))) {
19
+ const rel = `${dir}/${e.name}`;
20
+ if (e.isDirectory())
21
+ walk(root, rel, out);
22
+ else if (e.isFile() && e.name !== '.DS_Store')
23
+ out.push(rel);
24
+ }
25
+ }
26
+ export const integrity = {
27
+ id: 'integrity',
28
+ title: 'File integrity',
29
+ kinds: ['install'],
30
+ run({ target, signal, note }) {
31
+ return skipOnNetwork(async () => {
32
+ const root = target.path;
33
+ const out = [];
34
+ const cv = coreVersion(root);
35
+ if (!cv)
36
+ throw new EngineSkipped('Cannot read the WordPress version from wp-includes/version.php.');
37
+ const url = (locale) => `https://api.wordpress.org/core/checksums/1.0/?version=${cv.version}&locale=${locale}`;
38
+ let r = await getJson(url(cv.locale), { ttlMs: MONTH, ...(signal ? { signal } : {}) });
39
+ let sums = rec(rec(r.data)?.checksums);
40
+ if (!sums && cv.locale !== 'en_US') {
41
+ r = await getJson(url('en_US'), { ttlMs: MONTH, ...(signal ? { signal } : {}) });
42
+ sums = rec(rec(r.data)?.checksums);
43
+ }
44
+ if (!sums) {
45
+ note(`wordpress.org has no checksums for WordPress ${cv.version}. Core files were not compared.`);
46
+ }
47
+ else {
48
+ for (const [file, sum] of Object.entries(sums)) {
49
+ if (file.startsWith('wp-content/'))
50
+ continue;
51
+ const abs = path.join(root, file);
52
+ if (!existsSync(abs)) {
53
+ out.push({ rule: 'core.missing', severity: 'warning', category: 'health', message: 'A WordPress core file is missing.', location: { file } });
54
+ }
55
+ else if (md5(abs) !== sum) {
56
+ out.push({
57
+ rule: 'core.modified', severity: 'error', category: 'security',
58
+ message: 'This WordPress core file differs from the official release.',
59
+ hint: 'Reinstall WordPress core, or compare the file with the official release.', location: { file },
60
+ });
61
+ }
62
+ }
63
+ const found = [];
64
+ walk(root, 'wp-admin', found);
65
+ walk(root, 'wp-includes', found);
66
+ for (const file of found) {
67
+ if (Object.hasOwn(sums, file))
68
+ continue;
69
+ out.push({
70
+ rule: 'core.unexpected', severity: 'warning', category: 'security', message: 'This file is not part of WordPress core.',
71
+ hint: 'The core folders hold only core files. Find out what put it there.', location: { file },
72
+ });
73
+ }
74
+ }
75
+ let skipped = 0;
76
+ for (const pkg of packages(target)) {
77
+ if (signal?.aborted)
78
+ break;
79
+ if (pkg.kind !== 'plugin' || !pkg.version)
80
+ continue;
81
+ if (statSync(pkg.path).isFile())
82
+ continue;
83
+ const pr = await getJson(`https://downloads.wordpress.org/plugin-checksums/${pkg.slug}/${pkg.version}.json`, { ttlMs: MONTH, ...(signal ? { signal } : {}) });
84
+ const files = pr.status === 200 ? rec(rec(pr.data)?.files) : undefined;
85
+ if (!files) {
86
+ skipped++;
87
+ continue;
88
+ }
89
+ for (const [rel, info] of Object.entries(files)) {
90
+ const abs = path.join(pkg.path, rel);
91
+ const file = path.relative(root, abs).split(path.sep).join('/');
92
+ if (!existsSync(abs)) {
93
+ out.push({ rule: 'plugin.missing', severity: 'warning', category: 'health', message: `A file of ${pkg.name} ${pkg.version} is missing.`, location: { file } });
94
+ continue;
95
+ }
96
+ const want = rec(info)?.md5;
97
+ const list = Array.isArray(want) ? want : [want];
98
+ if (!list.includes(md5(abs))) {
99
+ out.push({ rule: 'plugin.modified', severity: 'error', category: 'security', message: `This file differs from the wordpress.org release of ${pkg.name} ${pkg.version}.`, location: { file } });
100
+ }
101
+ }
102
+ }
103
+ if (skipped)
104
+ note(`${skipped} ${skipped === 1 ? 'plugin has' : 'plugins have'} no checksums on wordpress.org and ${skipped === 1 ? 'was' : 'were'} not compared.`);
105
+ return out;
106
+ });
107
+ },
108
+ };
@@ -0,0 +1,2 @@
1
+ import type { Engine } from '../types.ts';
2
+ export declare const phpCompat: Engine;
@@ -0,0 +1,26 @@
1
+ import { requiresPhp } from '../php/files.js';
2
+ import { runPhpcs } from '../php/phpcs.js';
3
+ export const phpCompat = {
4
+ id: 'php-compat',
5
+ title: 'PHP compatibility',
6
+ kinds: ['theme', 'plugin'],
7
+ async run({ target, signal, note }) {
8
+ const declared = requiresPhp(target.path);
9
+ const min = declared ?? '7.4';
10
+ note(declared ? `Checking against PHP ${min} and newer.` : 'No "Requires PHP" header found. Checking against PHP 7.4 and newer.');
11
+ const messages = await runPhpcs({
12
+ target,
13
+ standard: 'PHPCompatibilityWP',
14
+ extra: ['--runtime-set', 'testVersion', `${min}-`],
15
+ ...(signal ? { signal } : {}),
16
+ note,
17
+ });
18
+ return messages.map((m) => ({
19
+ rule: m.source,
20
+ severity: m.type === 'ERROR' ? 'error' : 'warning',
21
+ category: 'compatibility',
22
+ message: m.message,
23
+ location: { file: m.file, line: m.line, column: m.column },
24
+ }));
25
+ },
26
+ };
@@ -0,0 +1,6 @@
1
+ import type { Engine } from '../types.ts';
2
+ export declare function parseLint(output: string): {
3
+ message: string;
4
+ line?: number;
5
+ } | undefined;
6
+ export declare const phpLint: Engine;
@@ -0,0 +1,41 @@
1
+ import { statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { exec } from '../exec.js';
4
+ import { phpFiles } from '../php/files.js';
5
+ import { phpBinary, phpVersion } from '../php/php.js';
6
+ export function parseLint(output) {
7
+ const m = /(?:PHP )?(?:Parse|Fatal) error:\s+(.+?) in .+ on line (\d+)/.exec(output);
8
+ return m ? { message: m[1], line: Number(m[2]) } : undefined;
9
+ }
10
+ export const phpLint = {
11
+ id: 'php-lint',
12
+ title: 'PHP syntax',
13
+ kinds: ['theme', 'plugin'],
14
+ async run({ target, signal, note }) {
15
+ note(`Checking syntax with PHP ${await phpVersion()}.`);
16
+ const base = statSync(target.path).isFile() ? path.dirname(target.path) : target.path;
17
+ const files = phpFiles(target.path);
18
+ const findings = [];
19
+ let next = 0;
20
+ const worker = async () => {
21
+ while (next < files.length && !signal?.aborted) {
22
+ const file = files[next++];
23
+ const r = await exec(phpBinary(), ['-d', 'display_errors=1', '-d', 'log_errors=0', '-l', file], { ...(signal ? { signal } : {}) });
24
+ if (r.code === 0)
25
+ continue;
26
+ const out = `${r.stdout}\n${r.stderr}`;
27
+ const parsed = parseLint(out);
28
+ const first = out.split('\n').map((l) => l.trim()).find(Boolean);
29
+ findings.push({
30
+ rule: 'syntax',
31
+ severity: 'error',
32
+ category: 'correctness',
33
+ message: parsed?.message ?? first ?? 'PHP could not parse this file.',
34
+ location: { file: path.relative(base, file).split(path.sep).join('/'), ...(parsed?.line ? { line: parsed.line } : {}) },
35
+ });
36
+ }
37
+ };
38
+ await Promise.all(Array.from({ length: Math.min(8, files.length) }, worker));
39
+ return findings.sort((a, b) => (a.location.file < b.location.file ? -1 : a.location.file > b.location.file ? 1 : 0));
40
+ },
41
+ };
@@ -0,0 +1,11 @@
1
+ import type { Engine, RawFinding } from '../types.ts';
2
+ export declare function neon(opts: {
3
+ tools: string;
4
+ target: string;
5
+ isFile: boolean;
6
+ tmpDir: string;
7
+ vendor?: string;
8
+ exclude: string[];
9
+ }): string;
10
+ export declare function parsePhpstan(json: string, base: string): RawFinding[];
11
+ export declare const phpstan: Engine;
@@ -0,0 +1,102 @@
1
+ import { existsSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { exec } from '../exec.js';
5
+ import { home } from '../home.js';
6
+ import { phpFiles } from '../php/files.js';
7
+ import { phpBinary, phpVersion } from '../php/php.js';
8
+ import { phpTools } from '../php/tools.js';
9
+ const q = (p) => `'${p.replace(/'/g, "''")}'`;
10
+ export function neon(opts) {
11
+ const lines = [
12
+ 'includes:',
13
+ `\t- ${q(`${opts.tools}/vendor/szepeviktor/phpstan-wordpress/extension.neon`)}`,
14
+ 'parameters:',
15
+ '\tlevel: 5',
16
+ '\tpaths:',
17
+ `\t\t- ${q(opts.target)}`,
18
+ `\ttmpDir: ${q(opts.tmpDir)}`,
19
+ ];
20
+ if (opts.exclude.length)
21
+ lines.push('\texcludePaths:', '\t\tanalyse:', ...opts.exclude.map((e) => `\t\t\t- ${q(e)}`));
22
+ if (opts.vendor)
23
+ lines.push('\tscanDirectories:', `\t\t- ${q(opts.vendor)}`);
24
+ return lines.join('\n') + '\n';
25
+ }
26
+ export function parsePhpstan(json, base) {
27
+ let data;
28
+ try {
29
+ data = JSON.parse(json);
30
+ }
31
+ catch {
32
+ throw new Error('PHPStan returned output that is not JSON.');
33
+ }
34
+ if (!data || typeof data.files !== 'object' || data.files === null)
35
+ throw new Error('PHPStan returned output that is not JSON.');
36
+ if (data.errors?.length)
37
+ throw new Error(`PHPStan stopped: ${data.errors[0]}`);
38
+ const out = [];
39
+ for (const [abs, f] of Object.entries(data.files)) {
40
+ const rel = path.relative(base, abs);
41
+ const file = rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? rel.split(path.sep).join('/') : abs;
42
+ for (const m of f.messages ?? []) {
43
+ out.push({
44
+ rule: m.identifier ?? 'phpstan',
45
+ severity: 'warning',
46
+ category: 'correctness',
47
+ message: m.message,
48
+ location: { file, ...(typeof m.line === 'number' ? { line: m.line } : {}) },
49
+ ...(m.tip ? { hint: m.tip.replace(/\s*\n\s*/g, ' ') } : {}),
50
+ });
51
+ }
52
+ }
53
+ return out;
54
+ }
55
+ const isDir = (p) => existsSync(p) && statSync(p).isDirectory();
56
+ export const phpstan = {
57
+ id: 'phpstan',
58
+ title: 'PHPStan',
59
+ kinds: ['theme', 'plugin'],
60
+ async run({ target, signal, note }) {
61
+ await phpVersion();
62
+ const tools = await phpTools(note);
63
+ const isFile = statSync(target.path).isFile();
64
+ const base = isFile ? path.dirname(target.path) : target.path;
65
+ const exclude = isFile ? [] : [path.join(base, 'vendor'), path.join(base, 'node_modules')].filter(isDir);
66
+ const vendor = !isFile && isDir(path.join(base, 'vendor')) ? path.join(base, 'vendor') : undefined;
67
+ if (!isFile && ['phpstan.neon', 'phpstan.neon.dist', 'phpstan.dist.neon'].some((n) => existsSync(path.join(base, n)))) {
68
+ note('The project has its own PHPStan config. wp-shakedown uses its own settings at level 5.');
69
+ }
70
+ const files = phpFiles(target.path);
71
+ // PHPStan stops with an error when it has no file to read. A block theme can have no PHP at all.
72
+ if (files.length === 0)
73
+ return [];
74
+ const cfgDir = mkdtempSync(path.join(os.tmpdir(), 'wps-phpstan-'));
75
+ const analyse = async (broken) => {
76
+ const cfgFile = path.join(cfgDir, 'phpstan.neon');
77
+ writeFileSync(cfgFile, neon({ tools, target: target.path, isFile, tmpDir: path.join(home(), 'cache', 'phpstan'), ...(vendor ? { vendor } : {}), exclude: [...exclude, ...broken] }));
78
+ const r = await exec(phpBinary(), ['-d', 'memory_limit=1G', path.join(tools, 'vendor', 'bin', 'phpstan'), 'analyse', '-c', cfgFile, '--error-format=json', '--no-progress', '--no-interaction', '--memory-limit=1G'], { cwd: base, ...(signal ? { signal } : {}) });
79
+ if (!r.stdout.trim().startsWith('{')) {
80
+ const line = [r.stderr, r.stdout]
81
+ .flatMap((s) => s.split('\n').map((l) => l.trim()))
82
+ .find((l) => l && !l.startsWith('Warning: Module'));
83
+ throw new Error(`PHPStan stopped: ${line ?? 'no output'}`);
84
+ }
85
+ return parsePhpstan(r.stdout, base);
86
+ };
87
+ try {
88
+ const found = await analyse([]);
89
+ // When a file does not parse, PHPStan reports that and nothing else. Run again without those files.
90
+ const broken = [...new Set(found.filter((f) => f.rule === 'phpstan.parse').map((f) => path.join(base, f.location.file)))];
91
+ if (broken.length === 0)
92
+ return found;
93
+ note(`Left out ${broken.length} ${broken.length === 1 ? 'file' : 'files'} that PHP cannot parse. php-lint reports them.`);
94
+ if (broken.length >= files.length)
95
+ return [];
96
+ return (await analyse(broken)).filter((f) => f.rule !== 'phpstan.parse');
97
+ }
98
+ finally {
99
+ rmSync(cfgDir, { recursive: true, force: true });
100
+ }
101
+ },
102
+ };
@@ -0,0 +1,4 @@
1
+ import type { Category, Engine, RawFinding } from '../types.ts';
2
+ export declare function categoriseCss(rule: string): Category;
3
+ export declare function parseStylelint(json: string, base: string): RawFinding[];
4
+ export declare const stylelint: Engine;
@@ -0,0 +1,63 @@
1
+ import path from 'node:path';
2
+ import { exec } from '../exec.js';
3
+ import { isGenerated, sourceFiles } from '../js/files.js';
4
+ import { jsTools } from '../js/tools.js';
5
+ import { chunks, firstLine, posixRelative } from './eslint.js';
6
+ export function categoriseCss(rule) {
7
+ return /(-no-unknown$|-no-invalid|^no-invalid-|no-duplicate-|^block-no-empty$|-no-shorthand-property-overrides$|^string-no-newline$|^no-empty-source$|-no-missing-generic-family-keyword$|^no-irregular-whitespace$)/.test(rule)
8
+ ? 'correctness'
9
+ : 'standards';
10
+ }
11
+ export function parseStylelint(json, base) {
12
+ let data;
13
+ try {
14
+ data = JSON.parse(json);
15
+ }
16
+ catch {
17
+ data = null;
18
+ }
19
+ if (!Array.isArray(data))
20
+ throw new Error('Stylelint returned output that is not JSON.');
21
+ const out = [];
22
+ for (const f of data) {
23
+ for (const w of f.warnings ?? []) {
24
+ const message = w.text.endsWith(` (${w.rule})`) ? w.text.slice(0, -` (${w.rule})`.length) : w.text;
25
+ const location = { file: posixRelative(base, f.source), line: w.line, column: w.column };
26
+ if (w.rule === 'CssSyntaxError') {
27
+ out.push({ rule: 'syntax', severity: 'error', category: 'correctness', message, location });
28
+ continue;
29
+ }
30
+ const category = categoriseCss(w.rule);
31
+ out.push({ rule: w.rule, severity: category === 'standards' ? 'info' : 'warning', category, message, location });
32
+ }
33
+ }
34
+ return out;
35
+ }
36
+ export const stylelint = {
37
+ id: 'stylelint',
38
+ title: 'CSS',
39
+ kinds: ['theme', 'plugin'],
40
+ async run({ target, signal, note }) {
41
+ const files = sourceFiles(target.path, ['.css', '.scss']).filter((f) => !isGenerated(f));
42
+ if (files.length === 0)
43
+ return [];
44
+ const tools = await jsTools(note);
45
+ const out = [];
46
+ for (const chunk of chunks(files, 200)) {
47
+ if (signal?.aborted)
48
+ break;
49
+ const r = await exec(process.execPath, [
50
+ path.join(tools, 'node_modules', 'stylelint', 'bin', 'stylelint.mjs'),
51
+ '--config', path.join(tools, 'stylelint.config.mjs'), '--config-basedir', tools,
52
+ '--formatter', 'json', '--allow-empty-input',
53
+ ...chunk.map((f) => posixRelative(target.path, f)),
54
+ ], { cwd: target.path, ...(signal ? { signal } : {}) });
55
+ // Stylelint prints its JSON to stderr when it finds problems.
56
+ const text = r.stdout.trim() || r.stderr.trim();
57
+ if (!text.startsWith('['))
58
+ throw new Error(`Stylelint stopped: ${firstLine(r.stderr) || firstLine(r.stdout)}`);
59
+ out.push(...parseStylelint(text, target.path));
60
+ }
61
+ return out;
62
+ },
63
+ };
@@ -0,0 +1,4 @@
1
+ import type { Engine } from '../types.ts';
2
+ /** Whole days from a YYYY-MM-DD start of the text to now. Undefined when the text has no date. */
3
+ export declare function daysSince(dateText: string, now: Date): number | undefined;
4
+ export declare const updates: Engine;