@volumio/plugin-sdk 0.0.0-stage → 0.3.1

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 (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +125 -2
  3. package/bin/volumio-plugin.js +190 -0
  4. package/package.json +31 -4
  5. package/registry/functions.json +93 -0
  6. package/registry/g2-baseline.json +485 -0
  7. package/schema/manifest.schema.json +95 -0
  8. package/src/audit.js +46 -0
  9. package/src/check.js +114 -0
  10. package/src/deploy.js +183 -0
  11. package/src/fromV1.js +54 -0
  12. package/src/g2/baseline.js +31 -0
  13. package/src/g2/gitleaks.toml +4 -0
  14. package/src/g2/index.js +18 -0
  15. package/src/g2/js.js +63 -0
  16. package/src/g2/rule.js +94 -0
  17. package/src/g2/secrets.js +85 -0
  18. package/src/g2/shell.js +145 -0
  19. package/src/index.js +3 -0
  20. package/src/init.js +60 -0
  21. package/src/licence.js +88 -0
  22. package/src/manifest.js +36 -0
  23. package/src/package.js +170 -0
  24. package/src/sign.js +59 -0
  25. package/src/socketio.js +76 -0
  26. package/templates/generic/AGENTS.md +60 -0
  27. package/templates/generic/CLAUDE.md +2 -0
  28. package/templates/generic/LICENSE +21 -0
  29. package/templates/generic/README.md +13 -0
  30. package/templates/generic/UIConfig.json +23 -0
  31. package/templates/generic/VOLUMIO_API.md +91 -0
  32. package/templates/generic/config.json +3 -0
  33. package/templates/generic/gitignore +2 -0
  34. package/templates/generic/i18n/strings_en.json +8 -0
  35. package/templates/generic/index.js +81 -0
  36. package/templates/generic/install.sh +4 -0
  37. package/templates/generic/package.json +17 -0
  38. package/templates/generic/test/plugin.test.js +24 -0
  39. package/templates/generic/test/volumio.js +29 -0
  40. package/templates/generic/uninstall.sh +4 -0
  41. package/templates/generic/volumio-plugin.json +13 -0
  42. package/templates/music_service/UIConfig.json +23 -0
  43. package/templates/music_service/catalog.json +4 -0
  44. package/templates/music_service/config.json +3 -0
  45. package/templates/music_service/i18n/strings_en.json +8 -0
  46. package/templates/music_service/index.js +135 -0
  47. package/templates/music_service/test/music.test.js +52 -0
  48. package/templates/music_service/test/plugin.test.js +29 -0
  49. package/templates/music_service/volumio-plugin.json +13 -0
package/src/check.js ADDED
@@ -0,0 +1,114 @@
1
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import semver from 'semver';
4
+ import { validateManifest } from './manifest.js';
5
+ import { fromV1 } from './fromV1.js';
6
+ import { g2, BASELINE } from './g2/index.js';
7
+
8
+ export const REGISTRY = JSON.parse(readFileSync(new URL('../registry/functions.json', import.meta.url), 'utf8')).map((f) => f.id);
9
+
10
+ /** @typedef {{ rule: string, severity: 'error' | 'warning' | 'todo', message: string, fix?: string, path?: string }} Finding */
11
+
12
+ const finding = (severity) => (rule, message, fix, path) => ({ rule, severity, message, ...(fix && { fix }), ...(path && { path }) });
13
+ const error = finding('error');
14
+ const warning = finding('warning');
15
+
16
+ const readJson = (file) => {
17
+ try {
18
+ return { value: JSON.parse(readFileSync(file, 'utf8')) };
19
+ } catch (e) {
20
+ return { error: e instanceof Error ? e.message : String(e) };
21
+ }
22
+ };
23
+
24
+ /** Reads the manifest: volumio-plugin.json, else package.json through the v1 shim. */
25
+ export const load = (dir) => {
26
+ const v2File = join(dir, 'volumio-plugin.json');
27
+ const pkgFile = join(dir, 'package.json');
28
+ const pkg = existsSync(pkgFile) ? readJson(pkgFile) : { value: {} };
29
+ if (pkg.error) return { failure: error('G1.json', `package.json is not valid JSON: ${pkg.error}`) };
30
+ if (existsSync(v2File)) {
31
+ const manifest = readJson(v2File);
32
+ if (manifest.error) return { failure: error('G1.json', `volumio-plugin.json is not valid JSON: ${manifest.error}`) };
33
+ return { source: 'v2', manifest: manifest.value, pkg: pkg.value, todo: [], dropped: [] };
34
+ }
35
+ if (!existsSync(pkgFile)) {
36
+ return { failure: error('G1.manifest', 'No volumio-plugin.json or package.json in this folder', 'Run the command from the plugin root') };
37
+ }
38
+ return { source: 'v1', pkg: pkg.value, ...fromV1(pkg.value) };
39
+ };
40
+
41
+ const SCHEMA_FIXES = {
42
+ '/id': 'Use 2-64 letters, digits and underscores; no hyphens, the crypter rejects them',
43
+ };
44
+
45
+ // Published before the id pattern: a new id would orphan the installed copies, so theirs is only a warning.
46
+ const LEGACY_IDS = new Set(['gpio-buttons', 'volumio-stream-watchdog']);
47
+
48
+ const schemaFindings = (manifest, todo) =>
49
+ validateManifest(manifest)
50
+ .filter((e) => !todo.includes(e.path.slice(1)))
51
+ .map((e) => (e.path === '/id' && LEGACY_IDS.has(manifest.id) ? warning : error)('G1.schema', `${e.path.slice(1) || 'manifest'} ${e.message}`, SCHEMA_FIXES[e.path], e.path));
52
+
53
+ const ruleFindings = ({ manifest }, functions) => {
54
+ const findings = [];
55
+ if (manifest.function !== undefined && !functions.includes(manifest.function)) {
56
+ findings.push(error('G1.function', `function "${manifest.function}" is not in the registry`, 'Pick a registry function, or ask a moderator for a new one in your proposal'));
57
+ }
58
+ const range = manifest.engines?.volumio;
59
+ if (typeof range === 'string' && semver.validRange(range) === null) {
60
+ findings.push(error('G1.engines', `engines.volumio "${range}" is not a semver range`, 'Use a range such as ">=4.0.0 <5.0.0"'));
61
+ }
62
+ return findings;
63
+ };
64
+
65
+ // The source may keep main and i18n in a build folder (TypeScript); the built v2 package may not.
66
+ // v1 plugins run unencrypted from the store, so for them it is only a warning.
67
+ const builtFindings = (dir, { pkg, source }) => {
68
+ const report = source === 'v1' ? warning : error;
69
+ return [
70
+ pkg.main !== undefined && !['index.js', './index.js'].includes(pkg.main) &&
71
+ report('G1.main', `package.json main is "${pkg.main}"`, 'The crypter needs main = index.js at the package root'),
72
+ !existsSync(join(dir, 'i18n', 'strings_en.json')) && report('G1.file.i18n', 'i18n/strings_en.json is missing', 'Add the English strings file'),
73
+ ].filter(Boolean);
74
+ };
75
+
76
+ // v2: package generates what Volumio reads from package.json, so the source must not set it.
77
+ const GENERATED = ['name', 'version', 'volumio_info'];
78
+ const generatedFindings = ({ source, pkg }) =>
79
+ source !== 'v2' ? [] : GENERATED.filter((k) => pkg[k] !== undefined).map((k) =>
80
+ error('G1.package-json', `package.json sets ${k}, which is generated from volumio-plugin.json`, `Remove ${k} from package.json`));
81
+
82
+ const fileFindings = (dir, { source }) => {
83
+ const names = readdirSync(dir);
84
+ const has = (re) => names.some((n) => re.test(n));
85
+ // v1 plugins already state a licence in package.json; the file is required from v2 on.
86
+ const missingLicense = source === 'v1' ? warning : error;
87
+ return [
88
+ !has(/^readme/i) && error('G1.file.readme', 'README is missing', 'Add a README.md that says what the plugin does and how to set it up'),
89
+ !has(/^licen[sc]e(\.(md|txt))?$/i) && missingLicense('G1.file.license', 'LICENSE is missing', 'Add a LICENSE file matching the license field'),
90
+ ].filter(Boolean);
91
+ };
92
+
93
+ /**
94
+ * Gate G1 on one plugin folder.
95
+ * @param {string} dir
96
+ * @param {{ functions?: string[], built?: boolean, baseline?: Record<string, Record<string, number>> }} [options]
97
+ * built: dir is the package CI built, not the source; baseline: G2 known violations per plugin id
98
+ * @returns {{ dir: string, source?: 'v1' | 'v2', id?: string, version?: string, findings: Finding[], dropped?: string[] }}
99
+ */
100
+ export function check(dir, { functions = REGISTRY, built = false, baseline = BASELINE } = {}) {
101
+ const loaded = load(dir);
102
+ if (loaded.failure) return { dir, findings: [loaded.failure] };
103
+ const findings = [
104
+ ...schemaFindings(loaded.manifest, loaded.todo),
105
+ ...ruleFindings(loaded, functions),
106
+ ...(built ? builtFindings(dir, loaded) : generatedFindings(loaded)),
107
+ ...fileFindings(dir, loaded),
108
+ ...g2(dir, { id: loaded.manifest.id, source: loaded.source, apt: Array.isArray(loaded.manifest.system?.apt) ? loaded.manifest.system.apt : [] }, baseline),
109
+ ...(loaded.todo.length
110
+ ? [{ rule: 'G1.v2-fields', severity: 'todo', message: `v1 plugin: add ${loaded.todo.join(' and ')} in volumio-plugin.json to move to v2` }]
111
+ : []),
112
+ ];
113
+ return { dir, source: loaded.source, id: loaded.manifest.id, version: loaded.manifest.version, findings, ...(loaded.source === 'v1' && { dropped: loaded.dropped }) };
114
+ }
package/src/deploy.js ADDED
@@ -0,0 +1,183 @@
1
+ // `volumio-plugin deploy`: installs a plugin on a Volumio device on the local network, starts it,
2
+ // and returns what the device logged meanwhile. It talks to the backend as the web UI does: no SSH.
3
+ import { randomBytes } from 'node:crypto';
4
+ import { createSocket } from 'node:dgram';
5
+ import { createReadStream, statSync } from 'node:fs';
6
+ import { createServer } from 'node:http';
7
+ import { setTimeout as sleep } from 'node:timers/promises';
8
+ import { connect } from './socketio.js';
9
+
10
+ const TIMEOUTS = {
11
+ answer: 30000,
12
+ // install.sh may apt-get install packages.
13
+ install: 10 * 60000,
14
+ // At boot Volumio stops waiting for a plugin's onStart after 30 seconds.
15
+ start: 35000,
16
+ reboot: 5 * 60000,
17
+ };
18
+ // The device comes back from a reboot without telling anyone: ask again at this pace.
19
+ const RETRY_MS = 3000;
20
+ // journalctl hands a line to the live log a moment after the plugin writes it.
21
+ const LOG_GRACE_MS = 2000;
22
+ const LIVE_LOG = { endpoint: 'system_controller/system', method: 'enableLiveLog' };
23
+
24
+ /** Resolves with the data of the first `event` that `accept` takes; rejects after `timeout`. */
25
+ export const waitFor = (socket, event, accept = () => true, timeout = TIMEOUTS.answer) =>
26
+ new Promise((resolve, reject) => {
27
+ const timer = setTimeout(() => {
28
+ socket.off(event, listener);
29
+ reject(new Error(`No ${event} from the device within ${timeout / 1000}s`));
30
+ }, timeout);
31
+ const listener = (data) => {
32
+ if (!accept(data)) return;
33
+ clearTimeout(timer);
34
+ socket.off(event, listener);
35
+ resolve(data);
36
+ };
37
+ socket.on(event, listener);
38
+ });
39
+
40
+ const ask = (socket, [emit, data], [event, accept, timeout]) => {
41
+ const answer = waitFor(socket, event, accept, timeout);
42
+ socket.emit(emit, data);
43
+ return answer;
44
+ };
45
+
46
+ const listed = (list, { id, type }) => (list ?? []).find((p) => p.name === id && p.category === type);
47
+ const installedPlugin = (socket, plugin) => ask(socket, ['getInstalledPlugins'], ['pushInstalledPlugins']).then((list) => listed(list, plugin));
48
+ const plain = (html = '') => html.replace(/<br\s*\/?>/g, '\n').trim();
49
+
50
+ /** The address of this machine on the interface that reaches host. */
51
+ export const localAddressFor = (host) =>
52
+ new Promise((resolve, reject) => {
53
+ const udp = createSocket('udp4');
54
+ udp.once('error', (error) => {
55
+ udp.close();
56
+ reject(error);
57
+ });
58
+ // UDP connect sends nothing: it only picks the route.
59
+ udp.connect(80, host.replace(/:\d+$/, ''), () => {
60
+ const { address } = udp.address();
61
+ udp.close();
62
+ resolve(address);
63
+ });
64
+ });
65
+
66
+ /** Serves one file at an unguessable URL on address, until close(). */
67
+ export const serveFile = (file, address) =>
68
+ new Promise((resolve, reject) => {
69
+ const path = `/${randomBytes(16).toString('hex')}.zip`;
70
+ const server = createServer((req, res) => {
71
+ if (req.method !== 'GET' || req.url !== path) {
72
+ res.writeHead(404).end();
73
+ return;
74
+ }
75
+ res.writeHead(200, { 'content-type': 'application/zip', 'content-length': statSync(file).size });
76
+ createReadStream(file).pipe(res);
77
+ });
78
+ server.once('error', reject);
79
+ server.listen(0, address, () => {
80
+ resolve({ url: `http://${address}:${server.address().port}${path}`, close: () => server.close() });
81
+ });
82
+ });
83
+
84
+ /**
85
+ * Installs the zip at url, or updates the plugin when the device already has it.
86
+ * @returns {Promise<{ updated: boolean }>}
87
+ */
88
+ export async function install(socket, plugin, url, timeouts = TIMEOUTS) {
89
+ const updated = Boolean(await installedPlugin(socket, plugin));
90
+ const request = updated
91
+ ? ['updatePlugin', { url, category: plugin.type, name: plugin.id }]
92
+ // confirm: the backend would otherwise ask the person at the device's screen first.
93
+ : ['installPlugin', { url, confirm: true }];
94
+ const status = await ask(socket, request, ['installPluginStatus', (s) => s.progress === 100 || s.progress === 0, timeouts.install]);
95
+ if (status.progress === 0) throw new Error(`The device could not install ${plugin.id}: ${plain(status.message)}\n${plain(status.advancedLog)}`);
96
+ return { updated };
97
+ }
98
+
99
+ /** Reboots the device and reconnects once its backend answers again. */
100
+ export async function reboot(socket, host, plugin, { connectTo = connect, timeouts = TIMEOUTS, retry = RETRY_MS } = {}) {
101
+ await ask(socket, ['reboot'], ['disconnect', () => true, timeouts.reboot]);
102
+ const deadline = Date.now() + timeouts.reboot;
103
+ let back;
104
+ for (;;) {
105
+ back = await connectTo(host).catch(() => undefined);
106
+ if (back && (await installedPlugin(back, plugin).then(() => true, () => false))) break;
107
+ back?.close();
108
+ if (Date.now() > deadline) throw new Error(`${host} did not come back within ${timeouts.reboot / 1000}s`);
109
+ await sleep(retry);
110
+ }
111
+ // The backend answers before it has started every plugin. Let the boot start this one, or fail
112
+ // to, before deploy restarts it: a plugin that fails in onStart never shows as running.
113
+ const startBy = Date.now() + timeouts.start;
114
+ for (;;) {
115
+ const found = await installedPlugin(back, plugin);
116
+ if (!found?.enabled || found.active || Date.now() > startBy) return back;
117
+ await sleep(retry);
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Starts the plugin, or stops and starts it again, with the device's live log on.
123
+ * @returns {Promise<{ started: boolean, log: string }>}
124
+ */
125
+ export async function startWithLog(socket, plugin, { restart, timeouts = TIMEOUTS, grace = LOG_GRACE_MS }) {
126
+ const lines = [];
127
+ const collect = ({ message }) => lines.push(message);
128
+ socket.on('LLogProgress', collect);
129
+ await ask(socket, ['callMethod', { ...LIVE_LOG, data: 'true' }], ['LLogOpen']);
130
+ const target = { category: plugin.type, name: plugin.id };
131
+ try {
132
+ if (restart) await ask(socket, ['pluginManager', { action: 'disable', ...target }], ['pushInstalledPlugins', (l) => !listed(l, plugin)?.active]);
133
+ // The backend answers only when onStart resolves: a plugin that fails to start times out here.
134
+ const started = await ask(socket, ['pluginManager', { action: 'enable', ...target }], ['pushInstalledPlugins', (l) => listed(l, plugin)?.active, timeouts.start])
135
+ .then(() => true, () => false);
136
+ await sleep(grace);
137
+ return { started, log: lines.join('') };
138
+ } finally {
139
+ socket.off('LLogProgress', collect);
140
+ socket.emit('callMethod', { ...LIVE_LOG, data: 'false' });
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Installs the zip of plugin on host, reboots the device and starts the plugin. Volumio keeps
146
+ * running the code of a plugin it loaded once until its backend restarts, through updates and
147
+ * even an uninstall: only a reboot makes sure the new code runs.
148
+ * @param {string} host
149
+ * @param {{ id: string, type: string }} plugin
150
+ * @param {string} zip
151
+ * @param {{ connectTo?: Function, progress?: (line: string) => void }} [options]
152
+ * @returns {Promise<{ updated: boolean, started: boolean, log: string }>}
153
+ */
154
+ export async function deploy(host, plugin, zip, { connectTo = connect, progress = () => {} } = {}) {
155
+ let socket = await connectTo(host);
156
+ let server;
157
+ try {
158
+ server = await serveFile(zip, await localAddressFor(host));
159
+ progress(`Installing ${plugin.id} on ${host}`);
160
+ const { updated } = await install(socket, plugin, server.url).finally(() => server.close());
161
+ progress(`Rebooting ${host} to load the new code: this takes a minute or two`);
162
+ socket = await reboot(socket, host, plugin, { connectTo });
163
+ progress(`Starting ${plugin.id}`);
164
+ const running = Boolean((await installedPlugin(socket, plugin))?.active);
165
+ return { updated, ...(await startWithLog(socket, plugin, { restart: running })) };
166
+ } finally {
167
+ server?.close();
168
+ socket.close();
169
+ }
170
+ }
171
+
172
+ /** Writes the device's live log until `until` settles. */
173
+ export async function followLog(host, write, until, { connectTo = connect } = {}) {
174
+ const socket = await connectTo(host);
175
+ socket.on('LLogProgress', ({ message }) => write(message));
176
+ socket.emit('callMethod', { ...LIVE_LOG, data: 'true' });
177
+ try {
178
+ await until;
179
+ } finally {
180
+ socket.emit('callMethod', { ...LIVE_LOG, data: 'false' });
181
+ socket.close();
182
+ }
183
+ }
package/src/fromV1.js ADDED
@@ -0,0 +1,54 @@
1
+ // volumio_info field -> v2 field. Every other volumio_info field is reported as dropped.
2
+ const RENAMED = { prettyName: 'title', details: 'description', icon: 'icon', changelog: 'changelog', boot_priority: 'bootPriority' };
3
+ const MAPPED = new Set(['plugin_type', 'architectures', ...Object.keys(RENAMED)]);
4
+
5
+ // Fields v1 cannot provide: the author adds them when moving to v2.
6
+ const V2_ONLY = ['function', 'permissions'];
7
+
8
+ const defined = (obj) => Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined));
9
+
10
+ /**
11
+ * Reads a v1 package.json as a v2 manifest, without inventing missing values.
12
+ * @param {{ name?: string, version?: string, license?: string, engines?: { volumio?: string }, volumio_info?: Record<string, unknown> }} pkg
13
+ * @returns {{ manifest: Record<string, unknown>, todo: string[], dropped: string[] }}
14
+ */
15
+ export function fromV1(pkg) {
16
+ const info = pkg.volumio_info ?? {};
17
+ const manifest = defined({
18
+ id: pkg.name,
19
+ version: pkg.version,
20
+ type: info.plugin_type,
21
+ ...Object.fromEntries(Object.entries(RENAMED).map(([from, to]) => [to, info[from]])),
22
+ engines: defined({ volumio: pkg.engines?.volumio, api: '1' }),
23
+ arch: Array.isArray(info.architectures) ? [...info.architectures] : info.architectures,
24
+ license: pkg.license,
25
+ });
26
+ return {
27
+ manifest,
28
+ todo: [...V2_ONLY],
29
+ dropped: Object.keys(info).filter((k) => !MAPPED.has(k)),
30
+ };
31
+ }
32
+
33
+ /**
34
+ * The package.json Volumio reads today, from a v2 manifest: the manifest is the single source,
35
+ * so name, version, description, licence, engines.volumio and volumio_info are overwritten.
36
+ * @param {Record<string, any>} manifest
37
+ * @param {Record<string, any>} pkg the plugin's own package.json (main, dependencies, engines.node)
38
+ */
39
+ export function toV1(manifest, pkg = {}) {
40
+ return {
41
+ ...pkg,
42
+ name: manifest.id,
43
+ version: manifest.version,
44
+ description: manifest.description,
45
+ license: manifest.license,
46
+ engines: { ...pkg.engines, volumio: manifest.engines?.volumio },
47
+ volumio_info: defined({
48
+ plugin_type: manifest.type,
49
+ ...Object.fromEntries(Object.entries(RENAMED).map(([v1, v2]) => [v1, manifest[v2]])),
50
+ architectures: manifest.arch,
51
+ os: ['bookworm'],
52
+ }),
53
+ };
54
+ }
@@ -0,0 +1,31 @@
1
+ const keyOf = (f) => `${f.rule}|${f.file}`;
2
+
3
+ // Local accumulator: a plugin can have thousands of findings, copying per step would be quadratic.
4
+ const groupByKey = (findings) => {
5
+ const groups = new Map();
6
+ for (const f of findings) {
7
+ const group = groups.get(keyOf(f));
8
+ if (group) group.push(f);
9
+ else groups.set(keyOf(f), [f]);
10
+ }
11
+ return groups;
12
+ };
13
+
14
+ /** @param {Array<{ rule: string, file: string }>} findings @returns {Record<string, number>} */
15
+ export const countByKey = (findings) =>
16
+ Object.fromEntries([...groupByKey(findings)].map(([key, group]) => [key, group.length]));
17
+
18
+ /**
19
+ * Known violations (within the plugin's baseline count for that rule and file) become one warning;
20
+ * any rule and file over its count blocks. With no baseline, v1 plugins are in their grace period.
21
+ * @param {Array<{ rule: string, file: string, severity: string, message: string }>} findings
22
+ * @param {Record<string, number> | undefined} baseline
23
+ * @param {'v1' | 'v2' | undefined} source
24
+ */
25
+ export function applyBaseline(findings, baseline, source) {
26
+ if (!baseline) return findings.map((f) => ({ ...f, severity: source === 'v1' ? 'warning' : 'error' }));
27
+ return [...groupByKey(findings)].flatMap(([key, group]) =>
28
+ group.length <= (baseline[key] ?? 0)
29
+ ? [{ rule: group[0].rule, severity: 'warning', file: group[0].file, message: `${group.length} known (baseline)` }]
30
+ : group.map((f) => ({ ...f, severity: 'error' })));
31
+ }
@@ -0,0 +1,4 @@
1
+ # The gitleaks config G2 runs with: the default rules. Passed with --config, so a plugin's own
2
+ # .gitleaks.toml is never read.
3
+ [extend]
4
+ useDefault = true
@@ -0,0 +1,18 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { lintDir } from './js.js';
3
+ import { shellDir } from './shell.js';
4
+ import { secretFindings } from './secrets.js';
5
+ import { applyBaseline } from './baseline.js';
6
+
7
+ export const BASELINE = JSON.parse(readFileSync(new URL('../../registry/g2-baseline.json', import.meta.url), 'utf8'));
8
+
9
+ /** Every G2 finding of a plugin, before the baseline is applied; apt: the packages in system.apt. */
10
+ export const rawG2 = (dir, apt) => [...lintDir(dir), ...shellDir(dir, apt), ...secretFindings(dir)];
11
+
12
+ /**
13
+ * Gate G2 with the plugin's baseline applied.
14
+ * @param {string} dir
15
+ * @param {{ id?: string, source?: 'v1' | 'v2', apt?: string[] }} plugin
16
+ * @param {Record<string, Record<string, number>>} [baseline]
17
+ */
18
+ export const g2 = (dir, { id, source, apt }, baseline = BASELINE) => applyBaseline(rawG2(dir, apt), id && Object.hasOwn(baseline, id) ? baseline[id] : undefined, source);
package/src/g2/js.js ADDED
@@ -0,0 +1,63 @@
1
+ import { readFileSync, readdirSync } from 'node:fs';
2
+ import { extname, join } from 'node:path';
3
+ import { Linter } from 'eslint';
4
+ import { rule } from './rule.js';
5
+
6
+ const FIXES = {
7
+ 'G2.js.sync-exec': 'Use execFile or spawn and wait on the result asynchronously',
8
+ 'G2.js.shell': 'Pass the command and its arguments as a list to execFile or spawn, without shell: true',
9
+ 'G2.js.process-exit': 'Throw or return an error and let Volumio handle it',
10
+ 'G2.js.global-handler': 'Handle errors where they happen',
11
+ 'G2.js.command-router-override': 'Ask for a capability instead of replacing a core method',
12
+ 'G2.js.console-log': 'Log through this.logger',
13
+ 'G2.js.parse': 'Fix the syntax error',
14
+ };
15
+
16
+ const JS = new Set(['.js', '.cjs', '.mjs']);
17
+ const SKIP_DIRS = new Set(['node_modules', '.git', 'test', 'tests', '__tests__']);
18
+ const SKIP_FILES = /\.(test|spec|min)\.[cm]?js$/;
19
+
20
+ const linter = new Linter();
21
+ // noInlineConfig: a comment in the plugin must not switch a gate rule off.
22
+ const config = (sourceType) => ({
23
+ languageOptions: { ecmaVersion: 'latest', sourceType },
24
+ linterOptions: { noInlineConfig: true, reportUnusedDisableDirectives: 'off' },
25
+ plugins: { volumio: { rules: { g2: rule } } },
26
+ rules: { 'volumio/g2': 'error' },
27
+ });
28
+
29
+ const verify = (code, file) => {
30
+ const first = extname(file) === '.mjs' ? 'module' : 'commonjs';
31
+ const messages = linter.verify(code, config(first), { filename: file });
32
+ // A .js file may still be an ES module; try again before calling it broken.
33
+ if (first === 'commonjs' && messages.some((m) => m.fatal)) {
34
+ const asModule = linter.verify(code, config('module'), { filename: file });
35
+ if (!asModule.some((m) => m.fatal)) return asModule;
36
+ }
37
+ return messages;
38
+ };
39
+
40
+ /**
41
+ * G2 JavaScript checks on one source text.
42
+ * @param {string} code
43
+ * @param {string} file path relative to the plugin root, used in findings
44
+ * @returns {Array<{ rule: string, severity: 'error', file: string, line: number, message: string, fix: string }>}
45
+ */
46
+ export function lintSource(code, file) {
47
+ return verify(code, file).filter((m) => m.fatal || m.ruleId === 'volumio/g2').map((m) => {
48
+ const id = m.fatal ? 'G2.js.parse' : m.messageId;
49
+ return { rule: id, severity: 'error', file, line: m.line, message: m.message, fix: FIXES[id] };
50
+ });
51
+ }
52
+
53
+ const sourceFiles = (root, rel = '') =>
54
+ readdirSync(join(root, rel), { withFileTypes: true }).flatMap((entry) => {
55
+ const path = rel ? `${rel}/${entry.name}` : entry.name;
56
+ if (entry.isDirectory()) return SKIP_DIRS.has(entry.name) ? [] : sourceFiles(root, path);
57
+ return JS.has(extname(entry.name)) && !SKIP_FILES.test(entry.name) ? [path] : [];
58
+ });
59
+
60
+ /** G2 JavaScript checks on every source file of a plugin, tests and node_modules excluded. */
61
+ export function lintDir(dir) {
62
+ return sourceFiles(dir).flatMap((file) => lintSource(readFileSync(join(dir, file), 'utf8'), file));
63
+ }
package/src/g2/rule.js ADDED
@@ -0,0 +1,94 @@
1
+ // One ESLint rule for every G2 JavaScript check; each messageId is the G2 rule id.
2
+ const CHILD_PROCESS = new Set(['child_process', 'node:child_process']);
3
+ const SYNC = new Set(['execSync', 'execFileSync', 'spawnSync']);
4
+ const SHELL_OPTION = new Set(['spawn', 'execFile']);
5
+ const GLOBAL_EVENTS = new Set(['uncaughtException', 'unhandledRejection']);
6
+ const LISTEN = new Set(['on', 'once', 'addListener', 'prependListener']);
7
+ const ROUTER = new Set(['commandRouter', 'coreCommand']);
8
+
9
+ const keyOf = (node) => (node.computed ? node.property.value : node.property.name);
10
+ const isMember = (node, object, props) =>
11
+ node?.type === 'MemberExpression' && node.object.type === 'Identifier' && node.object.name === object && props.has(keyOf(node));
12
+ const isRequireOfChildProcess = (node) =>
13
+ node?.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === 'require' &&
14
+ node.arguments[0]?.type === 'Literal' && CHILD_PROCESS.has(node.arguments[0].value);
15
+ const keyName = (key) => key.name ?? key.value;
16
+ // shell: true or a shell path runs one; only a literal false (or empty path) is known not to.
17
+ const hasShellOption = (args) =>
18
+ args.some((a) => a.type === 'ObjectExpression' &&
19
+ a.properties.some((p) => p.type === 'Property' && keyName(p.key) === 'shell' && (p.value.type !== 'Literal' || Boolean(p.value.value))));
20
+
21
+ export const rule = {
22
+ meta: {
23
+ type: 'problem',
24
+ messages: {
25
+ 'G2.js.sync-exec': '{{name}} blocks the backend while the command runs',
26
+ 'G2.js.shell': '{{name}} runs the command through a shell',
27
+ 'G2.js.process-exit': 'process.{{name}} stops the whole backend',
28
+ 'G2.js.global-handler': "process.{{name}}('{{event}}') changes how the whole backend fails",
29
+ 'G2.js.command-router-override': 'replacing commandRouter.{{name}} changes Volumio for every plugin',
30
+ 'G2.js.console-log': 'console.log bypasses the Volumio logger',
31
+ },
32
+ },
33
+ create(context) {
34
+ const { sourceCode } = context;
35
+ // Scope analysis runs before traversal: a name resolves to its declaration wherever it is written.
36
+ const variableOf = (identifier) => {
37
+ for (let scope = sourceCode.getScope(identifier); scope; scope = scope.upper) {
38
+ const variable = scope.set.get(identifier.name);
39
+ if (variable) return variable;
40
+ }
41
+ return undefined;
42
+ };
43
+ // What one declaration binds a name to: the child_process module ({ module }), one of its functions ({ fn }), or neither.
44
+ const bindingOfDef = (def, identifier) => {
45
+ if (def.type === 'ImportBinding') {
46
+ if (!CHILD_PROCESS.has(def.parent.source.value)) return undefined;
47
+ return def.node.type === 'ImportSpecifier' ? { fn: keyName(def.node.imported) } : { module: true };
48
+ }
49
+ if (def.type !== 'Variable') return undefined;
50
+ const { id, init } = def.node;
51
+ if (isRequireOfChildProcess(init)) {
52
+ if (id.type === 'Identifier') return { module: true };
53
+ const prop = id.type === 'ObjectPattern' &&
54
+ id.properties.find((p) => p.type === 'Property' && p.value.type === 'Identifier' && p.value.name === identifier.name);
55
+ return prop ? { fn: keyName(prop.key) } : undefined;
56
+ }
57
+ if (init?.type === 'MemberExpression' && isRequireOfChildProcess(init.object) && id.type === 'Identifier') return { fn: keyOf(init) };
58
+ return undefined;
59
+ };
60
+ // A name declared more than once (var) has one definition per declaration.
61
+ const bindingOf = (identifier) =>
62
+ (variableOf(identifier)?.defs ?? []).map((def) => bindingOfDef(def, identifier)).find(Boolean);
63
+ const childProcessFunction = (callee) => {
64
+ if (callee.type === 'Identifier') return bindingOf(callee)?.fn;
65
+ if (callee.type !== 'MemberExpression') return undefined;
66
+ if (isRequireOfChildProcess(callee.object)) return keyOf(callee);
67
+ return callee.object.type === 'Identifier' && bindingOf(callee.object)?.module ? keyOf(callee) : undefined;
68
+ };
69
+ const report = (node, messageId, data) => context.report({ node, messageId, data });
70
+ // A file with a shebang is an executable run as its own process, not a module the backend loads.
71
+ const ownProcess = context.sourceCode.text.startsWith('#!');
72
+
73
+ return {
74
+ CallExpression(node) {
75
+ const name = childProcessFunction(node.callee);
76
+ if (SYNC.has(name)) return report(node, 'G2.js.sync-exec', { name });
77
+ if (name === 'exec' || (SHELL_OPTION.has(name) && hasShellOption(node.arguments))) return report(node, 'G2.js.shell', { name });
78
+ if (!ownProcess && isMember(node.callee, 'process', new Set(['exit', 'abort']))) return report(node, 'G2.js.process-exit', { name: keyOf(node.callee) });
79
+ const event = node.arguments[0]?.value;
80
+ if (!ownProcess && isMember(node.callee, 'process', LISTEN) && GLOBAL_EVENTS.has(event)) {
81
+ return report(node, 'G2.js.global-handler', { name: keyOf(node.callee), event });
82
+ }
83
+ if (isMember(node.callee, 'console', new Set(['log']))) return report(node, 'G2.js.console-log');
84
+ return undefined;
85
+ },
86
+ AssignmentExpression(node) {
87
+ const target = node.left;
88
+ if (target.type === 'MemberExpression' && target.object.type === 'MemberExpression' && ROUTER.has(keyOf(target.object))) {
89
+ report(node, 'G2.js.command-router-override', { name: keyOf(target) });
90
+ }
91
+ },
92
+ };
93
+ },
94
+ };
@@ -0,0 +1,85 @@
1
+ import { cpSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { tmpdir } from 'node:os';
4
+ import { basename, join, relative } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+
7
+ // Credentials with a recognisable shape. Anything shipped in a plugin is public, whatever the repository's visibility.
8
+ const PATTERNS = [
9
+ { name: 'a private key', test: /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----/ },
10
+ { name: 'an AWS access key', test: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/ },
11
+ { name: 'a GitHub token', test: /\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{60,})/ },
12
+ { name: 'a Slack token', test: /\bxox[abprs]-[A-Za-z0-9-]{10,}/ },
13
+ { name: 'a Google API key', test: /\bAIza[0-9A-Za-z_-]{35}/ },
14
+ { name: 'a Stripe live key', test: /\b[rs]k_live_[0-9A-Za-z]{20,}/ },
15
+ ];
16
+ const SKIPPED_DIRS = new Set(['node_modules', '.git']);
17
+ // ponytail: larger files are skipped, not streamed; stream them if a plugin ever ships one.
18
+ const MAX_BYTES = 10 * 1024 * 1024;
19
+ const FIX = 'Remove it and revoke it: it is already public. Read secrets from the plugin settings or the device at runtime';
20
+ // The gitleaks of the build container (scripts/install-tools.sh): the baseline is recorded with it.
21
+ export const GITLEAKS_VERSION = '8.30.1';
22
+ const GITLEAKS_CONFIG = fileURLToPath(new URL('./gitleaks.toml', import.meta.url));
23
+
24
+ const files = (root, rel = '') =>
25
+ readdirSync(join(root, rel), { withFileTypes: true })
26
+ .sort((a, b) => a.name.localeCompare(b.name))
27
+ .flatMap((e) => {
28
+ const path = rel ? `${rel}/${e.name}` : e.name;
29
+ if (e.isDirectory()) return SKIPPED_DIRS.has(e.name) ? [] : files(root, path);
30
+ return e.isFile() ? [path] : [];
31
+ });
32
+
33
+ /** Credentials in the plugin's own files. The finding names the kind of secret, never the secret. */
34
+ const patternFindings = (dir) =>
35
+ files(dir).flatMap((file) => {
36
+ if (statSync(join(dir, file)).size > MAX_BYTES) return [];
37
+ const bytes = readFileSync(join(dir, file));
38
+ if (bytes.includes(0)) return [];
39
+ return bytes.toString('utf8').split('\n').flatMap((text, i) =>
40
+ PATTERNS.filter((p) => p.test.test(text)).map((p) => ({
41
+ rule: 'G2.secret',
42
+ severity: 'error',
43
+ file,
44
+ line: i + 1,
45
+ message: `${p.name} in the package`,
46
+ fix: FIX,
47
+ })));
48
+ });
49
+
50
+ /** @returns {string | undefined} the installed gitleaks version */
51
+ export const gitleaksVersion = () => spawnSync('gitleaks', ['version'], { encoding: 'utf8' }).stdout?.trim() || undefined;
52
+
53
+ // gitleaks is optional on a laptop and required in CI, which installs it. The plugin cannot switch it
54
+ // off: our --config, gitleaks:allow ignored, and it scans a copy without the .gitleaksignore it would read.
55
+ const gitleaksFindings = (dir) => {
56
+ const work = mkdtempSync(join(tmpdir(), 'g2gl-'));
57
+ try {
58
+ const copy = join(work, 'plugin');
59
+ cpSync(dir, copy, { recursive: true, filter: (p) => !SKIPPED_DIRS.has(basename(p)) && basename(p) !== '.gitleaksignore' });
60
+ const report = join(work, 'report.json');
61
+ const run = spawnSync('gitleaks', ['dir', copy, '--config', GITLEAKS_CONFIG, '--gitleaks-ignore-path', work,
62
+ '--ignore-gitleaks-allow', '--redact', '--no-banner', '--max-target-megabytes', '10', '--exit-code', '0',
63
+ '--report-format', 'json', '--report-path', report], { cwd: work, encoding: 'utf8' });
64
+ if (run.error?.code === 'ENOENT') return [];
65
+ if (run.error || run.status !== 0) throw new Error(`gitleaks failed: ${run.error?.message ?? run.stderr}`);
66
+ // gitleaks scans files in parallel: sorted, so the baseline is the same on every run.
67
+ return JSON.parse(readFileSync(report, 'utf8')).map((leak) => ({
68
+ rule: `G2.secret.${leak.RuleID}`,
69
+ severity: 'error',
70
+ file: relative(copy, leak.File),
71
+ line: leak.StartLine,
72
+ message: `${leak.RuleID} (gitleaks) in the package`,
73
+ fix: FIX,
74
+ })).toSorted((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
75
+ } finally {
76
+ rmSync(work, { recursive: true, force: true });
77
+ }
78
+ };
79
+
80
+ /** G2: the built-in patterns, plus gitleaks on the lines they did not flag. */
81
+ export function secretFindings(dir) {
82
+ const own = patternFindings(dir);
83
+ const flagged = new Set(own.map((f) => `${f.file}:${f.line}`));
84
+ return [...own, ...gitleaksFindings(dir).filter((f) => !flagged.has(`${f.file}:${f.line}`))];
85
+ }