236 lines
9.9 KiB
TypeScript
236 lines
9.9 KiB
TypeScript
/**
|
||
* Atrium Domi's rules for a `domi-app.toml` (Atrium docs/APP_CONTRACT.md v0 §2), as a test helper. The real parser is
|
||
* Rust (`atrium_registry::parse_manifest`, Fundamentum). APP_CONTRACT §6 asks an app that cannot use it "at least" to
|
||
* check its file against §2. The rules are checked in the parser's order, so a hostile file gets the reason code
|
||
* the parser gives. That agreement was measured once against the parser itself (review of `feature/atrium-door`).
|
||
*
|
||
* The TOML reader takes only what a manifest needs: `key = value` lines, comments, basic strings, booleans, decimal
|
||
* integers (so `format = 2` is `unknown_key`, as in the parser), one-line inline tables and arrays of strings. Anything else is `not_toml`. That is stricter than TOML, which is safe for
|
||
* Rosea's own file; `toml` 1.x would accept some files this refuses.
|
||
*/
|
||
export interface Refusal {
|
||
readonly field: string | null;
|
||
readonly reason: string;
|
||
}
|
||
|
||
type Value = string | boolean | number | readonly string[] | { readonly [k: string]: Value };
|
||
|
||
const MAX_MANIFEST = 16_384;
|
||
|
||
class NotToml extends Error {}
|
||
|
||
function readString(s: string, at: number): [string, number] {
|
||
if (s[at] !== '"') throw new NotToml();
|
||
let out = '';
|
||
let i = at + 1;
|
||
while (i < s.length) {
|
||
const c = s[i]!;
|
||
if (c === '"') return [out, i + 1];
|
||
if (c === '\\') {
|
||
const e = s[i + 1];
|
||
const simple: Record<string, string> = { '"': '"', '\\': '\\', n: '\n', t: '\t', r: '\r', b: '\b', f: '\f' };
|
||
if (e && e in simple) {
|
||
out += simple[e];
|
||
i += 2;
|
||
} else if (e === 'u' || e === 'U') {
|
||
const len = e === 'u' ? 4 : 8;
|
||
const hex = s.slice(i + 2, i + 2 + len);
|
||
if (!/^[0-9a-fA-F]+$/.test(hex) || hex.length !== len) throw new NotToml();
|
||
out += String.fromCodePoint(parseInt(hex, 16));
|
||
i += 2 + len;
|
||
} else throw new NotToml();
|
||
} else if (c === '\n' || (c.charCodeAt(0) < 0x20 && c !== '\t') || c === '\x7f') {
|
||
throw new NotToml();
|
||
} else {
|
||
out += c;
|
||
i += 1;
|
||
}
|
||
}
|
||
throw new NotToml();
|
||
}
|
||
|
||
const skip = (s: string, at: number): number => {
|
||
let i = at;
|
||
while (s[i] === ' ' || s[i] === '\t') i += 1;
|
||
return i;
|
||
};
|
||
|
||
function readValue(s: string, at: number): [Value, number] {
|
||
const i = skip(s, at);
|
||
if (s[i] === '"') return readString(s, i);
|
||
if (s.startsWith('true', i)) return [true, i + 4];
|
||
if (s.startsWith('false', i)) return [false, i + 5];
|
||
const int = /^[+-]?(0|[1-9][0-9]*)(?![0-9A-Za-z._:])/.exec(s.slice(i));
|
||
if (int) return [Number(int[0]), i + int[0].length];
|
||
if (s[i] === '[') {
|
||
const items: string[] = [];
|
||
let j = skip(s, i + 1);
|
||
if (s[j] === ']') return [items, j + 1];
|
||
for (;;) {
|
||
const [v, k] = readString(s, skip(s, j));
|
||
items.push(v);
|
||
j = skip(s, k);
|
||
if (s[j] === ']') return [items, j + 1];
|
||
if (s[j] !== ',') throw new NotToml();
|
||
j += 1;
|
||
}
|
||
}
|
||
if (s[i] === '{') {
|
||
const table: Record<string, Value> = {};
|
||
let j = skip(s, i + 1);
|
||
if (s[j] === '}') return [table, j + 1];
|
||
for (;;) {
|
||
const key = /^[A-Za-z0-9_-]+/.exec(s.slice(skip(s, j)))?.[0];
|
||
if (!key) throw new NotToml();
|
||
j = skip(s, skip(s, j) + key.length);
|
||
if (s[j] !== '=') throw new NotToml();
|
||
const [v, k] = readValue(s, j + 1);
|
||
if (key in table) throw new NotToml();
|
||
table[key] = v;
|
||
j = skip(s, k);
|
||
if (s[j] === '}') return [table, j + 1];
|
||
if (s[j] !== ',') throw new NotToml();
|
||
j += 1;
|
||
}
|
||
}
|
||
throw new NotToml();
|
||
}
|
||
|
||
function readToml(text: string): Record<string, Value> {
|
||
const table: Record<string, Value> = {};
|
||
for (const raw of text.split('\n')) {
|
||
const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw;
|
||
const start = skip(line, 0);
|
||
if (start === line.length || line[start] === '#') continue;
|
||
const key = /^[A-Za-z0-9_-]+/.exec(line.slice(start))?.[0];
|
||
if (!key) throw new NotToml();
|
||
let i = skip(line, start + key.length);
|
||
if (line[i] !== '=') throw new NotToml();
|
||
const [v, end] = readValue(line, i + 1);
|
||
i = skip(line, end);
|
||
if (i !== line.length && line[i] !== '#') throw new NotToml();
|
||
if (key in table) throw new NotToml();
|
||
table[key] = v;
|
||
}
|
||
return table;
|
||
}
|
||
|
||
type Kind = 'str' | 'bool' | 'table' | 'array' | 'other';
|
||
const KEYS: readonly (readonly [string, Kind, boolean])[] = [
|
||
['id', 'str', true],
|
||
['name', 'str', true],
|
||
['label', 'str', true],
|
||
['version', 'str', true],
|
||
['accent', 'str', true],
|
||
['icon', 'str', false],
|
||
['ui_bundle', 'str', false],
|
||
['hostable', 'bool', true],
|
||
['free', 'bool', true],
|
||
['needs', 'table', true],
|
||
['capabilities', 'array', false]
|
||
];
|
||
const kindOf = (v: Value): Kind =>
|
||
typeof v === 'string' ? 'str' : typeof v === 'boolean' ? 'bool' : typeof v === 'number' ? 'other' : Array.isArray(v) ? 'array' : 'table';
|
||
|
||
// SemVer 2.0 (semver.org's regular expression).
|
||
const SEMVER =
|
||
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
|
||
// The part of Cargo's requirement syntax this file uses: comparators like `>=0.7`, comma-separated.
|
||
const SEMVER_REQ = /^\s*(?:[=><~^]|>=|<=)?\s*\d+(?:\.\d+){0,2}(?:\s*,\s*(?:[=><~^]|>=|<=)?\s*\d+(?:\.\d+){0,2})*\s*$/;
|
||
// eslint-disable-next-line no-control-regex -- APP_CONTRACT §2.2's control characters, on purpose
|
||
const CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
|
||
const BIDI = /[--]/;
|
||
const DEVICE = /^(con|prn|aux|nul|com[0-9]|lpt[0-9]|conin\$|conout\$)$/i;
|
||
|
||
function text(field: string, value: string, max: number): Refusal | null {
|
||
const chars = [...value].length;
|
||
if (chars === 0) return { field, reason: 'empty' };
|
||
if (chars > max) return { field, reason: 'too_long' };
|
||
if (CONTROL.test(value)) return { field, reason: 'control_char' };
|
||
if (BIDI.test(value)) return { field, reason: 'bidi_char' };
|
||
if (value.trim() !== value) return { field, reason: 'edge_space' };
|
||
return null;
|
||
}
|
||
|
||
function relPath(p: string): string | null {
|
||
if (p.length === 0) return 'path_empty';
|
||
if (new TextEncoder().encode(p).length > 255) return 'path_too_long';
|
||
if (p.includes('\0')) return 'path_nul';
|
||
if (p.includes('\\')) return 'path_backslash';
|
||
if (p.startsWith('/')) return 'path_absolute';
|
||
if (p.includes(':')) return 'path_colon';
|
||
if (p.includes('..')) return 'path_dotdot';
|
||
const parts = p.split('/');
|
||
if (parts.some((c) => c === '' || c === '.')) return 'path_component';
|
||
if (parts.some((c) => c.endsWith('.') || c.endsWith(' '))) return 'path_trailing';
|
||
if (parts.some((c) => DEVICE.test(c.split('.')[0]!))) return 'path_reserved';
|
||
if (!/^[A-Za-z0-9\-_./ %+()]+$/.test(p)) return 'path_char';
|
||
return null;
|
||
}
|
||
|
||
/** `null` when Atrium Domi would accept the file, else the first rule it breaks. */
|
||
export function checkManifest(bytes: Uint8Array): Refusal | null {
|
||
if (bytes.length > MAX_MANIFEST) return { field: null, reason: 'too_large' };
|
||
let source: string;
|
||
try {
|
||
source = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
||
} catch {
|
||
// Invalid UTF-8 is the answer itself, not an error to report.
|
||
return { field: null, reason: 'not_utf8' };
|
||
}
|
||
let t: Record<string, Value>;
|
||
try {
|
||
t = readToml(source);
|
||
} catch (e) {
|
||
if (e instanceof NotToml) return { field: null, reason: 'not_toml' };
|
||
throw e;
|
||
}
|
||
if (Object.keys(t).some((k) => !KEYS.some(([name]) => name === k))) return { field: null, reason: 'unknown_key' };
|
||
for (const [key, kind, required] of KEYS) {
|
||
const v = t[key];
|
||
if (v === undefined) {
|
||
if (required) return { field: key, reason: 'missing' };
|
||
} else if (kindOf(v) !== kind) return { field: key, reason: 'wrong_type' };
|
||
}
|
||
const needs = t['needs'] as Record<string, Value>;
|
||
if (Object.keys(needs).some((k) => k !== 'fundamentum' && k !== 'atrium')) return { field: 'needs', reason: 'unknown_key' };
|
||
for (const k of ['fundamentum', 'atrium']) {
|
||
if (needs[k] === undefined) return { field: 'needs', reason: 'missing' };
|
||
if (typeof needs[k] !== 'string') return { field: 'needs', reason: 'wrong_type' };
|
||
}
|
||
const caps = (t['capabilities'] ?? []) as readonly Value[];
|
||
if (caps.length > 64) return { field: 'capabilities', reason: 'too_many' };
|
||
if (caps.some((c) => typeof c !== 'string')) return { field: 'capabilities', reason: 'wrong_type' };
|
||
|
||
const id = t['id'] as string;
|
||
if (!/^[a-z0-9-]{1,32}$/.test(id) || id.startsWith('-') || id.endsWith('-')) return { field: 'id', reason: 'bad_id' };
|
||
const named = text('name', t['name'] as string, 64) ?? text('label', t['label'] as string, 32);
|
||
if (named) return named;
|
||
const version = t['version'] as string;
|
||
if (version.length > 64 || !SEMVER.test(version)) return { field: 'version', reason: 'not_semver' };
|
||
if (!/^#[0-9a-fA-F]{6}$/.test(t['accent'] as string)) return { field: 'accent', reason: 'not_rgb' };
|
||
if (typeof t['icon'] === 'string') {
|
||
const bad = relPath(t['icon']);
|
||
if (bad) return { field: 'icon', reason: bad };
|
||
const last = t['icon'].split('/').pop()!;
|
||
const dot = last.lastIndexOf('.');
|
||
if (dot <= 0 || !['png', 'svg', 'ico'].includes(last.slice(dot + 1).toLowerCase())) return { field: 'icon', reason: 'icon_type' };
|
||
}
|
||
if (typeof t['ui_bundle'] === 'string') {
|
||
const bad = relPath(t['ui_bundle']);
|
||
if (bad) return { field: 'ui_bundle', reason: bad };
|
||
} else if (t['hostable'] === true) return { field: 'ui_bundle', reason: 'required' };
|
||
for (const k of ['fundamentum', 'atrium']) {
|
||
const req = needs[k] as string;
|
||
if (req.length > 64 || !SEMVER_REQ.test(req)) return { field: 'needs', reason: 'not_semver_req' };
|
||
}
|
||
const seen = new Set<string>();
|
||
for (const c of caps as readonly string[]) {
|
||
if (!/^[a-z0-9-]+\.[a-z0-9-]+\.[a-z0-9-]+$/.test(c)) return { field: 'capabilities', reason: 'bad_name' };
|
||
if (!c.startsWith(`${id}.`)) return { field: 'capabilities', reason: 'foreign_prefix' };
|
||
if (seen.has(c)) return { field: 'capabilities', reason: 'duplicate' };
|
||
seen.add(c);
|
||
}
|
||
return null;
|
||
}
|