waybetter-for-x/scripts/check-store.mjs
2026-09-30 23:01:13 +00:00

287 lines
20 KiB
JavaScript

#!/usr/bin/env node
// `bun run check:store`: what a contributor runs before a pull request that adds or changes a
// Store item, and what a maintainer runs before merging. No key is needed and nothing is written
// to the repository.
//
// node scripts/check-store.mjs check every item under store/x/ and the published catalog
// node scripts/check-store.mjs --verbose also print the notes (not failures)
//
// It checks, for every folder under store/x/ (layout: store/README.md):
// - ids, file names, item.json fields, categories and tags, duplicates
// - plugins: the rules the app applies at install (waybetter-host `validate_plugin`): UTF-8 text,
// a header with @name and @version, valid @permissions; plus the Store's own: a description,
// a @permissions line that names network or network:none, gated API calls declared, and no
// code loaded or evaluated at run time (eval, new Function, import())
// - themes: a JSON object the app's sanitizer accepts, no outside files in its CSS
// - previews: .svg or .png, 16:10, at least 640×400, at most 300 KB, nothing scriptable
// - media for the item's page (item.json "cover", "screenshots", "video"; files in media/):
// PNG, WebP or JPEG up to 400 KB and 1600 px wide with alt text, a 16:10 cover, at most six
// screenshots; one MP4 (H.264) or WebM up to 6 MB and 20 s, without sound, with a poster
// - search and sharing: the page title (≤ 60) and description (50–160) the site generates
// then builds the catalog in a temporary folder (the framework's rules, the ones the apps enforce)
// and compares it with the published one in apps/web/public/store/: the signature, every file's
// size and SHA-256, and which items a maintainer still has to build and sign.
import { cpSync, existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { buildStore, catalogProblems, sha256, verifyFile } from '../waybetter/packages/waybetter/cli/store.mjs';
import config, { APP, source } from './store.config.mjs';
import { CATEGORIES } from './store/source.mjs';
import { readAreaSource } from './store/areas.mjs';
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const PUBLISHED = join(ROOT, 'apps/web/public/store');
const PUBLIC_KEY = join(ROOT, 'apps/desktop/src-tauri/keys/store.pub');
const MAX_ITEM_BYTES = 2 * 1024 * 1024;
const MAX_PREVIEW_BYTES = 300 * 1024;
const verbose = process.argv.includes('--verbose');
const errors = [];
const notes = [];
const fail = (where, message) => errors.push(`${where}: ${message}`);
const note = (where, message) => notes.push(`${where}: ${message}`);
/** What waybetter-host `source_findings` looks for; `network:none` with any of the first five is refused. */
const NETWORK = [['fetch(', 'fetch'], ['XMLHttpRequest', 'XMLHttpRequest'], ['WebSocket', 'WebSocket'], ['EventSource', 'EventSource'], ['sendBeacon', 'sendBeacon']];
const RUNTIME_CODE = [[/\bimport\s*\(/, 'import()'], [/\beval\b/, 'eval'], [/\bnew\s+Function\b/, 'new Function']];
/** The gated part of the plugin API (docs/PLUGINS.md → Permissions). */
const GATED = [
['storage', /\bapi\.storage\s*\(/], ['ui', /\bapi\.(ui\b|toast\s*\()|\bscope\.ui\b/], ['clipboard', /\bapi\.copyText\s*\(/],
['account', /\bapi\.account\s*\(/], ['users', /\bapi\.users\b/], ['commands', /\bapi\.commands\b|\bscope\.commands\b/],
];
function checkPlugin(entry) {
const where = `${entry.dir}/${entry.file}`;
const bytes = Buffer.isBuffer(entry.bytes) ? entry.bytes : Buffer.from(entry.bytes);
if (!bytes.length) return fail(where, 'the file is empty');
if (bytes.length > MAX_ITEM_BYTES) fail(where, 'plugins are limited to 2 MiB');
const text = bytes.toString('utf8');
if (!Buffer.from(text, 'utf8').equals(bytes)) return fail(where, 'a plugin must be UTF-8 text');
// eslint-disable-next-line no-control-regex
if (/[\u0000-\u0008\u000b\u000e-\u001f\u007f-\u009f�]/.test(text)) return fail(where, 'the file contains binary data, not JavaScript text');
const start = text.replace(/^/, '').trimStart();
if (!start.startsWith('/**') || !start.includes('*/')) return fail(where, 'a plugin starts with a /** … */ header (@name, @version, @description, @author, @permissions)');
const header = start.slice(0, start.indexOf('*/'));
if (!header.includes('@name')) fail(where, 'the header needs an @name');
if (!header.includes('@description') || !entry.description) fail(where, 'the header needs an @description');
if (!entry.firstParty && !entry.author) fail(where, 'the header needs an @author');
if ([...header.matchAll(/@description\s*(.*)/g)].some(match => [...match[1].trim()].length > 300)) note(where, 'the @description is longer than 300 characters; the app and the Store keep the first 300');
const permissions = entry.permissions;
if (permissions == null) fail(where, 'the header needs a @permissions line (for example "@permissions storage, ui, network:none"); a plugin without one is "legacy" and is not accepted in the Store');
else {
if (permissions.includes('network') && permissions.includes('network:none')) fail(where, '@permissions: "network" and "network:none" contradict each other');
if (!permissions.includes('network') && !permissions.includes('network:none')) fail(where, '@permissions must say whether the plugin contacts a server: add "network" or "network:none"');
const used = NETWORK.filter(([needle]) => text.includes(needle)).map(([, name]) => name);
if (permissions.includes('network:none') && used.length) fail(where, `the header says network:none but the code uses ${used.join(', ')}`);
for (const [permission, pattern] of GATED) {
if (pattern.test(text) && !permissions.includes(permission)) fail(where, `the code uses the "${permission}" part of the API but @permissions does not declare it`);
}
}
const loaded = RUNTIME_CODE.filter(([pattern]) => pattern.test(text)).map(([, name]) => name);
if (loaded.length) fail(where, `a Store plugin may not load or evaluate code at run time (${loaded.join(', ')}): the code that is reviewed and signed must be the code that runs`);
if (/<script[\s>]|createElement\(\s*['"`]script['"`]\s*\)/i.test(text)) fail(where, 'a Store plugin may not add <script> elements: the code that is reviewed and signed must be the code that runs');
}
/** A string pack: the framework's pack rules, and every string fits the site's inventory. */
async function checkStrings(entry) {
const where = `${entry.dir}/${entry.file}`;
const bytes = Buffer.isBuffer(entry.bytes) ? entry.bytes : Buffer.from(entry.bytes);
if (bytes.length > MAX_ITEM_BYTES) fail(where, 'string packs are limited to 2 MiB');
const { checkPackShape, compilePack } = await import('../waybetter/packages/runtime/src/stringPacks.ts');
for (const issue of checkPackShape(entry.pack)) (issue.level === 'error' ? fail : note)(where, issue.message);
const inventory = JSON.parse(readFileSync(join(ROOT, 'apps/desktop/strings/x.web.inventory.json'), 'utf8'));
if (entry.pack.catalog !== inventory.catalog) return fail(where, `the pack is for the "${entry.pack.catalog}" catalog; the inventory is "${inventory.catalog}"`);
let compiled;
try { compiled = compilePack(entry.pack, inventory); } catch (error) { return fail(where, error.message); }
const { unknown, rejected } = compiled.report;
if (unknown.length) fail(where, `${unknown.length} key(s) the inventory does not have (${unknown.slice(0, 5).join(', ')}); run waybetter strings check`);
for (const item of rejected.slice(0, 10)) fail(where, `${item.id}: ${item.reason}`);
if (rejected.length > 10) fail(where, `… ${rejected.length - 10} more strings do not fit`);
}
function checkTheme(entry) {
const where = `${entry.dir}/theme.json`;
const bytes = Buffer.isBuffer(entry.bytes) ? entry.bytes : Buffer.from(entry.bytes);
if (bytes.length > MAX_ITEM_BYTES) fail(where, 'themes are limited to 2 MiB');
const css = typeof entry.theme?.css === 'string' ? entry.theme.css : '';
if (css) {
if (/@import\b/i.test(css)) fail(where, 'a Store theme\'s css may not @import anything');
if (/url\(\s*['"]?\s*(https?:)?\/\//i.test(css)) fail(where, 'a Store theme\'s css may not load files from another server');
if (!entry.firstParty) note(where, 'this theme carries custom CSS; the install screen warns about it and a maintainer reads it');
}
if (entry.theme?.id !== undefined && entry.theme.id !== entry.id && !entry.firstParty) note(where, `the theme's "id" (${entry.theme.id}) differs from its folder (${entry.id}); the Store uses the folder`);
}
/** Pixel size of a PNG (IHDR) or an SVG (width/height, else viewBox). */
function pictureSize(bytes, png) {
if (png) {
if (bytes.length < 24 || bytes.readUInt32BE(0) !== 0x89504e47 || bytes.toString('latin1', 12, 16) !== 'IHDR') return null;
return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
}
const tag = /<svg\b[^>]*>/i.exec(bytes.toString('utf8'))?.[0];
if (!tag) return null;
const number = name => Number(new RegExp(`\\s${name}="([\\d.]+)(?:px)?"`).exec(tag)?.[1]);
const box = /\sviewBox="\s*[-\d.]+[\s,]+[-\d.]+[\s,]+([\d.]+)[\s,]+([\d.]+)\s*"/.exec(tag);
const width = number('width') || Number(box?.[1]);
const height = number('height') || Number(box?.[2]);
return width && height ? { width, height } : null;
}
function checkPreview(entry) {
const preview = entry.preview;
const where = `${entry.dir} (preview ${preview.path.split('/').pop()})`;
const bytes = Buffer.isBuffer(preview.bytes) ? preview.bytes : Buffer.from(preview.bytes);
const png = preview.path.endsWith('.png');
if (bytes.length > MAX_PREVIEW_BYTES) fail(where, `a preview is at most 300 KB (this one is ${Math.round(bytes.length / 1024)} KB)`);
const size = pictureSize(bytes, png);
if (!size) return fail(where, png ? 'not a PNG file' : 'an SVG preview needs width and height, or a viewBox');
if (Math.abs(size.width / size.height - 1.6) > 0.01) fail(where, `a preview is 16:10, for example 640×400 (this one is ${size.width}×${size.height})`);
if (png && size.width < 640) fail(where, `a PNG preview is at least 640×400 (this one is ${size.width}×${size.height})`);
if (!png) {
const svg = bytes.toString('utf8');
if (/<script\b|<foreignObject\b|\son[a-z]+\s*=|javascript:/i.test(svg)) fail(where, 'an SVG preview may not contain scripts, event handlers or foreignObject');
// The namespace declarations are names, not files; pictures inside the SVG must be data: URLs.
if (/(?:href|src)\s*=\s*["']\s*(?:https?:)?\/\//i.test(svg) || /url\(\s*['"]?\s*(?:https?:)?\/\//i.test(svg)) fail(where, 'an SVG preview may not load files from another server (embed pictures as data: URLs)');
}
}
try {
// ---- The source folders ---------------------------------------------------------------------
const { entries, problems } = await source();
for (const problem of problems) errors.push(problem);
const { readItemMedia } = await import('../apps/web/store-media.ts');
const withMedia = [];
const seen = new Map();
const files = new Map();
for (const entry of entries) {
const where = entry.dir;
const key = `${entry.kind}/${entry.id}`;
if (seen.has(key)) fail(where, `duplicate id (also ${seen.get(key)})`);
seen.set(key, where);
if (entry.kind === 'plugin') {
const file = entry.file.toLowerCase();
if (files.has(file)) fail(where, `another plugin is installed under the same file name (${files.get(file)})`);
files.set(file, where);
}
if (!CATEGORIES[entry.kind].includes(entry.category)) fail(`${where}/item.json`, `"category" must be one of ${CATEGORIES[entry.kind].join(', ')}${entry.category ? ` (not "${entry.category}")` : ''}`);
if (entry.tags.length > 12 || entry.tags.some(tag => !tag.trim() || [...tag].length > 32)) fail(`${where}/item.json`, 'tags: at most 12, each 1 to 32 characters');
if (new Set(entry.tags.map(tag => tag.toLowerCase())).size !== entry.tags.length) fail(`${where}/item.json`, 'tags: a tag is listed twice');
if (!/^\d+\.\d+\.\d+([-+][\w.-]+)?$/.test(entry.version)) note(where, `version "${entry.version}" is not major.minor.patch`);
if ([...entry.name].length > 60) fail(where, 'the name is longer than 60 characters');
if ([...entry.description].length < 50) fail(where, `the description is ${[...entry.description].length} characters; say what it does in at least 50 (it becomes the text under the item's name in search results)`);
if (entry.kind === 'plugin') checkPlugin(entry); else if (entry.kind === 'strings') await checkStrings(entry); else checkTheme(entry);
checkPreview(entry);
// The item's own cover, screenshots and video (website only; the catalog never names them).
const { media, problems: mediaProblems } = readItemMedia(join(ROOT, where), `/store-media/${where.slice('store/'.length)}/`, where);
for (const problem of mediaProblems) errors.push(problem);
const pieces = [media.cover && 'a cover', media.screenshots.length && `${media.screenshots.length} screenshot(s)`, media.video && `a ${media.video.seconds.toFixed(1)} s video`].filter(Boolean);
if (pieces.length) withMedia.push(`${where}: ${pieces.join(', ')}`);
}
// The area plugins: built into the app, a page each on the site (store/x/areas/<id>/), never in the catalog.
const { X_TABLE } = await import('../apps/desktop/src/areas/table.ts');
const areas = readAreaSource({ root: ROOT, app: APP, ids: X_TABLE.areas.map(area => area.id) });
for (const problem of areas.problems) errors.push(problem);
for (const area of areas.entries) {
const { media, problems: mediaProblems } = readItemMedia(join(ROOT, area.dir), `/store-media/${area.dir.slice('store/'.length)}/`, area.dir);
for (const problem of mediaProblems) errors.push(problem);
const pieces = [media.cover && 'a cover', media.screenshots.length && `${media.screenshots.length} screenshot(s)`, media.video && `a ${media.video.seconds.toFixed(1)} s video`].filter(Boolean);
if (pieces.length) withMedia.push(`${area.dir}: ${pieces.join(', ')}`);
}
for (const line of withMedia) note(line, 'media for its page on the site (not in the catalog: no signature needed)');
// store/featured.json: the storefront's "Featured" shelf.
const featuredPath = join(ROOT, 'store/featured.json');
if (existsSync(featuredPath)) {
let featured = [];
try { featured = JSON.parse(readFileSync(featuredPath, 'utf8')); } catch (error) { fail('store/featured.json', `not valid JSON (${error.message})`); }
if (!Array.isArray(featured)) fail('store/featured.json', 'must be a list of "<app>/<kind>/<id>"');
else for (const item of featured) if (typeof item !== 'string' || !seen.has(item.replace(new RegExp(`^${APP}/`), ''))) fail('store/featured.json', `"${item}" is not an item under store/ (write "<app>/<kind>/<id>")`);
}
// ---- The catalog these folders build, with the rules the apps enforce -------------------------
let built = null;
if (!problems.length) {
const out = mkdtempSync(join(tmpdir(), 'wb-store-check-'));
try {
// Start from the published catalog, as the real build does (other apps' items stay).
if (existsSync(join(PUBLISHED, 'catalog.json'))) cpSync(join(PUBLISHED, 'catalog.json'), join(out, 'catalog.json'));
built = (await buildStore(config, { out })).catalog;
} catch (error) {
errors.push(error.message);
} finally {
rmSync(out, { recursive: true, force: true });
}
}
// ---- Search and sharing: the meta data the site generates for every item page -----------------
if (built) {
const { sitePages, TITLE_MAX, DESCRIPTION_MIN, DESCRIPTION_MAX } = await import('../apps/web/seo.ts');
const { areaItems } = await import('../apps/web/areas.ts');
const pages = sitePages(built, { areas: areaItems() });
const titles = new Map();
const descriptions = new Map();
for (const page of pages) {
const where = `page ${page.path}`;
const title = [...page.title].length;
const description = [...page.description].length;
if (title > TITLE_MAX) fail(where, `the title is ${title} characters (at most ${TITLE_MAX}): "${page.title}"`);
// The two app pages keep their longer, hand-written descriptions.
if (page.path.startsWith('/store/') || page.path === '/themes/' || page.path === '/plugins/') {
if (description < DESCRIPTION_MIN || description > DESCRIPTION_MAX) fail(where, `the description is ${description} characters (${DESCRIPTION_MIN} to ${DESCRIPTION_MAX})`);
}
if (titles.has(page.title)) fail(where, `same title as ${titles.get(page.title)}: "${page.title}"`);
if (descriptions.has(page.description)) fail(where, `same description as ${descriptions.get(page.description)}`);
titles.set(page.title, page.path);
descriptions.set(page.description, page.path);
}
for (const entry of entries) if ([...entry.description].length > DESCRIPTION_MAX) note(entry.dir, `the description is ${[...entry.description].length} characters; search engines get its first ${DESCRIPTION_MAX} or fewer (whole sentences)`);
}
// ---- The published catalog (apps/web/public/store): signature, files, and what is pending ------
const catalogPath = join(PUBLISHED, 'catalog.json');
let pending = [];
if (existsSync(catalogPath)) {
const published = JSON.parse(readFileSync(catalogPath, 'utf8'));
for (const problem of catalogProblems(published, { app: APP })) fail('published catalog', problem);
if (!existsSync(`${catalogPath}.sig`) || !verifyFile(catalogPath, [readFileSync(PUBLIC_KEY, 'utf8').trim()])) fail('published catalog', 'catalog.json.sig does not verify with apps/desktop/src-tauri/keys/store.pub (a maintainer signs: node scripts/sign-store.mjs)');
const base = 'https://waybetter.fyi/store/';
for (const item of published.items) {
for (const [field, url] of [['file', item.url], ['preview', item.preview]]) {
if (!url?.startsWith(base)) continue;
const path = join(PUBLISHED, url.slice(base.length));
if (!existsSync(path)) { fail(`published ${item.kind}:${item.id}`, `${field} ${url.slice(base.length)} is missing from apps/web/public/store`); continue; }
if (field !== 'file') continue;
const bytes = readFileSync(path);
if (bytes.length !== item.size || sha256(bytes) !== item.sha256) fail(`published ${item.kind}:${item.id}`, `${url.slice(base.length)} does not match the size and sha256 in the signed catalog`);
}
}
if (built) {
const key = item => `${item.kind}:${item.id}`;
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
const mine = items => new Map(items.filter(item => item.apps.includes(APP)).map(item => [key(item), item]));
const before = mine(published.items);
const after = mine(built.items);
for (const [id, item] of after) if (!before.has(id)) pending.push(`new: ${id}`); else if (!same(item, before.get(id))) pending.push(`changed: ${id}`);
for (const id of before.keys()) if (!after.has(id)) pending.push(`removed: ${id}`);
}
} else fail('published catalog', 'apps/web/public/store/catalog.json is missing');
// ---- Report ---------------------------------------------------------------------------------
const count = kind => entries.filter(entry => entry.kind === kind).length;
if (verbose) for (const line of notes) console.log(`note ${line}`);
for (const line of errors) console.error(`error ${line}`);
console.log(`store: ${count('plugin')} plugins, ${count('theme')} themes, ${count('strings')} string packs under store/${APP}/ · ${errors.length} error(s), ${notes.length} note(s)${notes.length && !verbose ? ' (--verbose lists them)' : ''}`);
if (built && !errors.length) {
if (pending.length) {
console.log(`published catalog: signature and files verify · ${pending.length} item(s) wait for a maintainer to build and sign:`);
for (const line of pending) console.log(` ${line}`);
} else console.log('published catalog: signature and files verify · in sync with the source (nothing to build or sign)');
}
process.exit(errors.length ? 1 : 0);
} catch (error) {
console.error(`check-store: ${error.stack ?? error}`);
process.exit(1);
}