@volumio/plugin-sdk 0.0.0-stage → 0.3.2

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 (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +118 -2
  3. package/bin/volumio-plugin.js +158 -0
  4. package/package.json +37 -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/socketio.js +76 -0
  25. package/templates/generic/AGENTS.md +60 -0
  26. package/templates/generic/CLAUDE.md +2 -0
  27. package/templates/generic/LICENSE +21 -0
  28. package/templates/generic/README.md +13 -0
  29. package/templates/generic/UIConfig.json +23 -0
  30. package/templates/generic/VOLUMIO_API.md +91 -0
  31. package/templates/generic/config.json +3 -0
  32. package/templates/generic/gitignore +2 -0
  33. package/templates/generic/i18n/strings_en.json +8 -0
  34. package/templates/generic/index.js +81 -0
  35. package/templates/generic/install.sh +4 -0
  36. package/templates/generic/package.json +17 -0
  37. package/templates/generic/test/plugin.test.js +24 -0
  38. package/templates/generic/test/volumio.js +29 -0
  39. package/templates/generic/uninstall.sh +4 -0
  40. package/templates/generic/volumio-plugin.json +13 -0
  41. package/templates/music_service/UIConfig.json +23 -0
  42. package/templates/music_service/catalog.json +4 -0
  43. package/templates/music_service/config.json +3 -0
  44. package/templates/music_service/i18n/strings_en.json +8 -0
  45. package/templates/music_service/index.js +135 -0
  46. package/templates/music_service/test/music.test.js +52 -0
  47. package/templates/music_service/test/plugin.test.js +29 -0
  48. package/templates/music_service/volumio-plugin.json +13 -0
@@ -0,0 +1,145 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { join } from 'node:path';
4
+
5
+ const SET_E = /^\s*set\s+(-[a-zA-Z]*e|-o\s+errexit)/m;
6
+ const HAS_CHECKSUM = /\bsha(256|512)sum\b/;
7
+ // The ShellCheck of Debian Bookworm, as in the build container: the baseline is recorded with it.
8
+ export const SHELLCHECK_VERSION = '0.9.0';
9
+
10
+ // ponytail: line heuristics, not a shell parser; parse with shfmt's parser if evasions keep showing up.
11
+ // The line before its comment: a # that starts a word, outside quotes.
12
+ const CODE = /^(?:'[^']*'|"(?:[^"\\]|\\.)*"|\\.|[^'"\\#]|(?<=\S)#|['"\\])*/;
13
+ // The commands on a line and the separators between them, quotes kept whole.
14
+ const PIECES = /(?:'[^']*'|"(?:[^"\\]|\\.)*"|\\.|[^;&|'"\\]|['"\\])+|[;&|]+/g;
15
+ // Quoted text with no expansion or command substitution in it: echo and printf only print it.
16
+ const QUOTED = /'[^']*'|"(?:[^"\\$`]|\\.)*"/g;
17
+ const PRINTS = /^\s*(sudo\s+)?(echo|printf|logger)\b/;
18
+ const RUNS_TEXT = /\|\s*(sudo\s+)?(ba|da|z)?sh\b|\beval\b/;
19
+ /** The code on a line: no comment, and no text that a print command only prints. */
20
+ const codeOf = (line) => {
21
+ const code = line.match(CODE)[0];
22
+ if (RUNS_TEXT.test(code)) return code;
23
+ return (code.match(PIECES) ?? []).map((piece) => (PRINTS.test(piece) ? piece.replace(QUOTED, "''") : piece)).join('');
24
+ };
25
+
26
+ // Volumio runs install.sh with sh, dash on Debian: the shebang is ignored.
27
+ const LINE_RULES = [
28
+ { rule: 'G2.shell.pipefail', test: /\bpipefail\b/, message: 'pipefail stops install.sh: Volumio runs it with sh (dash), which has no pipefail', fix: 'Use set -eu' },
29
+ { rule: 'G2.shell.or-true', test: /\|\|\s*(true|:)\s*($|[;&|)])/, message: '|| true hides a failure', fix: 'Let the command fail, or handle the failure explicitly' },
30
+ {
31
+ rule: 'G2.shell.package-manager',
32
+ test: /\bdpkg\s+(-i|--install)\b|\b(npm|yarn|pnpm)\s+(i|install|add|ci)\b|\bpip3?\s+install\b/,
33
+ message: 'install.sh runs a package manager',
34
+ fix: 'Ship npm dependencies inside the package; install Debian packages with apt-get, declared in system.apt',
35
+ },
36
+ // On the raw line: a quoted sudoers path is still written.
37
+ { rule: 'G2.shell.sudoers', raw: true, test: /\/etc\/sudoers/, message: 'install.sh writes sudoers rules', fix: 'Ask for the capability you need instead' },
38
+ ];
39
+
40
+ // apt-get install is allowed for the packages the manifest declares in system.apt.
41
+ // ponytail: words split on spaces with quotes dropped, not a shell parser.
42
+ const APT_COMMAND = /\b(?:apt-get|apt|aptitude)\s([^;&|)]*)/g;
43
+ const APT_ON = /\b(?:apt-get|apt|aptitude)\b/;
44
+ const APT_NAME = /^[a-z0-9][a-z0-9+.-]+$/;
45
+ // Options that take the next word as their value, and redirections whose target may be the next word.
46
+ const WITH_VALUE = /^(-[oct]|--(option|config-file|target-release|default-release)|\d*[<>]+&?)$/;
47
+ const REDIRECT = /^\d*[<>]/;
48
+
49
+ /** The operands of one apt command when its subcommand is install. */
50
+ const installOperands = (args) => {
51
+ const words = args.trim().split(/\s+/).filter(Boolean);
52
+ const operands = [];
53
+ for (let i = 0; i < words.length; i++) {
54
+ if (WITH_VALUE.test(words[i])) i++;
55
+ else if (!words[i].startsWith('-') && !REDIRECT.test(words[i])) operands.push(words[i]);
56
+ }
57
+ return operands[0] === 'install' ? operands.slice(1) : undefined;
58
+ };
59
+
60
+ const aptFindings = (command, apt) => {
61
+ const installs = [...command.matchAll(APT_COMMAND)].map(([, args]) => installOperands(args)).filter(Boolean);
62
+ if (!installs.length) return [];
63
+ // An install that names nothing (apt-get install -f) installs what apt picks: '' never passes.
64
+ const operands = installs.flatMap((o) => (o.length ? o : ['']));
65
+ // An expansion can split into other packages: literal words only, their quotes dropped.
66
+ const literal = operands.map((o) => (/[$`]/.test(o) ? '' : o.replace(/["']/g, '')));
67
+ // A version, architecture or release after the name: pkg=1.2, pkg:arm64, pkg/bookworm-backports.
68
+ const names = literal.map((o) => o.split(/[=:/]/)[0]);
69
+ if (!names.every((n) => APT_NAME.test(n))) {
70
+ return [{ message: 'install.sh installs APT packages it does not name', fix: 'Name each package in the apt-get install line, as declared in system.apt' }];
71
+ }
72
+ const undeclared = [...new Set(names)].filter((n) => !apt.includes(n));
73
+ return undeclared.length
74
+ ? [{ message: `install.sh installs ${undeclared.join(', ')}, not declared in system.apt`, fix: `Add ${undeclared.join(', ')} to system.apt in volumio-plugin.json` }]
75
+ : [];
76
+ };
77
+ // One finding per rule and line, messages joined: the baseline counts lines.
78
+ const onePerRule = (found) => [...found.reduce((byRule, f) => {
79
+ const seen = byRule.get(f.rule);
80
+ return byRule.set(f.rule, seen ? { ...seen, message: `${seen.message}; ${f.message}`, fix: `${seen.fix}; ${f.fix}` } : f);
81
+ }, new Map()).values()];
82
+ // The command a line starts, with the lines it continues on (a trailing backslash).
83
+ const continued = (code, i) => {
84
+ let text = code[i];
85
+ for (let j = i + 1; /\\\s*$/.test(text) && j < code.length; j++) text = text.replace(/\\\s*$/, ' ') + code[j];
86
+ return text.replace(/\\\s*$/, '');
87
+ };
88
+
89
+ const DOWNLOAD = { rule: 'G2.shell.download', test: /\b(wget|curl)\b/, message: 'a download with no checksum check', fix: 'Verify the file with sha256sum -c before using it' };
90
+
91
+ /**
92
+ * G2 rules on the text of install.sh.
93
+ * @param {string} script
94
+ * @param {string} file
95
+ * @param {string[]} [apt] the packages the manifest declares in system.apt
96
+ */
97
+ export function shellFindings(script, file, apt = []) {
98
+ const lines = script.split('\n');
99
+ const code = lines.map(codeOf);
100
+ const rules = code.some((c) => HAS_CHECKSUM.test(c)) ? LINE_RULES : [...LINE_RULES, DOWNLOAD];
101
+ const finding = (r, line) => ({ rule: r.rule, severity: 'error', file, line, message: r.message, fix: r.fix });
102
+ const missingSetE = !SET_E.test(script)
103
+ ? [{ rule: 'G2.shell.set-e', severity: 'error', file, line: 1, message: 'install.sh does not stop on the first error', fix: 'Add set -eu at the top. A -e on the shebang line does not count: Volumio runs install.sh with sh' }]
104
+ : [];
105
+ const perLine = lines.flatMap((text, i) => onePerRule([
106
+ ...rules.filter((r) => r.test.test(r.raw ? text.match(CODE)[0] : code[i])).map((r) => finding(r, i + 1)),
107
+ // On the line apt-get is on, not on a line it continues from.
108
+ ...(APT_ON.test(code[i]) ? aptFindings(continued(code, i), apt) : []).map((f) => finding({ rule: 'G2.shell.package-manager', ...f }, i + 1)),
109
+ ]));
110
+ return [...missingSetE, ...perLine];
111
+ }
112
+
113
+ /** @returns {string | undefined} the installed ShellCheck version */
114
+ export const shellcheckVersion = () => spawnSync('shellcheck', ['--version'], { encoding: 'utf8' }).stdout?.match(/version:\s*(\S+)/)?.[1];
115
+
116
+ // Line numbers are kept: each directive becomes an empty comment.
117
+ const DIRECTIVE = /^([ \t]*)#[ \t]*shellcheck\b.*$/gm;
118
+
119
+ // ShellCheck is optional on a laptop and required in CI, which installs it. The plugin cannot
120
+ // switch checks off: no .shellcheckrc (--norc), no '# shellcheck disable=' directives. Checked as
121
+ // dash, the shell Volumio runs install.sh with, whatever the shebang says.
122
+ const shellcheck = (script, file) => {
123
+ const run = spawnSync('shellcheck', ['--norc', '--shell=dash', '-f', 'json1', '-S', 'warning', '-'], { input: script.replace(DIRECTIVE, '$1#'), encoding: 'utf8' });
124
+ if (run.error || !run.stdout) return [];
125
+ return JSON.parse(run.stdout).comments.map((c) => ({
126
+ rule: `G2.shellcheck.SC${c.code}`,
127
+ severity: 'error',
128
+ file,
129
+ line: c.line,
130
+ message: c.message,
131
+ fix: `https://www.shellcheck.net/wiki/SC${c.code}`,
132
+ }));
133
+ };
134
+
135
+ /**
136
+ * G2 shell checks on a plugin's install.sh, if it has one.
137
+ * @param {string} dir
138
+ * @param {string[]} [apt] the packages the manifest declares in system.apt
139
+ */
140
+ export function shellDir(dir, apt) {
141
+ const path = join(dir, 'install.sh');
142
+ if (!existsSync(path)) return [];
143
+ const script = readFileSync(path, 'utf8');
144
+ return [...shellFindings(script, 'install.sh', apt), ...shellcheck(script, 'install.sh')];
145
+ }
package/src/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { validateManifest, schema } from './manifest.js';
2
+ export { fromV1 } from './fromV1.js';
3
+ export { check } from './check.js';
package/src/init.js ADDED
@@ -0,0 +1,60 @@
1
+ // `volumio-plugin init`: a new plugin from a template, ready to pass every check.
2
+ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { validateManifest } from './manifest.js';
6
+ import { REGISTRY } from './check.js';
7
+ import { files } from './package.js';
8
+
9
+ const TEMPLATES = new URL('../templates/', import.meta.url);
10
+ // generic, plus a template per plugin type that needs its own code, copied over generic.
11
+ export const TEMPLATE_NAMES = ['generic', 'music_service'];
12
+
13
+ // "my_radio" -> "MyRadio", "80s_radio" -> "Plugin80sRadio": the class name in index.js.
14
+ const classNameOf = (id) => {
15
+ const name = id.split('_').filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1)).join('');
16
+ return /^[A-Za-z]/.test(name) ? name : `Plugin${name}`;
17
+ };
18
+
19
+ /**
20
+ * Writes a new plugin into dir, which must not exist or be empty.
21
+ * @param {string} dir
22
+ * @param {{ id: string, type: string, function: string, title: string, description: string, author?: string, template?: string }} options
23
+ * @returns {string[]} the files written, relative to dir
24
+ */
25
+ export function initPlugin(dir, { id, type, function: fn, title, description, author, template = TEMPLATE_NAMES.includes(type) ? type : 'generic' }) {
26
+ if (!TEMPLATE_NAMES.includes(template)) throw new Error(`Unknown template "${template}": ${TEMPLATE_NAMES.join(', ')}`);
27
+ if (existsSync(dir) && readdirSync(dir).length) throw new Error(`${dir} is not empty`);
28
+ const values = {
29
+ id, type, function: fn, title, description,
30
+ author: author || `The ${title} authors`,
31
+ className: classNameOf(id),
32
+ year: String(new Date().getUTCFullYear()),
33
+ };
34
+ // The manifest is the template's, filled in: reject bad values before writing anything.
35
+ const source = (name) => fileURLToPath(new URL(`${name}/`, TEMPLATES));
36
+ const own = join(source(template), 'volumio-plugin.json');
37
+ const manifest = JSON.parse(fill(readFileSync(existsSync(own) ? own : join(source('generic'), 'volumio-plugin.json'), 'utf8'), values, true));
38
+ const errors = validateManifest(manifest);
39
+ if (errors.length) throw new Error(errors.map((e) => `${e.path.slice(1) || 'manifest'} ${e.message}`).join('\n'));
40
+ if (!REGISTRY.includes(fn)) throw new Error(`function "${fn}" is not an id from registry/functions.json`);
41
+
42
+ mkdirSync(dir, { recursive: true });
43
+ cpSync(source('generic'), dir, { recursive: true });
44
+ if (template !== 'generic') cpSync(source(template), dir, { recursive: true });
45
+ // npm drops .gitignore from published packages, so the template keeps it without the dot.
46
+ renameSync(join(dir, 'gitignore'), join(dir, '.gitignore'));
47
+ const written = files(dir);
48
+ for (const file of written) {
49
+ const path = join(dir, file);
50
+ writeFileSync(path, fill(readFileSync(path, 'utf8'), values, file.endsWith('.json')));
51
+ }
52
+ return written.sort();
53
+ }
54
+
55
+ // {{name}} -> value; inside JSON the value is escaped as a JSON string.
56
+ const fill = (text, values, json) =>
57
+ text.replace(/\{\{(\w+)\}\}/g, (match, name) => {
58
+ if (!(name in values)) return match;
59
+ return json ? JSON.stringify(values[name]).slice(1, -1) : values[name];
60
+ });
package/src/licence.js ADDED
@@ -0,0 +1,88 @@
1
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+
4
+ const PERMISSIVE = new Set(['MIT', 'MIT-0', 'ISC', 'BSD-2-Clause', 'BSD-3-Clause', '0BSD', 'Apache-2.0', 'MPL-2.0', 'Zlib', 'CC0-1.0', 'Unlicense', 'BlueOak-1.0.0']);
5
+ // Non-SPDX spellings such as GPLV3 are still GPL.
6
+ const COPYLEFT = /^(A|L)?GPL/i;
7
+ const RANK = { permissive: 0, unknown: 1, copyleft: 2, missing: 3 };
8
+
9
+ const ofId = (id) => (PERMISSIVE.has(id) ? 'permissive' : COPYLEFT.test(id) ? 'copyleft' : 'unknown');
10
+ const best = (classes) => classes.toSorted((a, b) => RANK[a] - RANK[b])[0];
11
+ const worst = (classes) => classes.toSorted((a, b) => RANK[b] - RANK[a])[0];
12
+
13
+ /**
14
+ * Classifies an SPDX expression (or a legacy { type } object): an OR takes the best choice, an AND the worst.
15
+ * @returns {'permissive' | 'copyleft' | 'unknown' | 'missing'}
16
+ */
17
+ export function classify(licence) {
18
+ const text = typeof licence === 'object' && licence ? licence.type : licence;
19
+ if (!text || text === 'UNLICENSED' || /^SEE LICEN[CS]E IN/i.test(text)) return 'missing';
20
+ const tokens = text.match(/[()]|[^\s()]+/g) ?? [];
21
+ let at = 0;
22
+ // SPDX precedence: parentheses, then WITH, then AND, then OR.
23
+ const term = () => {
24
+ if (tokens[at] === '(') {
25
+ at += 1;
26
+ const inner = anyOf();
27
+ at += 1;
28
+ return inner;
29
+ }
30
+ const id = tokens[at++];
31
+ if (tokens[at] === 'WITH') at += 2;
32
+ return ofId(id);
33
+ };
34
+ const allOf = () => {
35
+ const parts = [term()];
36
+ while (tokens[at] === 'AND') { at += 1; parts.push(term()); }
37
+ return worst(parts);
38
+ };
39
+ const anyOf = () => {
40
+ const choices = [allOf()];
41
+ while (tokens[at] === 'OR') { at += 1; choices.push(allOf()); }
42
+ return best(choices);
43
+ };
44
+ return anyOf();
45
+ }
46
+
47
+ // Every installed package folder, scoped and nested ones included.
48
+ const packageDirs = (root, modules = 'node_modules') => {
49
+ if (!existsSync(join(root, modules))) return [];
50
+ return readdirSync(join(root, modules), { withFileTypes: true })
51
+ .filter((e) => e.isDirectory() && !e.name.startsWith('.'))
52
+ .flatMap((e) => (e.name.startsWith('@')
53
+ ? readdirSync(join(root, modules, e.name), { withFileTypes: true }).filter((s) => s.isDirectory()).map((s) => `${modules}/${e.name}/${s.name}`)
54
+ : [`${modules}/${e.name}`]))
55
+ .flatMap((dir) => [dir, ...packageDirs(root, `${dir}/node_modules`)]);
56
+ };
57
+
58
+ const RULES = {
59
+ missing: { rule: 'G2.licence.missing', fix: 'Replace the dependency: without a licence it cannot be redistributed' },
60
+ copyleft: { rule: 'G2.licence.copyleft', fix: 'Fine for a community plugin; a plugin Verified for products needs a review of the source obligations' },
61
+ unknown: { rule: 'G2.licence.unknown', fix: 'Check the licence by hand, or use an SPDX identifier' },
62
+ };
63
+
64
+ /**
65
+ * G2: the licence of every installed production dependency. Missing or proprietary blocks v2;
66
+ * copyleft and unrecognised licences are warnings.
67
+ * @param {string} dir the built package, after the production install
68
+ * @param {'v1' | 'v2' | undefined} source
69
+ */
70
+ export function licenceFindings(dir, source) {
71
+ return packageDirs(dir)
72
+ .toSorted()
73
+ .filter((pkgDir) => existsSync(join(dir, pkgDir, 'package.json')))
74
+ .flatMap((pkgDir) => {
75
+ const pkg = JSON.parse(readFileSync(join(dir, pkgDir, 'package.json'), 'utf8'));
76
+ const licence = pkg.license ?? pkg.licenses?.[0];
77
+ const kind = classify(licence);
78
+ if (kind === 'permissive') return [];
79
+ const text = (typeof licence === 'object' && licence ? licence.type : licence) || 'no licence';
80
+ return [{
81
+ rule: RULES[kind].rule,
82
+ severity: kind === 'missing' && source !== 'v1' ? 'error' : 'warning',
83
+ file: `${pkgDir}/package.json`,
84
+ message: `${pkg.name}@${pkg.version}: ${text}`,
85
+ fix: RULES[kind].fix,
86
+ }];
87
+ });
88
+ }
@@ -0,0 +1,36 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import Ajv2020 from 'ajv/dist/2020.js';
3
+
4
+ export const schema = JSON.parse(readFileSync(new URL('../schema/manifest.schema.json', import.meta.url), 'utf8'));
5
+
6
+ const validate = new Ajv2020({ allErrors: true, strict: true }).compile(schema);
7
+
8
+ /** @param {import('ajv').ErrorObject} e */
9
+ const pathOf = (e) => {
10
+ if (e.keyword === 'required') return `${e.instancePath}/${e.params.missingProperty}`;
11
+ if (e.keyword === 'additionalProperties') return `${e.instancePath}/${e.params.additionalProperty}`;
12
+ return e.instancePath || '/';
13
+ };
14
+
15
+ /** @param {import('ajv').ErrorObject} e */
16
+ const messageOf = (e) => {
17
+ if (e.keyword === 'required') return 'is missing';
18
+ if (e.keyword === 'additionalProperties') return 'is not a v2 manifest field';
19
+ if (e.keyword === 'enum') return `must be one of: ${e.params.allowedValues.join(', ')}`;
20
+ return e.message ?? 'is invalid';
21
+ };
22
+
23
+ /**
24
+ * Validates a v2 manifest. One error per path: anyOf branches would otherwise repeat it.
25
+ * @param {unknown} manifest
26
+ * @returns {Array<{ path: string, message: string }>}
27
+ */
28
+ export function validateManifest(manifest) {
29
+ if (validate(manifest)) return [];
30
+ const byPath = new Map();
31
+ for (const e of validate.errors ?? []) {
32
+ const path = pathOf(e);
33
+ if (!byPath.has(path)) byPath.set(path, { path, message: messageOf(e) });
34
+ }
35
+ return [...byPath.values()];
36
+ }
package/src/package.js ADDED
@@ -0,0 +1,170 @@
1
+ import { closeSync, cpSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, utimesSync, writeFileSync } from 'node:fs';
2
+ import { createHash } from 'node:crypto';
3
+ import { spawnSync } from 'node:child_process';
4
+ import { tmpdir } from 'node:os';
5
+ import { join, relative } from 'node:path';
6
+ import { check, load } from './check.js';
7
+ import { runAudit } from './audit.js';
8
+ import { licenceFindings } from './licence.js';
9
+ import { toV1 } from './fromV1.js';
10
+
11
+ const ARCH = { arm: 'armhf', x64: 'amd64', arm64: 'arm64' };
12
+ const ELF_MACHINE = { 40: 'armhf', 62: 'amd64', 183: 'arm64' };
13
+ // Top-level entries that never ship: the device installs what is left.
14
+ const NOT_SHIPPED = new Set(['.git', '.github', 'node_modules', 'test', 'tests', '__tests__']);
15
+ const SDK_VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
16
+
17
+ /** @param {string} nodeArch process.arch */
18
+ export function archOf(nodeArch) {
19
+ const arch = ARCH[nodeArch];
20
+ if (!arch) throw new Error(`Unsupported architecture: ${nodeArch}`);
21
+ return arch;
22
+ }
23
+
24
+ /** The architectures a plugin declares: the build runs once for each. @returns {string[]} */
25
+ export function declaredArches(dir) {
26
+ const loaded = load(dir);
27
+ if (loaded.failure) throw new Error(loaded.failure.message);
28
+ const arches = loaded.manifest.arch ?? [];
29
+ if (!arches.length) throw new Error('The manifest declares no architecture');
30
+ const unknown = arches.filter((a) => !Object.values(ARCH).includes(a));
31
+ if (unknown.length) throw new Error(`Unsupported architecture: ${unknown.join(', ')}`);
32
+ return arches;
33
+ }
34
+
35
+ /** @param {Buffer} header the first bytes of a file @returns {string | undefined} */
36
+ export const elfArch = (header) =>
37
+ header.length >= 20 && header.readUInt32BE(0) === 0x7f454c46 ? ELF_MACHINE[header.readUInt16LE(18)] : undefined;
38
+
39
+ // Regular files only, like the device-side submit: no symlinks, which miniunzip does not restore.
40
+ export const files = (root, rel = '') =>
41
+ readdirSync(join(root, rel), { withFileTypes: true }).flatMap((e) => {
42
+ const path = rel ? `${rel}/${e.name}` : e.name;
43
+ if (e.isDirectory()) return files(root, path);
44
+ return e.isFile() ? [path] : [];
45
+ });
46
+
47
+ const header = (path) => {
48
+ const fd = openSync(path, 'r');
49
+ try {
50
+ const buf = Buffer.alloc(20);
51
+ return buf.subarray(0, readSync(fd, buf, 0, 20, 0));
52
+ } finally {
53
+ closeSync(fd);
54
+ }
55
+ };
56
+
57
+ // The npm package a file belongs to: the last node_modules/<name> or node_modules/@scope/<name> in its path.
58
+ const owner = (file) => /^((?:.*\/)?node_modules\/(?:@[^/]+\/)?[^/]+)\//.exec(file)?.[1] ?? '';
59
+ // node-gyp-build loads build/ before prebuilds/: a binary there must match even when a prebuild does.
60
+ const loadedFirst = (file) => /^\/?build\//.test(file.slice(owner(file).length));
61
+
62
+ /**
63
+ * G3: every package with native modules must have one built for the target architecture. A package may ship
64
+ * a binary per platform and pick one at runtime (prebuilds/, gpiox_arm64.node next to gpiox_arm32.node).
65
+ */
66
+ export function nativeFindings(dir, arch) {
67
+ const binaries = files(dir)
68
+ .filter((f) => f.endsWith('.node'))
69
+ .map((file) => ({ file, found: elfArch(header(join(dir, file))) }));
70
+ const covered = new Set(binaries.filter(({ found }) => found === arch).map(({ file }) => owner(file)));
71
+ return binaries
72
+ .filter(({ file, found }) => found !== arch && (loadedFirst(file) || !covered.has(owner(file))))
73
+ .map(({ file, found }) => ({
74
+ rule: 'G3.native-arch',
75
+ severity: 'error',
76
+ file,
77
+ message: `native module built for ${found ?? 'an unknown architecture'}, not ${arch}`,
78
+ fix: 'Build inside the target architecture container, as the Volumio workflow does',
79
+ }));
80
+ }
81
+
82
+ // npm's output goes to stderr: stdout carries only what package reports (findings, zip, sha256).
83
+ const run = (cmd, args, cwd) => {
84
+ const result = spawnSync(cmd, args, { cwd, stdio: ['ignore', 2, 'inherit'] });
85
+ if (result.error || result.status !== 0) throw new Error(`${cmd} ${args.join(' ')} failed in ${cwd}`);
86
+ };
87
+
88
+ const hasProdDeps = (pkg) => Object.keys({ ...pkg.dependencies, ...pkg.optionalDependencies }).length > 0;
89
+
90
+ /** Installs the production dependencies inside the package, building the plugin first if it has a build script. */
91
+ const installDependencies = (stage, pkg, source) => {
92
+ const hasDeps = hasProdDeps(pkg);
93
+ const build = pkg.scripts?.build;
94
+ if (!hasDeps && !build) return [];
95
+ const locked = existsSync(join(stage, 'package-lock.json'));
96
+ const install = (prodOnly) => run('npm', [locked ? 'ci' : 'install', '--no-audit', '--no-fund', ...(prodOnly ? ['--omit=dev'] : [])], stage);
97
+ if (build) {
98
+ install(false);
99
+ run('npm', ['run', 'build'], stage);
100
+ run('npm', ['prune', '--omit=dev'], stage);
101
+ } else {
102
+ install(true);
103
+ }
104
+ return locked ? [] : [{
105
+ rule: 'G3.lockfile',
106
+ severity: source === 'v1' ? 'warning' : 'error',
107
+ file: 'package-lock.json',
108
+ message: 'no package-lock.json: the dependencies are not reproducible',
109
+ fix: 'Commit package-lock.json',
110
+ }];
111
+ };
112
+
113
+ /** Deterministic zip: sorted entries, one fixed mtime, no extra attributes, UTC. */
114
+ const zip = (stage, target, epoch) => {
115
+ const entries = files(stage).sort();
116
+ for (const f of entries) utimesSync(join(stage, f), epoch, epoch);
117
+ const result = spawnSync('zip', ['-X', '-D', '-q', '-9', target, '-@'], {
118
+ cwd: stage,
119
+ input: entries.join('\n'),
120
+ env: { ...process.env, TZ: 'UTC' },
121
+ });
122
+ if (result.error || result.status !== 0) throw new Error(`zip failed: ${result.error?.message ?? result.stderr}`);
123
+ };
124
+
125
+ /**
126
+ * Builds the installable package of a plugin for one architecture, runs the gates on it,
127
+ * and writes <id>-<version>-<arch>.zip, its .sha256 and the provenance next to it.
128
+ * @param {string} src plugin source folder
129
+ * @param {{ out: string, arch?: string, epoch: number, meta?: Record<string, unknown>,
130
+ * functions?: string[], baseline?: Record<string, Record<string, number>> }} options
131
+ */
132
+ export function packagePlugin(src, { out, arch = archOf(process.arch), epoch, meta = {}, functions, baseline }) {
133
+ const stage = mkdtempSync(join(tmpdir(), 'volumio-plugin-'));
134
+ cpSync(src, stage, { recursive: true, filter: (p) => !NOT_SHIPPED.has(relative(src, p).split('/')[0]) });
135
+ const pkgFile = join(stage, 'package.json');
136
+ const source = load(stage);
137
+ // The gates run on the tree that ships: the build can write files.
138
+ const installed = installDependencies(stage, source.pkg ?? {}, source.source);
139
+ // Volumio reads package.json: a v2 plugin's is generated from volumio-plugin.json as the build left it.
140
+ const built = load(stage);
141
+ if (built.source === 'v2') writeFileSync(pkgFile, `${JSON.stringify(toV1(built.manifest, built.pkg), null, 2)}\n`);
142
+ const gates = check(stage, { built: true, functions, baseline });
143
+ // The build can add dependencies: decide on the manifest that ships.
144
+ const shipped = existsSync(pkgFile) ? JSON.parse(readFileSync(pkgFile, 'utf8')) : {};
145
+ const dependencies = hasProdDeps(shipped) ? [...runAudit(stage, gates.source), ...licenceFindings(stage, gates.source)] : [];
146
+ const findings = [...gates.findings, ...installed, ...dependencies, ...nativeFindings(stage, arch)]
147
+ .filter((f) => f.severity !== 'todo');
148
+
149
+ const name = `${gates.id}-${gates.version}-${arch}`;
150
+ mkdirSync(out, { recursive: true });
151
+ const zipPath = join(out, `${name}.zip`);
152
+ zip(stage, zipPath, epoch);
153
+ const sha256 = createHash('sha256').update(readFileSync(zipPath)).digest('hex');
154
+ writeFileSync(`${zipPath}.sha256`, `${sha256} ${name}.zip\n`);
155
+
156
+ const count = (severity) => findings.filter((f) => f.severity === severity).length;
157
+ const provenance = {
158
+ id: gates.id,
159
+ version: gates.version,
160
+ arch,
161
+ sha256,
162
+ sdk: SDK_VERSION,
163
+ epoch,
164
+ source: { repository: meta.repository, commit: meta.commit, ref: meta.ref },
165
+ build: { runId: meta.runId, runAttempt: meta.runAttempt, workflowRef: meta.workflowRef },
166
+ gates: { errors: count('error'), warnings: count('warning'), findings },
167
+ };
168
+ writeFileSync(join(out, `${name}.provenance.json`), `${JSON.stringify(provenance, null, 2)}\n`);
169
+ return { ok: provenance.gates.errors === 0, zip: zipPath, sha256, provenance };
170
+ }
@@ -0,0 +1,76 @@
1
+ // A socket.io v2 client (engine.io protocol 3), the protocol Volumio's backend speaks, on the
2
+ // WebSocket built into Node 22. Events only: no acks, no binary packets, no reconnection.
3
+
4
+ const CONNECT_TIMEOUT_MS = 10000;
5
+
6
+ /**
7
+ * Connects to a Volumio device.
8
+ * @param {string} host address or name, with an optional :port
9
+ * @returns {Promise<{ on: Function, off: Function, emit: Function, close: Function }>}
10
+ */
11
+ export function connect(host, { timeout = CONNECT_TIMEOUT_MS } = {}) {
12
+ if (typeof WebSocket !== 'function') return Promise.reject(new Error('Talking to a device needs Node 22 or later'));
13
+ const ws = new WebSocket(`ws://${host}/socket.io/?EIO=3&transport=websocket`);
14
+ const listeners = new Map();
15
+ const fire = (event, data) => [...(listeners.get(event) ?? [])].forEach((listener) => listener(data));
16
+ let ping;
17
+
18
+ ws.addEventListener('message', ({ data }) => {
19
+ const packet = parse(String(data));
20
+ if (packet.type === 'open') ping = setInterval(() => ws.send('2'), packet.pingInterval);
21
+ else if (packet.type === 'event') fire(packet.event, packet.data);
22
+ else if (packet.type === 'connect') fire('connect');
23
+ });
24
+ ws.addEventListener('close', () => {
25
+ clearInterval(ping);
26
+ fire('disconnect');
27
+ });
28
+
29
+ const socket = {
30
+ on(event, listener) {
31
+ listeners.set(event, new Set([...(listeners.get(event) ?? []), listener]));
32
+ },
33
+ off(event, listener) {
34
+ listeners.get(event)?.delete(listener);
35
+ },
36
+ emit(event, data) {
37
+ ws.send(encode(event, data));
38
+ },
39
+ close() {
40
+ ws.close();
41
+ },
42
+ };
43
+
44
+ return new Promise((resolve, reject) => {
45
+ const timer = setTimeout(() => fail(new Error(`No answer from ${host} within ${timeout / 1000}s`)), timeout);
46
+ const fail = (error) => {
47
+ clearTimeout(timer);
48
+ ws.close();
49
+ reject(error);
50
+ };
51
+ ws.addEventListener('error', () => fail(new Error(`Cannot connect to ${host}`)));
52
+ socket.on('connect', () => {
53
+ clearTimeout(timer);
54
+ resolve(socket);
55
+ });
56
+ });
57
+ }
58
+
59
+ /** One engine.io text frame: open (0), pong (3), or a socket.io packet in a message (4). */
60
+ export function parse(frame) {
61
+ if (frame[0] === '0') return { type: 'open', pingInterval: JSON.parse(frame.slice(1)).pingInterval };
62
+ if (frame === '40') return { type: 'connect' };
63
+ // 42, an optional ack id, then ["event", data].
64
+ const event = /^42\d*(\[.*)$/s.exec(frame);
65
+ if (!event) return { type: 'other' };
66
+ try {
67
+ const [name, data] = JSON.parse(event[1]);
68
+ return { type: 'event', event: name, data };
69
+ } catch {
70
+ // The backend sends some payloads that are not JSON; no event here is one of them.
71
+ return { type: 'other' };
72
+ }
73
+ }
74
+
75
+ /** A socket.io event as an engine.io text frame. */
76
+ export const encode = (event, data) => `42${JSON.stringify(data === undefined ? [event] : [event, data])}`;
@@ -0,0 +1,60 @@
1
+ # {{title}}: instructions for coding agents
2
+
3
+ This folder is a Volumio plugin: id `{{id}}`, type `{{type}}`. The person you work for may not be a developer: tell them in plain words what you changed and why.
4
+
5
+ Before you write code, read `VOLUMIO_API.md`. It describes the plugin API that this plugin's Volumio runs (`engines.api` in `volumio-plugin.json`): what Volumio calls, what it expects back, and the mistakes that break a plugin on the device. This file stays the same from one API to the next; `VOLUMIO_API.md` is the part that changes.
6
+
7
+ ## Files
8
+
9
+ | File | What it is |
10
+ | --- | --- |
11
+ | `volumio-plugin.json` | The manifest: id, version, title, permissions, system packages, hosts |
12
+ | `index.js` | The plugin: the class Volumio creates and calls |
13
+ | `UIConfig.json`, `config.json`, `i18n/` | The settings page, the saved values with their defaults, the text in each language |
14
+ | `install.sh`, `uninstall.sh` | Run as root on the device when the plugin is installed and removed |
15
+ | `test/` | Tests that run the plugin against a fake Volumio (`test/volumio.js`) |
16
+
17
+ `package.json` holds dependencies and scripts only. Never set its `name`, `version` or `volumio_info`: the build writes them from `volumio-plugin.json`.
18
+
19
+ ## After every change
20
+
21
+ ```bash
22
+ npm test
23
+ npx --package=@volumio/plugin-sdk volumio-plugin check .
24
+ ```
25
+
26
+ Both must pass before you say the work is done. `check` runs the gates the store runs on every submission, and each finding comes with a `fix:` line. Fix the code, never the check: inline `eslint-disable` comments, `# shellcheck disable` directives and `.shellcheckrc` are ignored.
27
+
28
+ Add a test in `test/` for each behaviour you add. When the plugin calls a part of Volumio the fake does not have, add it to `test/volumio.js`, following `VOLUMIO_API.md`.
29
+
30
+ ## Try it on a Volumio
31
+
32
+ ```bash
33
+ npx --package=@volumio/plugin-sdk volumio-plugin deploy <device> .
34
+ npx --package=@volumio/plugin-sdk volumio-plugin logs <device> --seconds 30
35
+ ```
36
+
37
+ `<device>` is the address of a Volumio on the same network, such as `volumio.local` or `192.168.1.20`: ask the person for it. `deploy` builds the plugin, installs it, starts it, and prints what the device logged meanwhile; read that log when something fails. `deploy` reboots the device to load the new code, which stops the music for a minute or two: ask the person before the first deploy. `logs` prints the device's log as it is written. Both need Node 22 or later.
38
+
39
+ ## Rules the gates enforce
40
+
41
+ - Log with `this.logger`, never `console.log`.
42
+ - Run a program with `execFile` or `spawn` and its arguments as a list. No `exec`, no `shell: true`, no `execSync` or `spawnSync`.
43
+ - No `process.exit` and no process-wide error handlers (`uncaughtException`, `unhandledRejection`).
44
+ - Never replace a Volumio method (`this.commandRouter.something = ...`).
45
+ - No secrets in any file: no API keys, tokens or private keys. A key the service needs is typed by the user in the settings page.
46
+ - `install.sh` runs with `sh` (dash) as root: POSIX shell only, `set -e`, no `pipefail`, no `|| true`. Install a system package only as `apt-get install -y <package>`, each package named in full and listed in `system.apt` in `volumio-plugin.json`. No npm, pip or dpkg there. Check every download with `sha256sum -c`. Never touch sudoers.
47
+ - Every production dependency has a licence and no high or critical `npm audit` advisory.
48
+
49
+ ## Keep the plugin honest
50
+
51
+ - List in `network`, in `volumio-plugin.json`, every host the plugin connects to, streams included (`stream.example.com`, or `*.example.com` for a family of hosts). Volumio does not block other hosts: the list tells users and reviewers what the plugin talks to. Tell the person which hosts you added.
52
+ - Text the user sees is never written in code: it is a key in `i18n/strings_en.json`, in English, with the same key in `i18n/strings_<language>.json` for each other language, such as `strings_it.json`.
53
+
54
+ ## Ask the person first
55
+
56
+ - Before you add an entry to `permissions` or `system` in `volumio-plugin.json`: each one widens what the plugin does on the user's device, and reviewers check it.
57
+ - Before you add a dependency: prefer what Node and Volumio already provide.
58
+ - Before you remove or weaken a test.
59
+
60
+ The manifest takes no other fields: the schema rejects them. Raise `version` (semver) for each release.
@@ -0,0 +1,2 @@
1
+ @AGENTS.md
2
+ @VOLUMIO_API.md