dsh-brain/lib/skills/repository.js

201 lines
8.6 KiB
JavaScript

// Skill bundle member — SkillRepository over the skill admin.
// Directory layout, atomic writes, the delivery receipt and park/unpark
// moves live here, so the sync engine never builds a skill path itself.
import { cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
import { randomUUID } from 'node:crypto';
import { dirname, join, resolve, sep } from 'node:path';
import { dshHome } from "../store.js";
import { checkFolder } from "../skill-admin.js";
import { isCloudSkillPath, sha256Hex } from "./shared.js";
function inside(root, target) {
const normalizedRoot = resolve(root);
const normalizedTarget = resolve(target);
return normalizedTarget === normalizedRoot || normalizedTarget.startsWith(normalizedRoot + sep);
}
const RECEIPT = '.manifest.json';
async function isDirectory(path) {
try {
return (await stat(path)).isDirectory();
}
catch {
return false;
}
}
/** Walk a skill folder skipping dot-prefixed names — the reserved-file rule. */
async function walkSkillFiles(dir) {
const files = [];
const walk = async (current, depth) => {
let entries;
try {
entries = await readdir(current, { withFileTypes: true });
}
catch {
return;
}
for (const entry of entries) {
if (entry.name.startsWith('.'))
continue;
const full = join(current, entry.name);
if (entry.isDirectory()) {
await walk(full, depth + 1);
continue;
}
if (!entry.isFile())
continue;
files.push({
rel: full.slice(dir.length + 1).replace(/\\/g, '/'),
bytes: await readFile(full),
mtimeMs: (await stat(full)).mtimeMs,
});
}
};
await walk(dir, 0);
return files.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
}
/** Parse the `.manifest.json` delivery receipt of one folder. */
async function readDeliveryReceipt(dir) {
try {
const raw = JSON.parse(await readFile(join(dir, RECEIPT), 'utf8'));
if (typeof raw !== 'object' || raw === null)
return undefined;
const record = raw;
if (typeof record.name !== 'string' || typeof record.revision !== 'number' || typeof record.manifest_sha256 !== 'string')
return undefined;
const files = Array.isArray(record.files)
? record.files.filter((file) => typeof file === 'object' && file !== null && typeof file.path === 'string' && typeof file.sha256 === 'string')
: undefined;
const delivery = { name: record.name, revision: record.revision, manifest: record.manifest_sha256 };
if (files !== undefined && files.length > 0)
delivery.files = files;
if (typeof record.synced_at === 'string')
delivery.syncedAt = record.synced_at;
return delivery;
}
catch {
return undefined;
}
}
export class AdminSkillRepository {
deps;
constructor(deps) {
this.deps = deps;
}
async list() {
const entries = [];
// Root skips dot-prefixed folders, mirroring the upload scan; holding
// takes every folder, mirroring the sync presence sweep.
for (const entry of await readdir(this.deps.skillsRoot(), { withFileTypes: true }).catch(() => [])) {
if (!entry.isDirectory() || entry.name.startsWith('.'))
continue;
entries.push({ name: entry.name, area: 'root', enabled: true });
}
for (const entry of await readdir(this.deps.holdingDir(), { withFileTypes: true }).catch(() => [])) {
if (!entry.isDirectory())
continue;
entries.push({ name: entry.name, area: 'holding', enabled: false });
}
return entries;
}
async locate(name) {
const folder = checkFolder(name);
const rootDir = join(this.deps.skillsRoot(), folder);
if (await isDirectory(rootDir))
return { area: 'root', dir: rootDir };
const parkedDir = join(this.deps.holdingDir(), folder);
if (await isDirectory(parkedDir))
return { area: 'holding', dir: parkedDir };
return undefined;
}
async read(name) {
const found = await this.locate(name);
if (found === undefined)
return undefined;
const area = found.area;
const files = (await walkSkillFiles(found.dir)).map((file) => ({
path: file.rel,
sha256: sha256Hex(file.bytes),
size: file.bytes.length,
data: file.bytes.toString('base64'),
mtimeMs: file.mtimeMs,
}));
return { name, area, files, delivery: await readDeliveryReceipt(found.dir) };
}
async write(name, bundle, options) {
// The folder name decides where the whole bundle lands, and the file paths
// decide where each write goes — both are attacker-reachable through a
// hostile cloud payload, so both are checked before ANY byte is written.
checkFolder(name);
const decoded = [];
for (const file of bundle.files) {
if (typeof file.path !== 'string' || !isCloudSkillPath(file.path)) {
throw new Error(`refusing to write skill ${name}: invalid file path ${JSON.stringify(file.path)}`);
}
const bytes = Buffer.from(file.data, 'base64');
if (sha256Hex(bytes) !== file.sha256)
throw new Error('checksum mismatch for ' + file.path);
decoded.push({ file, bytes });
}
const folder = options?.folder !== undefined && options.folder !== '' ? checkFolder(options.folder) : name;
const found = await this.locate(folder);
// New skills land in root; a parked folder is written in place.
const dir = found?.dir ?? join(this.deps.skillsRoot(), folder);
const previous = await readDeliveryReceipt(dir);
const cleanup = new Set([...(previous?.files ?? []).map((file) => file.path), ...(options?.cleanupFiles ?? [])]);
await mkdir(dir, { recursive: true });
const keep = new Set(bundle.files.map((file) => file.path));
const written = [];
for (const { file, bytes } of decoded) {
const target = join(dir, ...file.path.split('/'));
if (!inside(dir, target))
throw new Error('skill_path_outside_root: ' + file.path);
await mkdir(dirname(target), { recursive: true });
// Unique temp name: concurrent writers to the same skill must never
// share a predictable temp file, or one rename can commit the other's bytes.
const tmp = `${target}.tmp-${randomUUID()}`;
await writeFile(tmp, bytes);
await rename(tmp, target);
written.push({ path: file.path, sha256: file.sha256, size: bytes.length });
}
// Remove files the previous delivery owned but the new bundle does not.
// Receipts are ours, but a tampered one must not delete outside the folder.
for (const path of cleanup) {
if (typeof path !== 'string' || keep.has(path))
continue;
if (isCloudSkillPath(path)) {
const target = join(dir, ...path.split('/'));
if (!inside(dir, target))
throw new Error('skill_path_outside_root: ' + path);
await rm(target, { force: true });
}
}
const receipt = join(dir, RECEIPT);
if (options?.delivery === false) {
await rm(receipt, { force: true });
return;
}
const payload = { name, revision: bundle.revision, manifest_sha256: bundle.manifest_sha256, files: written, synced_at: new Date().toISOString() };
const tmp = `${receipt}.tmp-${randomUUID()}`;
await writeFile(tmp, JSON.stringify(payload, null, 2) + '\n');
await rename(tmp, receipt);
}
async park(name) {
await this.deps.admin.setEnabled(name, false);
}
async unpark(name) {
await this.deps.admin.setEnabled(name, true);
}
async snapshot(name) {
const found = await this.locate(name);
if (found === undefined)
return undefined;
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
const target = join(dshHome(), '.dsh-brain-backups', 'sync', name, stamp);
await mkdir(dirname(target), { recursive: true });
await cp(found.dir, target, {
recursive: true,
filter: (source) => !source.split(/[\\/]/).includes('.git'),
});
return target;
}
}