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,72 @@
1
+ import { coreVersion, packages, skipOnNetwork } from '../health/install.js';
2
+ import { getJson } from '../net.js';
3
+ import { compareVersions } from '../versions.js';
4
+ const HALF_DAY = 12 * 3600 * 1000;
5
+ const rec = (v) => (v && typeof v === 'object' ? v : undefined);
6
+ /** Whole days from a YYYY-MM-DD start of the text to now. Undefined when the text has no date. */
7
+ export function daysSince(dateText, now) {
8
+ const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(dateText);
9
+ if (!m)
10
+ return undefined;
11
+ return Math.floor((now.getTime() - Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]))) / 86400000);
12
+ }
13
+ export const updates = {
14
+ id: 'updates',
15
+ title: 'Updates',
16
+ kinds: ['install'],
17
+ run({ target, signal }) {
18
+ return skipOnNetwork(async () => {
19
+ const out = [];
20
+ const o = { ttlMs: HALF_DAY, ...(signal ? { signal } : {}) };
21
+ const cv = coreVersion(target.path);
22
+ if (cv) {
23
+ const offers = rec((await getJson('https://api.wordpress.org/core/version-check/1.7/', o)).data)?.offers;
24
+ const latest = rec(Array.isArray(offers) ? offers[0] : undefined)?.version;
25
+ if (typeof latest === 'string' && compareVersions(cv.version, latest) < 0) {
26
+ out.push({
27
+ rule: 'core.outdated', severity: 'warning', category: 'health',
28
+ message: `WordPress ${cv.version} is installed. The current version is ${latest}.`, location: { file: 'wp-includes/version.php' },
29
+ });
30
+ }
31
+ }
32
+ const now = new Date();
33
+ for (const pkg of packages(target)) {
34
+ if (signal?.aborted)
35
+ break;
36
+ if (!pkg.version)
37
+ continue;
38
+ const { name, version, file } = pkg;
39
+ const plugin = pkg.kind === 'plugin';
40
+ const url = plugin
41
+ ? `https://api.wordpress.org/plugins/info/1.2/?action=plugin_information&request%5Bslug%5D=${encodeURIComponent(pkg.slug)}&request%5Bfields%5D%5Bsections%5D=0`
42
+ : `https://api.wordpress.org/themes/info/1.2/?action=theme_information&request%5Bslug%5D=${pkg.slug}`;
43
+ const r = await getJson(url, o);
44
+ const d = rec(r.data);
45
+ if (r.status === 404) {
46
+ if (plugin && d?.error === 'closed') {
47
+ out.push({
48
+ rule: 'plugin.closed', severity: 'warning', category: 'security', message: `wordpress.org closed ${name}.`,
49
+ hint: 'A closed plugin gets no updates. Look for a replacement.', location: { file },
50
+ });
51
+ }
52
+ continue;
53
+ }
54
+ if (typeof d?.version === 'string' && compareVersions(version, d.version) < 0) {
55
+ out.push({
56
+ rule: `${pkg.kind}.outdated`, severity: 'warning', category: 'health',
57
+ message: `${name} ${version} is installed. The current version is ${d.version}.`, location: { file },
58
+ });
59
+ }
60
+ const days = typeof d?.last_updated === 'string' ? daysSince(d.last_updated, now) : undefined;
61
+ if (days !== undefined && days > 730) {
62
+ out.push({
63
+ rule: `${pkg.kind}.abandoned`, severity: 'warning', category: 'health',
64
+ message: `${name} had its last release on ${d.last_updated.slice(0, 10)}.`,
65
+ hint: `A ${pkg.kind} with no release in two years may be abandoned.`, location: { file },
66
+ });
67
+ }
68
+ }
69
+ return out;
70
+ });
71
+ },
72
+ };
@@ -0,0 +1,22 @@
1
+ import type { Engine } from '../types.ts';
2
+ export interface WpvulnMatch {
3
+ title: string;
4
+ cves: string[];
5
+ link?: string;
6
+ fix?: string;
7
+ }
8
+ export declare function wpvulnMatches(data: unknown, version: string): WpvulnMatch[];
9
+ export interface Item {
10
+ type: 'core' | 'plugin' | 'theme';
11
+ slug: string;
12
+ version: string;
13
+ }
14
+ export interface WordfenceMatch {
15
+ title: string;
16
+ cve?: string;
17
+ link?: string;
18
+ fix?: string;
19
+ notice: string;
20
+ }
21
+ export declare function wordfenceMatches(feed: unknown, item: Item): WordfenceMatch[];
22
+ export declare const vulnerabilities: Engine;
@@ -0,0 +1,128 @@
1
+ import { coreVersion, packages, skipOnNetwork } from '../health/install.js';
2
+ import { getJson, Unreachable } from '../net.js';
3
+ import { inRange } from '../versions.js';
4
+ const HALF_DAY = 12 * 3600 * 1000;
5
+ const rec = (v) => (v && typeof v === 'object' ? v : undefined);
6
+ const arr = (v) => (Array.isArray(v) ? v : []);
7
+ const str = (v) => (typeof v === 'string' && v ? v : undefined);
8
+ const decode = (s) => s.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#039;/g, "'").replace(/&amp;/g, '&');
9
+ export function wpvulnMatches(data, version) {
10
+ const out = [];
11
+ for (const raw of arr(rec(data)?.vulnerability)) {
12
+ const v = rec(raw);
13
+ if (!v)
14
+ continue;
15
+ const op = rec(v.operator);
16
+ if (op && !inRange(version, { min: str(op.min_version) ?? null, minInclusive: op.min_operator === 'ge', max: str(op.max_version) ?? null, maxInclusive: op.max_operator === 'le' }))
17
+ continue;
18
+ const sources = arr(v.source).map(rec).filter((s) => !!s);
19
+ const isCve = (s) => String(s.id ?? '').startsWith('CVE-');
20
+ const plain = sources.find((s) => !isCve(s));
21
+ const first = sources.find(isCve) ?? sources[0];
22
+ let fix;
23
+ const max = str(op?.max_version);
24
+ if (String(op?.unfixed) === '1')
25
+ fix = 'No fixed version exists. Remove or replace it.';
26
+ else if (op?.max_operator === 'lt' && max)
27
+ fix = `Update to ${max} or newer.`;
28
+ else if (op?.max_operator === 'le' && max)
29
+ fix = `Update to a version newer than ${max}.`;
30
+ const link = str(first?.link);
31
+ out.push({
32
+ title: decode(str(plain?.name) ?? str(v.name) ?? 'Known vulnerability'),
33
+ cves: sources.filter(isCve).map((s) => String(s.id)),
34
+ ...(link ? { link } : {}),
35
+ ...(fix ? { fix } : {}),
36
+ });
37
+ }
38
+ return out;
39
+ }
40
+ export function wordfenceMatches(feed, item) {
41
+ const out = [];
42
+ for (const raw of Object.values(rec(feed) ?? {})) {
43
+ const r = rec(raw);
44
+ if (!r || r.informational)
45
+ continue;
46
+ for (const sw of arr(r.software).map(rec)) {
47
+ if (!sw || sw.type !== item.type || (item.type !== 'core' && sw.slug !== item.slug))
48
+ continue;
49
+ const hit = Object.values(rec(sw.affected_versions) ?? {}).some((x) => {
50
+ const a = rec(x);
51
+ return !!a && inRange(item.version, { min: str(a.from_version) ?? null, minInclusive: !!a.from_inclusive, max: str(a.to_version) ?? null, maxInclusive: !!a.to_inclusive });
52
+ });
53
+ if (!hit)
54
+ continue;
55
+ const c = rec(r.copyrights);
56
+ const notice = [rec(c?.defiant)?.notice, rec(c?.mitre)?.notice].filter((n) => typeof n === 'string' && !!n).join(' ');
57
+ const link = str(arr(r.references)[0]) ?? str(r.cve_link);
58
+ const cve = str(r.cve);
59
+ const fix = str(sw.remediation);
60
+ out.push({ title: decode(str(r.title) ?? 'Known vulnerability'), ...(cve ? { cve } : {}), ...(link ? { link } : {}), ...(fix ? { fix } : {}), notice });
61
+ break;
62
+ }
63
+ }
64
+ return out;
65
+ }
66
+ export const vulnerabilities = {
67
+ id: 'vulnerabilities',
68
+ title: 'Known vulnerabilities',
69
+ kinds: ['install'],
70
+ run({ target, signal, note }) {
71
+ return skipOnNetwork(async () => {
72
+ const o = { ttlMs: HALF_DAY, ...(signal ? { signal } : {}) };
73
+ const items = [];
74
+ const cv = coreVersion(target.path);
75
+ if (cv)
76
+ items.push({ type: 'core', slug: 'wordpress', version: cv.version, label: 'WordPress', file: 'wp-includes/version.php' });
77
+ let unversioned = 0;
78
+ for (const p of packages(target)) {
79
+ if (p.version)
80
+ items.push({ type: p.kind, slug: p.slug, version: p.version, label: p.name, file: p.file });
81
+ else
82
+ unversioned++;
83
+ }
84
+ if (unversioned)
85
+ note(`${unversioned} ${unversioned === 1 ? 'package has' : 'packages have'} no version header and ${unversioned === 1 ? 'was' : 'were'} not looked up.`);
86
+ let feed;
87
+ const key = process.env.WP_SHAKEDOWN_WORDFENCE_KEY;
88
+ if (key) {
89
+ try {
90
+ const r = await getJson('https://www.wordfence.com/api/intelligence/v3/vulnerabilities/production', { ...o, headers: { Authorization: `Bearer ${key}` } });
91
+ if (r.status !== 200)
92
+ throw new Unreachable('Cannot reach www.wordfence.com.');
93
+ feed = r.data;
94
+ note('Using Wordfence Intelligence next to WPVulnerability.');
95
+ }
96
+ catch (err) {
97
+ if (!(err instanceof Unreachable))
98
+ throw err;
99
+ note(`Wordfence Intelligence was not used: ${err.message}`);
100
+ }
101
+ }
102
+ const out = [];
103
+ for (const it of items) {
104
+ if (signal?.aborted)
105
+ break;
106
+ const base = 'https://www.wpvulnerability.net';
107
+ const url = it.type === 'core' ? `${base}/core/${it.version}/` : `${base}/${it.type}/${it.slug}/`;
108
+ const r = await getJson(url, o);
109
+ const a = r.status === 200 ? wpvulnMatches(rec(r.data)?.data, it.version) : [];
110
+ const add = (title, docs, hint) => out.push({
111
+ rule: 'vulnerability', severity: 'error', category: 'security', message: `${it.label} ${it.version}: ${title}`,
112
+ location: { file: it.file }, ...(docs ? { docs } : {}), ...(hint ? { hint } : {}),
113
+ });
114
+ for (const m of a)
115
+ add(m.title, m.link, m.fix);
116
+ if (feed) {
117
+ const seen = new Set(a.flatMap((m) => m.cves));
118
+ for (const m of wordfenceMatches(feed, it)) {
119
+ if (m.cve && seen.has(m.cve))
120
+ continue;
121
+ add(m.title, m.link, [m.fix, `Source: Wordfence Intelligence. ${m.notice}`.trim()].filter(Boolean).join(' '));
122
+ }
123
+ }
124
+ }
125
+ return out;
126
+ });
127
+ },
128
+ };
@@ -0,0 +1,18 @@
1
+ import type { Engine, Target } from '../types.ts';
2
+ type Kind = 'theme' | 'block';
3
+ export declare function jsonFiles(target: Target): {
4
+ file: string;
5
+ kind: Kind;
6
+ }[];
7
+ export declare function schemaUrl(kind: Kind, declared: unknown): string;
8
+ export declare function loadSchema(url: string): Promise<object>;
9
+ export declare function validate(schema: object, data: unknown): {
10
+ rule: string;
11
+ message: string;
12
+ }[];
13
+ export declare function syntaxFinding(err: unknown): {
14
+ message: string;
15
+ line?: number;
16
+ };
17
+ export declare const wpJson: Engine;
18
+ export {};
@@ -0,0 +1,133 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { Ajv } from 'ajv';
4
+ import { getJson, Unreachable } from '../net.js';
5
+ import { EngineSkipped } from '../types.js';
6
+ export function jsonFiles(target) {
7
+ if (statSync(target.path).isFile())
8
+ return [];
9
+ const out = [];
10
+ const walk = (dir, visit) => {
11
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
12
+ const p = path.join(dir, e.name);
13
+ if (e.isDirectory()) {
14
+ if (e.name !== 'vendor' && e.name !== 'node_modules' && !e.name.startsWith('.'))
15
+ walk(p, visit);
16
+ }
17
+ else if (e.isFile())
18
+ visit(p, e.name);
19
+ }
20
+ };
21
+ if (target.kind === 'theme') {
22
+ const top = path.join(target.path, 'theme.json');
23
+ if (existsSync(top))
24
+ out.push({ file: top, kind: 'theme' });
25
+ const styles = path.join(target.path, 'styles');
26
+ if (existsSync(styles) && statSync(styles).isDirectory()) {
27
+ walk(styles, (p, n) => {
28
+ if (n.endsWith('.json'))
29
+ out.push({ file: p, kind: 'theme' });
30
+ });
31
+ }
32
+ }
33
+ walk(target.path, (p, n) => {
34
+ if (n === 'block.json')
35
+ out.push({ file: p, kind: 'block' });
36
+ });
37
+ return out.sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : 0));
38
+ }
39
+ export function schemaUrl(kind, declared) {
40
+ if (typeof declared === 'string') {
41
+ const m = /^https:\/\/schemas\.wp\.org\/(?:trunk|wp\/\d+\.\d+)\/(theme|block)\.json$/.exec(declared);
42
+ if (m && m[1] === kind)
43
+ return declared;
44
+ }
45
+ return `https://schemas.wp.org/trunk/${kind}.json`;
46
+ }
47
+ const WEEK = 7 * 24 * 3600 * 1000;
48
+ export async function loadSchema(url) {
49
+ const skip = new EngineSkipped(`Cannot download ${url}. The engine needs the schema once and then works offline for a week.`);
50
+ try {
51
+ const r = await getJson(url, { ttlMs: WEEK });
52
+ if (r.status === 200 && r.data && typeof r.data === 'object')
53
+ return r.data;
54
+ }
55
+ catch (err) {
56
+ if (!(err instanceof Unreachable))
57
+ throw err;
58
+ }
59
+ throw skip;
60
+ }
61
+ const ajv = new Ajv({ strict: false, allErrors: true, validateFormats: false });
62
+ const validators = new WeakMap();
63
+ const SKIP = new Set(['if', 'then', 'else', 'anyOf', 'oneOf', 'allOf', 'not']);
64
+ export function validate(schema, data) {
65
+ let v = validators.get(schema);
66
+ if (!v)
67
+ validators.set(schema, (v = ajv.compile(schema)));
68
+ v(data);
69
+ const seen = new Set();
70
+ const out = [];
71
+ for (const e of v.errors ?? []) {
72
+ if (SKIP.has(e.keyword))
73
+ continue;
74
+ // A name that propertyNames rejects also produces errors about the name itself. The propertyNames error says it all.
75
+ if ('propertyName' in e && e.keyword !== 'propertyNames')
76
+ continue;
77
+ const where = e.instancePath || '/';
78
+ let message = `${where}: ${e.message}`;
79
+ // The WordPress schemas reject an unknown name with additionalProperties in some places and with propertyNames in others.
80
+ if (e.keyword === 'additionalProperties')
81
+ message = `${where}: "${e.params.additionalProperty}" is not a known property`;
82
+ if (e.keyword === 'propertyNames')
83
+ message = `${where}: "${e.params.propertyName}" is not a known property`;
84
+ if (e.keyword === 'enum')
85
+ message += `: ${e.params.allowedValues.slice(0, 8).join(', ')}`;
86
+ const rule = `schema.${e.keyword}`;
87
+ const key = `${rule}\n${message}`;
88
+ if (seen.has(key))
89
+ continue;
90
+ seen.add(key);
91
+ out.push({ rule, message });
92
+ }
93
+ return out.slice(0, 50);
94
+ }
95
+ export function syntaxFinding(err) {
96
+ const message = err instanceof Error ? err.message : String(err);
97
+ const m = /\(line (\d+) column \d+\)/.exec(message);
98
+ return { message, ...(m ? { line: Number(m[1]) } : {}) };
99
+ }
100
+ export const wpJson = {
101
+ id: 'wp-json',
102
+ title: 'theme.json and block.json',
103
+ kinds: ['theme', 'plugin'],
104
+ async run({ target, signal }) {
105
+ const files = jsonFiles(target);
106
+ const out = [];
107
+ const schemas = new Map();
108
+ for (const { file, kind } of files) {
109
+ if (signal?.aborted)
110
+ break;
111
+ const rel = path.relative(target.path, file).split(path.sep).join('/');
112
+ let data;
113
+ try {
114
+ data = JSON.parse(readFileSync(file, 'utf8'));
115
+ }
116
+ catch (err) {
117
+ const s = syntaxFinding(err);
118
+ out.push({ rule: 'json.syntax', severity: 'error', category: 'correctness', message: s.message, location: { file: rel, ...(s.line ? { line: s.line } : {}) } });
119
+ continue;
120
+ }
121
+ const url = schemaUrl(kind, data?.$schema);
122
+ let pending = schemas.get(url);
123
+ if (!pending)
124
+ schemas.set(url, (pending = loadSchema(url)));
125
+ const schema = await pending;
126
+ for (const v of validate(schema, data)) {
127
+ // shortcut: no line number. Mapping a JSON path to a line needs a position-aware parser. Add one when people ask where in the file.
128
+ out.push({ rule: v.rule, severity: 'warning', category: 'correctness', message: v.message, location: { file: rel } });
129
+ }
130
+ }
131
+ return out;
132
+ },
133
+ };
@@ -0,0 +1,7 @@
1
+ import type { PhpcsMessage } from '../php/phpcs.ts';
2
+ import type { Category, Engine, RawFinding } from '../types.ts';
3
+ export declare function categorise(source: string): Category;
4
+ export declare function toFinding(m: PhpcsMessage): RawFinding;
5
+ /** The WordPress-Extra rules plus the Plugin Check review rules, as a ruleset file in the tools folder. */
6
+ export declare function pluginRuleset(tools: string): string;
7
+ export declare const wpcs: Engine;
@@ -0,0 +1,60 @@
1
+ import { existsSync, statSync, writeFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { runPhpcs } from '../php/phpcs.js';
4
+ const RULES = [
5
+ [/^PluginCheck\.Security\./, 'security'],
6
+ [/^PluginCheck\.CodeAnalysis\./, 'correctness'],
7
+ [/^WordPress\.PHP\.YodaConditions/, 'standards'],
8
+ [/^WordPress\.Security\./, 'security'],
9
+ [/^WordPress\.DB\.PreparedSQL/, 'security'],
10
+ [/^WordPress\.WP\.I18n\./, 'i18n'],
11
+ [/^WordPress\.DB\.(DirectDatabaseQuery|SlowDBQuery)/, 'performance'],
12
+ [/^WordPress\.(WP|PHP|DB|DateTime|CodeAnalysis|Utils)\./, 'correctness'],
13
+ [/^(Generic\.PHP\.(Syntax|BacktickOperator|DiscourageGoto|ForbiddenFunctions)|Squiz\.PHP\.(Eval|DiscouragedFunctions)|Generic\.CodeAnalysis\.|Generic\.PHP\.(DisallowShortOpenTag|DisallowAlternativePHPTags)|Generic\.Files\.ByteOrderMark)/, 'correctness'],
14
+ ];
15
+ export function categorise(source) {
16
+ return RULES.find(([re]) => re.test(source))?.[1] ?? 'standards';
17
+ }
18
+ export function toFinding(m) {
19
+ const category = categorise(m.source);
20
+ const error = m.type === 'ERROR';
21
+ const severity = category === 'standards' ? (error ? 'warning' : 'info') : error ? 'error' : 'warning';
22
+ return {
23
+ rule: m.source,
24
+ severity,
25
+ category,
26
+ message: m.message,
27
+ location: { file: m.file, line: m.line, column: m.column },
28
+ ...(m.fixable ? { hint: 'phpcbf can fix this.' } : {}),
29
+ };
30
+ }
31
+ const PLUGIN_RULESET = `<?xml version="1.0"?>
32
+ <ruleset name="wp-shakedown plugin">
33
+ <rule ref="WordPress-Extra"/>
34
+ <rule ref="./vendor/plugin-check/phpcs-sniffs/phpcs-rulesets/plugin-review.xml"/>
35
+ </ruleset>
36
+ `;
37
+ /** The WordPress-Extra rules plus the Plugin Check review rules, as a ruleset file in the tools folder. */
38
+ export function pluginRuleset(tools) {
39
+ const file = path.join(tools, 'wp-shakedown-plugin.xml');
40
+ if (!existsSync(file))
41
+ writeFileSync(file, PLUGIN_RULESET);
42
+ return file;
43
+ }
44
+ const RULESETS = ['.phpcs.xml', 'phpcs.xml', '.phpcs.xml.dist', 'phpcs.xml.dist'];
45
+ export const wpcs = {
46
+ id: 'wpcs',
47
+ title: 'WordPress Coding Standards',
48
+ kinds: ['theme', 'plugin'],
49
+ async run({ target, signal, note }) {
50
+ let standard = target.kind === 'plugin' ? pluginRuleset : 'WordPress-Extra';
51
+ if (statSync(target.path).isDirectory()) {
52
+ const name = RULESETS.find((n) => existsSync(path.join(target.path, n)));
53
+ if (name) {
54
+ standard = path.join(target.path, name);
55
+ note(`Using the project ruleset ${name}.`);
56
+ }
57
+ }
58
+ return (await runPhpcs({ target, standard, ...(signal ? { signal } : {}), note })).map(toFinding);
59
+ },
60
+ };
package/dist/exec.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ export interface ExecResult {
2
+ code: number;
3
+ stdout: string;
4
+ stderr: string;
5
+ }
6
+ /** Thrown when the command does not exist. */
7
+ export declare class NotFound extends Error {
8
+ }
9
+ export declare function exec(cmd: string, args: string[], opts?: {
10
+ cwd?: string;
11
+ signal?: AbortSignal;
12
+ }): Promise<ExecResult>;
package/dist/exec.js ADDED
@@ -0,0 +1,19 @@
1
+ import { spawn } from 'node:child_process';
2
+ /** Thrown when the command does not exist. */
3
+ export class NotFound extends Error {
4
+ }
5
+ export function exec(cmd, args, opts = {}) {
6
+ return new Promise((resolve, reject) => {
7
+ const child = spawn(cmd, args, {
8
+ ...(opts.cwd ? { cwd: opts.cwd } : {}),
9
+ ...(opts.signal ? { signal: opts.signal } : {}),
10
+ stdio: ['ignore', 'pipe', 'pipe'],
11
+ });
12
+ let stdout = '';
13
+ let stderr = '';
14
+ child.stdout.setEncoding('utf8').on('data', (d) => (stdout += d));
15
+ child.stderr.setEncoding('utf8').on('data', (d) => (stderr += d));
16
+ child.on('error', (err) => reject(err.code === 'ENOENT' ? new NotFound(`${cmd} was not found.`) : err));
17
+ child.on('close', (code) => resolve({ code: code ?? 1, stdout, stderr }));
18
+ });
19
+ }
@@ -0,0 +1,10 @@
1
+ import type { Location } from './types.ts';
2
+ export declare function assignIds<T extends {
3
+ engine: string;
4
+ unit?: string;
5
+ rule: string;
6
+ message: string;
7
+ location: Location;
8
+ }>(items: T[]): (T & {
9
+ id: string;
10
+ })[];
@@ -0,0 +1,29 @@
1
+ import { createHash } from 'node:crypto';
2
+ const sha = (s) => createHash('sha256').update(s).digest('hex').slice(0, 12);
3
+ export function assignIds(items) {
4
+ const groups = new Map();
5
+ items.forEach((f, i) => {
6
+ const key = JSON.stringify([
7
+ f.engine,
8
+ f.rule,
9
+ f.unit ?? '',
10
+ f.location.file ?? f.location.url ?? '',
11
+ f.location.selector ?? '',
12
+ f.message,
13
+ ]);
14
+ const g = groups.get(key);
15
+ if (g)
16
+ g.push(i);
17
+ else
18
+ groups.set(key, [i]);
19
+ });
20
+ const ids = [];
21
+ for (const [key, idx] of groups) {
22
+ idx.sort((a, b) => (items[a].location.line ?? 0) - (items[b].location.line ?? 0) ||
23
+ (items[a].location.column ?? 0) - (items[b].location.column ?? 0));
24
+ idx.forEach((i, n) => {
25
+ ids[i] = n === 0 ? sha(key) : sha(`${key}#${n + 1}`);
26
+ });
27
+ }
28
+ return items.map((f, i) => ({ ...f, id: ids[i] }));
29
+ }
@@ -0,0 +1,16 @@
1
+ import type { Target } from '../types.ts';
2
+ export declare function coreVersion(root: string): {
3
+ version: string;
4
+ locale: string;
5
+ } | undefined;
6
+ export interface Package {
7
+ kind: 'plugin' | 'theme';
8
+ slug: string;
9
+ name: string;
10
+ version?: string;
11
+ path: string;
12
+ file: string;
13
+ }
14
+ export declare function packages(target: Target): Package[];
15
+ /** Turns a lost connection into a skipped engine. */
16
+ export declare function skipOnNetwork<T>(work: () => Promise<T>): Promise<T>;
@@ -0,0 +1,68 @@
1
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { Unreachable } from '../net.js';
4
+ import { EngineSkipped } from '../types.js';
5
+ export function coreVersion(root) {
6
+ let text;
7
+ try {
8
+ text = readFileSync(path.join(root, 'wp-includes', 'version.php'), 'utf8');
9
+ }
10
+ catch {
11
+ return undefined;
12
+ }
13
+ const version = /\$wp_version\s*=\s*'([^']+)'/.exec(text)?.[1];
14
+ if (!version)
15
+ return undefined;
16
+ return { version, locale: /\$wp_local_package\s*=\s*'([^']+)'/.exec(text)?.[1] ?? 'en_US' };
17
+ }
18
+ const PLUGIN_HEAD = /^[ \t\/*#@]*Plugin Name:/im;
19
+ const VERSION_HEAD = /^[ \t\/*#@]*Version:\s*(.+)$/im;
20
+ function head(file) {
21
+ try {
22
+ return readFileSync(file).subarray(0, 8192).toString('utf8');
23
+ }
24
+ catch {
25
+ return '';
26
+ }
27
+ }
28
+ function pluginMain(dir) {
29
+ let names;
30
+ try {
31
+ names = readdirSync(dir).filter((n) => n.endsWith('.php')).sort();
32
+ }
33
+ catch {
34
+ return undefined;
35
+ }
36
+ for (const n of names) {
37
+ const f = path.join(dir, n);
38
+ if (statSync(f, { throwIfNoEntry: false })?.isFile() && PLUGIN_HEAD.test(head(f)))
39
+ return f;
40
+ }
41
+ return undefined;
42
+ }
43
+ export function packages(target) {
44
+ return target.units.map((u) => {
45
+ const isFile = statSync(u.path, { throwIfNoEntry: false })?.isFile() ?? false;
46
+ const main = u.kind === 'theme' ? path.join(u.path, 'style.css') : isFile ? u.path : pluginMain(u.path);
47
+ const version = main ? VERSION_HEAD.exec(head(main))?.[1]?.replace(/\*\/\s*$/, '').trim() || undefined : undefined;
48
+ return {
49
+ kind: u.kind,
50
+ slug: path.basename(u.path).replace(/\.php$/, ''),
51
+ name: u.name,
52
+ ...(version ? { version } : {}),
53
+ path: u.path,
54
+ file: path.relative(target.path, main ?? u.path).split(path.sep).join('/'),
55
+ };
56
+ });
57
+ }
58
+ /** Turns a lost connection into a skipped engine. */
59
+ export async function skipOnNetwork(work) {
60
+ try {
61
+ return await work();
62
+ }
63
+ catch (err) {
64
+ if (err instanceof Unreachable)
65
+ throw new EngineSkipped(`${err.message} This engine needs the network.`);
66
+ throw err;
67
+ }
68
+ }
package/dist/home.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** The folder where wp-shakedown keeps reports and downloaded tools. */
2
+ export declare function home(): string;
package/dist/home.js ADDED
@@ -0,0 +1,6 @@
1
+ import os from 'node:os';
2
+ import path from 'node:path';
3
+ /** The folder where wp-shakedown keeps reports and downloaded tools. */
4
+ export function home() {
5
+ return process.env.WP_SHAKEDOWN_HOME || path.join(os.homedir(), '.wp-shakedown');
6
+ }
@@ -0,0 +1,38 @@
1
+ export type * from './types.ts';
2
+ export { SEVERITIES, EngineSkipped } from './types.ts';
3
+ export { detectTarget, unitLabel } from './target.ts';
4
+ export { run, exitCode } from './runner.ts';
5
+ export type { RunOptions } from './runner.ts';
6
+ export { runSession } from './session.ts';
7
+ export type { SessionOptions, SessionResult } from './session.ts';
8
+ export { startMcp } from './mcp/server.ts';
9
+ export type { McpOptions } from './mcp/server.ts';
10
+ export { tools, selectFindings } from './mcp/tools.ts';
11
+ export type { Tool, ToolContext } from './mcp/tools.ts';
12
+ export { startUi } from './ui/server.ts';
13
+ export type { UiServer } from './ui/server.ts';
14
+ export { loadBaseline, applyBaseline } from './baseline.ts';
15
+ export { diffRuns } from './diff.ts';
16
+ export { assignIds } from './fingerprint.ts';
17
+ export { toMarkdown } from './report/markdown.ts';
18
+ export { toJson } from './report/json.ts';
19
+ export { toSarif } from './report/sarif.ts';
20
+ export { toHtml } from './report/html.ts';
21
+ export { assertReportDir, defaultReportDir, readPreviousRun, writeReports } from './report/write.ts';
22
+ export { engines } from './engines/index.ts';
23
+ export { home } from './home.ts';
24
+ export { phpLint } from './engines/php-lint.ts';
25
+ export { wpcs } from './engines/wpcs.ts';
26
+ export { phpCompat } from './engines/php-compat.ts';
27
+ export { phpstan } from './engines/phpstan.ts';
28
+ export { wpJson } from './engines/wp-json.ts';
29
+ export { eslint } from './engines/eslint.ts';
30
+ export { stylelint } from './engines/stylelint.ts';
31
+ export { integrity } from './engines/integrity.ts';
32
+ export { updates } from './engines/updates.ts';
33
+ export { vulnerabilities } from './engines/vulnerabilities.ts';
34
+ export { config } from './engines/config.ts';
35
+ export { compareVersions } from './versions.ts';
36
+ export { getJson } from './net.ts';
37
+ export { progressLine } from './progress.ts';
38
+ export { VERSION } from './version.ts';