diff --git a/package.json b/package.json index 925a7d0..2bdca25 100644 --- a/package.json +++ b/package.json @@ -11,9 +11,10 @@ ], "scripts": { "typecheck": "tsc -p tsconfig.json && tsc -p packages/create-waybetter/tsconfig.json", - "test": "bun run test:ts && bun run test:rust && bun run test:create", + "test": "bun run test:ts && bun run test:rust && bun run test:create && bun run test:cli", "test:ts": "node --test packages/runtime/tests/*.test.ts packages/shell/tests/*.test.ts", "test:create": "node --test packages/create-waybetter/tests/*.test.mjs", + "test:cli": "node --test packages/waybetter/tests/*.test.mjs", "test:rust": "cargo test --manifest-path crates/waybetter-host/Cargo.toml --locked --features net", "check:tauri": "cargo check --manifest-path crates/waybetter-host/Cargo.toml --features tauri,net", "build": "bun run typecheck && cargo build --manifest-path crates/waybetter-host/Cargo.toml --locked", diff --git a/packages/create-waybetter/tests/jsonSchema.mjs b/packages/create-waybetter/tests/jsonSchema.mjs index bf850fc..fc1e667 100644 --- a/packages/create-waybetter/tests/jsonSchema.mjs +++ b/packages/create-waybetter/tests/jsonSchema.mjs @@ -1,6 +1,7 @@ // A small JSON Schema (draft 2020-12) validator for the keywords theme.schema.json uses: type, // required, properties, additionalProperties, enum, const, pattern, min/maxLength, minimum, -// maximum, items, maxItems, oneOf, anyOf and local $ref. Returns a list of error paths. +// maximum, items, minItems, maxItems, uniqueItems, allOf, oneOf, anyOf and local $ref (theme and +// store catalog schemas). Returns a list of error paths. const typeOf = value => (value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value); @@ -30,7 +31,9 @@ export function validate(schema, value, root = schema, path = '$') { if (schema.maximum != null && value > schema.maximum) errors.push(`${path}: above ${schema.maximum}`); } if (Array.isArray(value)) { + if (schema.minItems != null && value.length < schema.minItems) errors.push(`${path}: fewer than ${schema.minItems} items`); if (schema.maxItems != null && value.length > schema.maxItems) errors.push(`${path}: more than ${schema.maxItems} items`); + if (schema.uniqueItems && new Set(value.map(item => JSON.stringify(item))).size !== value.length) errors.push(`${path}: repeated items`); if (schema.items) value.forEach((item, index) => errors.push(...validate(schema.items, item, root, `${path}[${index}]`))); } if (typeOf(value) === 'object') { @@ -41,6 +44,7 @@ export function validate(schema, value, root = schema, path = '$') { else if (schema.additionalProperties === false) errors.push(`${path}: unknown property ${key}`); } } + for (const option of schema.allOf ?? []) errors.push(...validate(option, value, root, path)); if (schema.oneOf) { const passing = schema.oneOf.filter(option => validate(option, value, root, path).length === 0).length; if (passing !== 1) errors.push(`${path}: matches ${passing} of oneOf (needs exactly 1)`); diff --git a/packages/waybetter/bin/waybetter.mjs b/packages/waybetter/bin/waybetter.mjs new file mode 100644 index 0000000..53704c6 --- /dev/null +++ b/packages/waybetter/bin/waybetter.mjs @@ -0,0 +1,19 @@ +#!/usr/bin/env node +// The `waybetter` command. Today: `waybetter store build|sign|verify` (cli/store.mjs). +import { readFileSync } from 'node:fs'; +import { STORE_USAGE, storeCommand } from '../cli/store.mjs'; + +const [area, ...rest] = process.argv.slice(2); +try { + if (area === 'store') { + for (const line of await storeCommand(rest)) console.log(line); + } else if (area === '--version' || area === '-v') { + console.log(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version); + } else { + console.log(STORE_USAGE); + if (area && area !== '--help' && area !== '-h') process.exitCode = 1; + } +} catch (error) { + console.error(`waybetter: ${error instanceof Error ? error.message : error}`); + process.exitCode = 1; +} diff --git a/packages/waybetter/cli/store.mjs b/packages/waybetter/cli/store.mjs new file mode 100644 index 0000000..31cc680 --- /dev/null +++ b/packages/waybetter/cli/store.mjs @@ -0,0 +1,314 @@ +// `waybetter store build|sign|verify`: builds an app's part of the shared wayBetter Store catalog, +// signs it offline with the store's Ed25519 key, and verifies it. The rules are the ones the apps +// enforce natively (waybetter-host `store::catalog`); docs/STORE.md in the framework has the format. +// +// waybetter store build --config store.config.mjs [--out dir] [--base https://…/store/] +// waybetter store sign [catalog.json] --key [--pub ] +// waybetter store sign --init --key --pub (once; never overwrites) +// waybetter store verify [catalog.json] --pub [--app id] +// +// The private key is a PKCS#8 PEM that stays where it is: nothing here prints, copies or moves it. +// `--key` defaults to $WAYBETTER_STORE_KEY. The signature file `.sig` is the base64 of the +// 64-byte signature over the exact catalog bytes; a public key file is the base64 of the raw 32 bytes. +import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, sign, verify } from 'node:crypto'; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; + +export const CATALOG_FORMAT = 2; +export const DEFAULT_BASE = 'https://waybetter.fyi/store/'; +/** The framework's download hosts (waybetter-host `DEFAULT_HOSTS`). */ +export const DEFAULT_HOSTS = [ + { host: 'waybetter.fyi', rawFilesOnly: false }, + { host: 'cdn1.crt.fyi', rawFilesOnly: false }, + { host: 'git.crt.fyi', rawFilesOnly: true }, +]; +export const PERMISSIONS = ['storage', 'ui', 'clipboard', 'account', 'users', 'commands', 'network', 'network:none']; +const MAX_BYTES = 2 * 1024 * 1024; +const MAX_ITEMS = 500; +const MAX_CATALOG_BYTES = 1024 * 1024; +// SPKI DER prefix of an Ed25519 public key; the raw 32 bytes follow it. +const SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex'); + +export const sha256 = bytes => createHash('sha256').update(bytes).digest('hex'); + +/** A plugin header (waybetter-host `parse_meta`), enough for the catalog: name, description, version, author, permissions. */ +export function pluginHeader(source) { + const meta = { name: '', description: '', version: '', author: '', permissions: null }; + const body = /^?\s*\/\*\*([\s\S]*?)\*\//.exec(source)?.[1]; + if (!body) return meta; + for (const raw of body.split(/\r?\n/)) { + const line = raw.trim().replace(/^\*+/, '').trim(); + const match = /^@(\w+)\s*(.*)$/.exec(line); + if (!match) continue; + const [, key, value] = match; + if (key === 'permissions') { + const list = value.split(/[\s,]+/).map(token => token.toLowerCase()).filter(token => token && token !== 'none'); + for (const token of list) if (!PERMISSIONS.includes(token)) throw new Error(`unknown permission ${token}`); + meta.permissions = [...new Set([...(meta.permissions ?? []), ...list])]; + // Same cap as the plugin store's parse_meta (300 characters, no control characters). + } else if (key in meta) meta[key] = [...value.trim()].filter(ch => ch >= ' ').slice(0, 300).join(''); + } + return meta; +} + +// ---- Validation (the same rules as waybetter-host store::catalog) ------------------------------ + +const validAppId = id => typeof id === 'string' && /^[a-z0-9-]{1,32}$/.test(id); +const validId = id => typeof id === 'string' && /^[a-z0-9-]{1,40}$/.test(id); +const text = (value, max) => typeof value === 'string' && [...value].length <= max && !/[\p{Cc}]/u.test(value); +const hex = value => typeof value === 'string' && /^#[0-9a-fA-F]{6}$/.test(value); +export const validFileName = file => typeof file === 'string' && file.length > '.plugin.js'.length && file.length <= 128 + && file.endsWith('.plugin.js') && !file.startsWith('.') && /^[A-Za-z0-9_\-. ]+$/.test(file); + +/** An https URL native code may download from (waybetter-host `allowed_download_url`). */ +export function allowedUrl(value, hosts = DEFAULT_HOSTS) { + let url; + try { url = new URL(value); } catch { return false; } + if (url.protocol !== 'https:' || url.username || url.password || url.port || url.hash || url.href.length > 2048) return false; + const rule = hosts.find(h => h.host === url.hostname); + if (!rule) return false; + if (rule.rawFilesOnly) { + const segments = url.pathname.split('/').slice(1); + return segments.length >= 4 && segments[2] === 'raw' && segments.every(s => s && s !== '..'); + } + return true; +} + +const ITEM_FIELDS = new Set(['apps', 'kind', 'id', 'name', 'author', 'version', 'description', 'category', 'tags', 'url', 'file', 'sha256', 'size', 'preview', 'permissions', 'colors']); + +/** Problems with one item; `hosts` checks the download hosts (the reading app's own items). */ +export function itemProblems(item, hosts) { + const bad = []; + if (!item || typeof item !== 'object' || Array.isArray(item)) return ['not an object']; + for (const key of Object.keys(item)) if (!ITEM_FIELDS.has(key)) bad.push(`unknown field ${key}`); + if (!Array.isArray(item.apps) || !item.apps.length || item.apps.length > 16 || !item.apps.every(validAppId) || new Set(item.apps).size !== item.apps.length) bad.push('apps'); + if (item.kind !== 'theme' && item.kind !== 'plugin') bad.push('kind'); + if (!validId(item.id)) bad.push('id'); + if (!text(item.name, 60) || !String(item.name).trim() || !text(item.author ?? '', 60) || !text(item.description ?? '', 600)) bad.push('name, author or description'); + if (!text(item.version, 32) || !item.version || !text(item.category ?? '', 32)) bad.push('version or category'); + if (item.tags !== undefined && (!Array.isArray(item.tags) || item.tags.length > 12 || !item.tags.every(tag => text(tag, 32)))) bad.push('tags'); + if (typeof item.url !== 'string' || !item.url.startsWith('https://') || (hosts && !allowedUrl(item.url, hosts))) bad.push('url (host not allowed)'); + if (item.preview !== undefined && (typeof item.preview !== 'string' || !item.preview.startsWith('https://') || (hosts && !allowedUrl(item.preview, hosts)))) bad.push('preview'); + if (typeof item.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(item.sha256)) bad.push('sha256'); + if (!Number.isInteger(item.size) || item.size <= 0 || item.size > MAX_BYTES) bad.push('size'); + if (item.kind === 'plugin') { + if (!validFileName(item.file) || item.colors != null) bad.push('plugin file'); + const p = item.permissions; + if (p != null && (!Array.isArray(p) || !p.every(x => PERMISSIONS.includes(x)) || new Set(p).size !== p.length || (p.includes('network') && p.includes('network:none')))) bad.push('permissions'); + } + if (item.kind === 'theme') { + if (item.file !== undefined || item.permissions !== undefined) bad.push('theme fields'); + const c = item.colors; + if (c != null && (typeof c !== 'object' || Object.keys(c).some(k => !['bg', 'surface', 'text', 'accent'].includes(k)) || !hex(c.bg) || !hex(c.text) || !hex(c.accent) || (c.surface !== undefined && !hex(c.surface)))) bad.push('colors'); + } + return bad; +} + +/** Problems with a whole catalog (empty = valid). `app`: that app's items are held to `hosts`. */ +export function catalogProblems(catalog, { app, hosts = DEFAULT_HOSTS } = {}) { + const out = []; + if (!catalog || typeof catalog !== 'object') return ['catalog: not an object']; + for (const key of Object.keys(catalog)) if (!['format', 'name', 'generatedAt', 'items'].includes(key)) out.push(`catalog: unknown field ${key}`); + if (catalog.format !== CATALOG_FORMAT) out.push(`catalog: format must be ${CATALOG_FORMAT}`); + if (typeof catalog.name !== 'string' || typeof catalog.generatedAt !== 'string') out.push('catalog: name and generatedAt are strings'); + if (!Array.isArray(catalog.items)) return [...out, 'catalog: items must be a list']; + if (catalog.items.length > MAX_ITEMS) out.push(`catalog: more than ${MAX_ITEMS} items`); + const ids = new Set(); + const files = new Set(); + for (const item of catalog.items) { + const where = `item ${item?.kind}:${item?.id}`; + for (const problem of itemProblems(item, app && item?.apps?.includes(app) ? hosts : undefined)) out.push(`${where}: invalid ${problem}`); + for (const a of Array.isArray(item?.apps) ? item.apps : []) { + const id = `${a}/${item.kind}/${item.id}`; + if (ids.has(id)) out.push(`${where}: duplicate for app ${a}`); + ids.add(id); + if (item.file) { + const file = `${a}/${String(item.file).toLowerCase()}`; + if (files.has(file)) out.push(`${where}: duplicate plugin file for app ${a}`); + files.add(file); + } + } + } + return out; +} + +// ---- Build ------------------------------------------------------------------------------------ + +/** + * Builds `config.app`'s part of the shared catalog in `out`: writes the files the config returns, + * replaces the app's items (other apps' items stay as they are), removes files only the app's old + * items used, validates the whole catalog and writes `catalog.json` (sign it afterwards). + * + * config: { app, name?, base?, out?, hosts?, items(context) → [{ kind, id, name, author, version, + * description, category, tags, file (plugins), permissions (plugins), colors (themes), + * path ('plugins/x.plugin.js'), bytes (Buffer|string), preview?: { path, bytes } }] } + */ +export async function buildStore(config, options = {}) { + const app = config.app; + if (!validAppId(app)) throw new Error('config.app must be an app id (a-z, 0-9, -)'); + const base = options.base ?? config.base ?? DEFAULT_BASE; + if (!/^https:\/\/[^/]+\/(.*\/)?$/.test(base)) throw new Error('base must be an https URL ending in /'); + const out = resolve(options.out ?? config.out ?? '.'); + const hosts = config.hosts ?? DEFAULT_HOSTS; + const catalogPath = join(out, 'catalog.json'); + const previous = existsSync(catalogPath) ? JSON.parse(readFileSync(catalogPath, 'utf8')) : null; + const kept = []; + const oldFiles = new Set(); + for (const item of previous?.format === CATALOG_FORMAT ? previous.items : []) { + if (!item.apps?.includes(app)) { kept.push(item); continue; } + for (const url of [item.url, item.preview]) if (url?.startsWith(base)) oldFiles.add(url.slice(base.length)); + const others = item.apps.filter(a => a !== app); + if (others.length) kept.push({ ...item, apps: others }); + } + const inside = path => { + const target = resolve(out, path); + const rel = relative(out, target); + if (!rel || rel.startsWith('..') || isAbsolute(rel) || !/^[\w.\-/]+$/.test(path)) throw new Error(`file path must stay inside the store folder: ${path}`); + return target; + }; + const entries = await config.items({ app, base, out }); + const items = []; + const files = new Map(); + const toBytes = value => (Buffer.isBuffer(value) ? value : Buffer.from(String(value), 'utf8')); + for (const entry of entries) { + const bytes = toBytes(entry.bytes); + files.set(entry.path, { target: inside(entry.path), bytes }); + const item = { apps: [app], kind: entry.kind, id: entry.id, name: entry.name, author: entry.author ?? '', version: entry.version, description: entry.description ?? '', category: entry.category ?? '', tags: entry.tags ?? [], url: `${base}${entry.path}` }; + if (entry.kind === 'plugin') item.file = entry.file; + item.sha256 = sha256(bytes); + item.size = bytes.length; + if (entry.preview) { + files.set(entry.preview.path, { target: inside(entry.preview.path), bytes: toBytes(entry.preview.bytes) }); + item.preview = `${base}${entry.preview.path}`; + } + if (entry.kind === 'plugin') item.permissions = entry.permissions ?? null; + if (entry.kind === 'theme' && entry.colors) item.colors = entry.colors; + items.push(item); + } + const catalog = { + format: CATALOG_FORMAT, + name: config.name ?? previous?.name ?? 'wayBetter Store', + generatedAt: new Date().toISOString().replace(/\.\d+Z$/, 'Z'), + items: [...kept, ...items], + }; + // Nothing is written unless the whole catalog is valid. + const problems = catalogProblems(catalog, { app, hosts }); + if (problems.length) throw new Error(`the catalog would be invalid:\n ${problems.join('\n ')}`); + const json = `${JSON.stringify(catalog, null, 2)}\n`; + if (Buffer.byteLength(json) > MAX_CATALOG_BYTES) throw new Error('the catalog is larger than apps accept (1 MiB)'); + for (const { target, bytes } of files.values()) { mkdirSync(dirname(target), { recursive: true }); writeFileSync(target, bytes); } + // Files this app's previous build wrote and no item uses any more (never another app's files). + const stillUsed = new Set(kept.flatMap(item => [item.url, item.preview]).filter(url => url?.startsWith(base)).map(url => url.slice(base.length))); + for (const path of oldFiles) if (!files.has(path) && !stillUsed.has(path)) rmSync(inside(path), { force: true }); + mkdirSync(out, { recursive: true }); + writeFileSync(catalogPath, json); + return { catalog, path: catalogPath, items }; +} + +// ---- Keys and signatures ---------------------------------------------------------------------- + +export function rawPublicKey(publicKey) { + const der = publicKey.export({ format: 'der', type: 'spki' }); + if (der.length !== 44 || !der.subarray(0, 12).equals(SPKI_PREFIX)) throw new Error('not an Ed25519 public key'); + return der.subarray(12); +} + +export function publicKeyFromBase64(value) { + const raw = Buffer.from(value.trim(), 'base64'); + if (raw.length !== 32) throw new Error('a public key file must be the base64 of 32 raw bytes'); + return createPublicKey({ key: Buffer.concat([SPKI_PREFIX, raw]), format: 'der', type: 'spki' }); +} + +/** Creates the store key once (0600, never overwritten) and writes its public key file. */ +export function initKey(keyPath, pubPath) { + if (existsSync(keyPath)) { + const base64 = rawPublicKey(createPublicKey(createPrivateKey(readFileSync(keyPath)))).toString('base64'); + if (!existsSync(pubPath) || readFileSync(pubPath, 'utf8').trim() !== base64) { mkdirSync(dirname(pubPath), { recursive: true }); writeFileSync(pubPath, `${base64}\n`); } + return { created: false, publicKey: base64 }; + } + mkdirSync(dirname(keyPath), { recursive: true }); + const { privateKey, publicKey } = generateKeyPairSync('ed25519'); + writeFileSync(keyPath, privateKey.export({ format: 'pem', type: 'pkcs8' }), { mode: 0o600, flag: 'wx' }); + const base64 = rawPublicKey(publicKey).toString('base64'); + mkdirSync(dirname(pubPath), { recursive: true }); + writeFileSync(pubPath, `${base64}\n`); + return { created: true, publicKey: base64 }; +} + +/** Signs the exact bytes of `file` into `.sig`; returns the public key (base64) that verifies it. */ +export function signFile(file, keyPath) { + const privateKey = createPrivateKey(readFileSync(keyPath)); + const signature = sign(null, readFileSync(file), privateKey).toString('base64'); + writeFileSync(`${file}.sig`, `${signature}\n`); + return rawPublicKey(createPublicKey(privateKey)).toString('base64'); +} + +/** Whether `.sig` verifies with any of the public keys (base64 strings). */ +export function verifyFile(file, publicKeys) { + const signature = Buffer.from(readFileSync(`${file}.sig`, 'utf8').trim(), 'base64'); + if (signature.length !== 64) return false; + const body = readFileSync(file); + return publicKeys.some(key => verify(null, body, publicKeyFromBase64(key), signature)); +} + +// ---- Command line ----------------------------------------------------------------------------- + +const USAGE = `Usage: + waybetter store build --config [--out ] [--base ] + waybetter store sign [catalog.json] --key [--pub ] + waybetter store sign --init --key --pub + waybetter store verify [catalog.json] --pub ... [--app ]`; + +function parse(argv) { + const out = { positional: [], pub: [], init: false }; + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + const value = () => { const next = argv[++i]; if (next === undefined) throw new Error(`${arg} needs a value`); return next; }; + if (arg === '--init') out.init = true; + else if (arg === '--pub') out.pub.push(resolve(value())); + else if (arg === '--key' || arg === '--config' || arg === '--out' || arg === '--base' || arg === '--app') out[arg.slice(2)] = value(); + else if (arg.startsWith('--')) throw new Error(`unknown option ${arg}`); + else out.positional.push(arg); + } + return out; +} + +/** Runs `waybetter store …`; returns the lines to print. Throws on errors. */ +export async function storeCommand(argv) { + const [command, ...rest] = argv; + const options = parse(rest); + const catalog = resolve(options.positional[0] ?? 'catalog.json'); + const key = options.key ? resolve(options.key) : process.env.WAYBETTER_STORE_KEY; + if (command === 'build') { + if (!options.config) throw new Error(`build needs --config\n${USAGE}`); + const config = (await import(pathToFileURL(resolve(options.config)).href)).default; + const { path, items } = await buildStore(config, { out: options.out, base: options.base }); + const count = kind => items.filter(item => item.kind === kind).length; + return [`store: ${config.app}: ${count('plugin')} plugins, ${count('theme')} themes → ${path}`, 'Now sign it: waybetter store sign --key ']; + } + if (command === 'sign') { + if (!key) throw new Error('sign needs --key (or WAYBETTER_STORE_KEY)'); + if (options.init) { + if (!options.pub.length) throw new Error('--init needs --pub'); + const { created, publicKey } = initKey(key, options.pub[0]); + return [`${created ? 'Created the store key' : 'Store key already exists'}; public key ${publicKey} → ${options.pub[0]}`]; + } + if (!existsSync(key)) throw new Error(`no store key at ${key} (create it once with --init)`); + const publicKey = signFile(catalog, key); + const keys = options.pub.length ? options.pub.map(file => readFileSync(file, 'utf8').trim()) : [publicKey]; + if (!verifyFile(catalog, keys)) throw new Error(`signature of ${catalog} does NOT verify with ${options.pub.join(', ') || 'the key'}`); + return [`Signed and verified ${catalog}.sig`]; + } + if (command === 'verify') { + if (!options.pub.length) throw new Error('verify needs --pub'); + const keys = options.pub.map(file => readFileSync(file, 'utf8').trim()); + if (!verifyFile(catalog, keys)) throw new Error(`signature of ${catalog} does NOT verify with ${options.pub.join(', ')}`); + const problems = catalogProblems(JSON.parse(readFileSync(catalog, 'utf8')), { app: options.app }); + if (problems.length) throw new Error(`${catalog} is signed but invalid:\n ${problems.join('\n ')}`); + return [`Verified ${catalog}.sig`]; + } + throw new Error(USAGE); +} + +export { USAGE as STORE_USAGE }; diff --git a/packages/waybetter/package.json b/packages/waybetter/package.json index 1617d24..9b532bd 100644 --- a/packages/waybetter/package.json +++ b/packages/waybetter/package.json @@ -3,7 +3,7 @@ "version": "0.2.0", "license": "GPL-3.0-or-later", "type": "module", - "description": "wayBetter: the framework for apps that run the apps you already use in a light native (Tauri) window and extend them in place. Page runtime (DOM/request hubs, plugins, plugin UI kit with themed dialogs and toasts, theme API and theme JSON Schema, theme color model, link routing, account reporting, deck columns, i18n: ICU-lite messages, locale fallback, plugin strings, catalog checks and JSON Schemas), shell models (address bar, panes, decks, profiles, palette, updates) and the Store: install screen and Store view React components (optional React peer), their state and catalog models. No dependencies.", + "description": "wayBetter: the framework for apps that run the apps you already use in a light native (Tauri) window and extend them in place. Page runtime (DOM/request hubs, plugins, plugin UI kit with themed dialogs and toasts, theme API and theme JSON Schema, theme color model, link routing, account reporting, deck columns, i18n: ICU-lite messages, locale fallback, plugin strings, catalog checks and JSON Schemas), shell models (address bar, panes, decks, profiles, palette, updates) and the Store: install screen and Store view React components (optional React peer), their state and catalog models, the store catalog JSON Schema and the `waybetter store build|sign|verify` command. No dependencies.", "keywords": [ "waybetter", "tauri", @@ -24,6 +24,9 @@ "url": "https://git.crt.fyi/CRT/waybetter/issues" }, "sideEffects": false, + "bin": { + "waybetter": "bin/waybetter.mjs" + }, "exports": { "./i18n": { "types": "./dist/runtime/i18n.d.ts", @@ -162,11 +165,16 @@ "import": "./dist/shell/*.js" }, "./theme.schema.json": "./theme.schema.json", + "./store-catalog.schema.json": "./store-catalog.schema.json", + "./cli/store": "./cli/store.mjs", "./package.json": "./package.json" }, "files": [ "dist", + "bin", + "cli", "theme.schema.json", + "store-catalog.schema.json", "i18n.schema.json", "i18n-meta.schema.json", "locales", @@ -193,7 +201,7 @@ }, "scripts": { "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p ../runtime/tsconfig.build.json --outDir dist/runtime --inlineSources --declarationMap false && tsc -p ../shell/tsconfig.build.json --outDir dist/shell --inlineSources --declarationMap false && node -e \"require('fs').copyFileSync('../shell/src/store.css','dist/shell/store.css')\"", - "test": "cd ../.. && node --test packages/runtime/tests/*.test.ts packages/shell/tests/*.test.ts", + "test": "cd ../.. && node --test packages/runtime/tests/*.test.ts packages/shell/tests/*.test.ts packages/waybetter/tests/*.test.mjs", "prepublishOnly": "npm run build && npm test" }, "devDependencies": { diff --git a/packages/waybetter/store-catalog.schema.json b/packages/waybetter/store-catalog.schema.json new file mode 100644 index 0000000..7346a51 --- /dev/null +++ b/packages/waybetter/store-catalog.schema.json @@ -0,0 +1,62 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://unpkg.com/waybetter/store-catalog.schema.json", + "title": "wayBetter Store catalog", + "description": "The shared, signed catalog of the wayBetter Store (format 2). Every wayBetter app reads the same file (catalog.json, signed by catalog.json.sig) and keeps only the items whose `apps` list its id. Apps verify the Ed25519 signature over the exact bytes first, then these rules (waybetter-host store::catalog), then each download's sha256 and size. Build it with `waybetter store build`, sign it with `waybetter store sign`.", + "type": "object", + "required": ["format", "name", "generatedAt", "items"], + "additionalProperties": false, + "properties": { + "format": { "const": 2 }, + "name": { "type": "string" }, + "generatedAt": { "type": "string", "description": "When the catalog was built (RFC 3339, UTC)." }, + "items": { "type": "array", "maxItems": 500, "items": { "$ref": "#/$defs/item" } } + }, + "$defs": { + "text": { "type": "string", "pattern": "^[^\\u0000-\\u001f\\u007f-\\u009f]*$" }, + "https": { "type": "string", "pattern": "^https://", "maxLength": 2048 }, + "color": { "type": "string", "pattern": "^#[0-9a-fA-F]{6}$" }, + "item": { + "type": "object", + "required": ["apps", "kind", "id", "name", "version", "url", "sha256", "size"], + "additionalProperties": false, + "properties": { + "apps": { + "type": "array", "minItems": 1, "maxItems": 16, "uniqueItems": true, + "description": "The wayBetter apps this item is for (app ids such as \"x\"). An app never shows, stages or installs another app's items.", + "items": { "type": "string", "pattern": "^[a-z0-9-]{1,32}$" } + }, + "kind": { "enum": ["theme", "plugin"] }, + "id": { "type": "string", "pattern": "^[a-z0-9-]{1,40}$", "description": "Unique per app and kind." }, + "name": { "allOf": [{ "$ref": "#/$defs/text" }], "type": "string", "minLength": 1, "maxLength": 60 }, + "author": { "allOf": [{ "$ref": "#/$defs/text" }], "type": "string", "maxLength": 60 }, + "version": { "allOf": [{ "$ref": "#/$defs/text" }], "type": "string", "minLength": 1, "maxLength": 32 }, + "description": { "allOf": [{ "$ref": "#/$defs/text" }], "type": "string", "maxLength": 600 }, + "category": { "allOf": [{ "$ref": "#/$defs/text" }], "type": "string", "maxLength": 32, "description": "Shown as `wb.store.category.` when the framework catalogs name it (reading, writing, filters, focus, tools, dark, light), else as is." }, + "tags": { "type": "array", "maxItems": 12, "items": { "allOf": [{ "$ref": "#/$defs/text" }], "type": "string", "maxLength": 32 } }, + "url": { "$ref": "#/$defs/https", "description": "The file. It must be on the reading app's download hosts (waybetter.fyi, cdn1.crt.fyi, git.crt.fyi raw files by default): https, default port, no credentials, no fragment." }, + "file": { "type": "string", "pattern": "^[A-Za-z0-9_\\-. ]+\\.plugin\\.js$", "maxLength": 128, "description": "Plugins only: the file name it is installed under (unique per app, ignoring case)." }, + "sha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" }, + "size": { "type": "integer", "minimum": 1, "maximum": 2097152 }, + "preview": { "$ref": "#/$defs/https" }, + "permissions": { + "description": "Plugins only: the declared @permissions; null = no @permissions line (legacy, full API).", + "anyOf": [ + { "type": "null" }, + { "type": "array", "uniqueItems": true, "items": { "enum": ["storage", "ui", "clipboard", "account", "users", "commands", "network", "network:none"] } } + ] + }, + "colors": { + "description": "Themes only: swatches for the card.", + "anyOf": [ + { "type": "null" }, + { + "type": "object", "required": ["bg", "text", "accent"], "additionalProperties": false, + "properties": { "bg": { "$ref": "#/$defs/color" }, "surface": { "$ref": "#/$defs/color" }, "text": { "$ref": "#/$defs/color" }, "accent": { "$ref": "#/$defs/color" } } + } + ] + } + } + } + } +} diff --git a/packages/waybetter/tests/store-cli.test.mjs b/packages/waybetter/tests/store-cli.test.mjs new file mode 100644 index 0000000..416bb57 --- /dev/null +++ b/packages/waybetter/tests/store-cli.test.mjs @@ -0,0 +1,106 @@ +// `waybetter store build|sign|verify` and the store catalog JSON Schema. +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { validate } from '../../create-waybetter/tests/jsonSchema.mjs'; +import { allowedUrl, buildStore, catalogProblems, pluginHeader, sha256 } from '../cli/store.mjs'; + +const BIN = fileURLToPath(new URL('../bin/waybetter.mjs', import.meta.url)); +const SCHEMA = JSON.parse(readFileSync(new URL('../store-catalog.schema.json', import.meta.url), 'utf8')); +const run = (...args) => execFileSync(process.execPath, [BIN, ...args], { encoding: 'utf8', stdio: 'pipe' }); +/** Runs the bin expecting a non-zero exit; returns what it printed on stderr. */ +function fails(...args) { + try { run(...args); } catch (error) { assert.equal(error.status, 1); return String(error.stderr); } + assert.fail(`waybetter ${args.join(' ')} succeeded`); +} +const PLUGIN = '/**\n * @name Tool\n * @version 1.2.0\n * @author me\n * @permissions ui, network:none\n */\nmodule.exports = class {};\n'; + +function config(app, extra = []) { + return { + app, + items: async () => [ + { kind: 'plugin', ...pluginHeader(PLUGIN), id: 'tool', category: 'tools', tags: ['x'], file: `${app}-tool.plugin.js`, path: `plugins/${app}-tool.plugin.js`, bytes: PLUGIN, preview: { path: `previews/${app}-tool.svg`, bytes: '' } }, + { kind: 'theme', id: 'nord', name: 'Nord', version: '1.0.0', category: 'dark', path: `themes/${app}-nord.json`, bytes: '{"name":"Nord"}\n', colors: { bg: '#2e3440', text: '#eceff4', accent: '#88c0d0' } }, + ...extra, + ], + }; +} + +test('plugin headers: name, version, author, permissions; unknown permissions refused', () => { + assert.deepEqual(pluginHeader(PLUGIN), { name: 'Tool', description: '', version: '1.2.0', author: 'me', permissions: ['ui', 'network:none'] }); + assert.equal(pluginHeader('module.exports = 1').permissions, null); + assert.throws(() => pluginHeader('/**\n * @permissions root\n */'), /unknown permission root/); +}); + +test('build: each app replaces only its own items and files in the shared catalog', async () => { + const out = mkdtempSync(join(tmpdir(), 'wb-store-')); + await buildStore(config('x'), { out }); + await buildStore(config('kick'), { out }); + let catalog = JSON.parse(readFileSync(join(out, 'catalog.json'), 'utf8')); + assert.equal(catalog.format, 2); + assert.deepEqual(catalog.items.map(item => `${item.apps}:${item.kind}:${item.id}`), ['x:plugin:tool', 'x:theme:nord', 'kick:plugin:tool', 'kick:theme:nord']); + const tool = catalog.items[0]; + assert.equal(tool.url, 'https://waybetter.fyi/store/plugins/x-tool.plugin.js'); + assert.equal(tool.sha256, sha256(Buffer.from(PLUGIN))); + assert.equal(tool.size, Buffer.byteLength(PLUGIN)); + assert.deepEqual(tool.permissions, ['ui', 'network:none']); + assert.deepEqual(validate(SCHEMA, catalog), [], 'the schema accepts what build writes'); + assert.deepEqual(catalogProblems(catalog, { app: 'x' }), []); + // x drops its theme: its file goes, kick's stays. + const smaller = { app: 'x', items: async () => (await config('x').items()).filter(item => item.kind === 'plugin') }; + await buildStore(smaller, { out }); + catalog = JSON.parse(readFileSync(join(out, 'catalog.json'), 'utf8')); + assert.deepEqual(catalog.items.map(item => `${item.apps}:${item.id}`), ['kick:tool', 'kick:nord', 'x:tool']); + assert.ok(!existsSync(join(out, 'themes/x-nord.json')) && existsSync(join(out, 'themes/kick-nord.json'))); +}); + +test('build refuses items apps would refuse, and paths outside the store folder', async () => { + const out = mkdtempSync(join(tmpdir(), 'wb-store-')); + await assert.rejects(buildStore({ app: 'X!', items: async () => [] }, { out }), /app id/); + await assert.rejects(buildStore(config('x', [{ kind: 'plugin', id: 'bad', name: 'Bad', version: '1', file: '../bad.plugin.js', path: 'plugins/bad.plugin.js', bytes: PLUGIN }]), { out }), /plugin file/); + await assert.rejects(buildStore(config('x', [{ kind: 'theme', id: 'nord', name: 'Again', version: '1', path: 'themes/again.json', bytes: '{}' }]), { out }), /duplicate/); + await assert.rejects(buildStore(config('x', [{ kind: 'theme', id: 'up', name: 'Up', version: '1', path: '../up.json', bytes: '{}' }]), { out }), /inside the store folder/); + await assert.rejects(buildStore(config('x'), { out, base: 'https://evil.example/store/' }), /host not allowed/); + assert.ok(allowedUrl('https://git.crt.fyi/CRT/repo/raw/branch/main/a.json') && !allowedUrl('https://git.crt.fyi/CRT/repo/src/a.json')); + assert.ok(!allowedUrl('https://waybetter.fyi:444/a') && !allowedUrl('http://waybetter.fyi/a') && !allowedUrl('https://u:p@waybetter.fyi/a')); +}); + +test('the schema refuses what apps refuse', () => { + const good = { format: 2, name: 'S', generatedAt: '2026-09-29T00:00:00Z', items: [{ apps: ['x'], kind: 'theme', id: 'nord', name: 'Nord', version: '1', url: 'https://waybetter.fyi/store/themes/nord.json', sha256: 'a'.repeat(64), size: 1 }] }; + assert.deepEqual(validate(SCHEMA, good), []); + for (const [what, patch] of [['format 1', { format: 1 }], ['no apps', { apps: [] }], ['app id', { apps: ['X'] }], ['repeated app', { apps: ['x', 'x'] }], ['sha256', { sha256: 'ABC' }], ['http', { url: 'http://waybetter.fyi/a' }], ['unknown field', { run: 'code' }], ['size', { size: 0 }]]) { + const doc = structuredClone(good); + if ('format' in patch) doc.format = patch.format; else Object.assign(doc.items[0], patch); + assert.notDeepEqual(validate(SCHEMA, doc), [], `accepted ${what}`); + assert.notDeepEqual(catalogProblems(doc, { app: 'x' }), [], `cli accepted ${what}`); + } +}); + +test('sign and verify: a fresh key signs, the signature verifies, a changed byte does not, key material is never printed', () => { + const dir = mkdtempSync(join(tmpdir(), 'wb-store-')); + const key = join(dir, 'keys', 'store.key'); + const pub = join(dir, 'store.pub'); + const other = join(dir, 'other.pub'); + const catalog = join(dir, 'catalog.json'); + writeFileSync(catalog, JSON.stringify({ format: 2, name: 'Test', generatedAt: '2026-09-29T00:00:00Z', items: [] })); + assert.match(run('store', 'sign', '--init', '--key', key, '--pub', pub), /Created the store key/); + const again = run('store', 'sign', '--init', '--key', key, '--pub', pub); + assert.match(again, /already exists/); + assert.doesNotMatch(again + readFileSync(pub, 'utf8'), /PRIVATE|BEGIN/, 'never prints key material'); + assert.match(run('store', 'sign', catalog, '--key', key, '--pub', pub), /Signed and verified/); + assert.equal(Buffer.from(readFileSync(`${catalog}.sig`, 'utf8').trim(), 'base64').length, 64); + assert.equal(Buffer.from(readFileSync(pub, 'utf8').trim(), 'base64').length, 32); + assert.match(run('store', 'verify', catalog, '--pub', pub), /Verified/); + // Rotation: any listed key verifies. + run('store', 'sign', '--init', '--key', join(dir, 'keys', 'next.key'), '--pub', other); + assert.match(run('store', 'verify', catalog, '--pub', other, '--pub', pub), /Verified/); + assert.match(fails('store', 'verify', catalog, '--pub', other), /does NOT verify/); + writeFileSync(catalog, readFileSync(catalog, 'utf8').replace('Test', 'Tesu')); + assert.match(fails('store', 'verify', catalog, '--pub', pub), /does NOT verify/); + assert.match(fails('store', 'sign', catalog, '--key', join(dir, 'missing.key')), /no store key/); + assert.match(fails('store', 'frobnicate'), /Usage/); +});