@sellable/install
Version:
One-command installer for Sellable MCP in Claude Code, Codex, and Hermes
297 lines (279 loc) • 8.63 kB
JavaScript
import { createHash } from "node:crypto";
import {
closeSync,
constants,
fstatSync,
lstatSync,
mkdirSync,
openSync,
readFileSync,
readdirSync,
renameSync,
rmSync,
writeFileSync,
} from "node:fs";
import { join } from "node:path";
// Fly's in-Machine exec service rejects a request body over 16 KiB, and it still
// answers HTTP 200 with the rejection only in stderr. A bridge request above
// the server's inline budget therefore arrives in bounded pieces, each written
// by its own exec call into a root-only staging directory, and one small commit
// call reassembles the pieces and checks their exact length and digest before
// the bridge runs the request. Nothing outside the staging directory changes
// until the commit has proven the whole request.
export const FLY_EXEC_STAGE_MARKER = "sellable-exec-stage/v1";
export const FLY_EXEC_COMMIT_MARKER = "sellable-exec-commit/v1";
export const FLY_EXEC_STAGE_CHUNK_MAX_BYTES = 12 * 1024;
export const FLY_EXEC_STAGE_MAX_CHUNKS = 128;
export const FLY_EXEC_STAGING_ROOT = "/run/sellable-agent-exec-staging";
export const FLY_EXEC_STAGING_TTL_MS = 10 * 60 * 1000;
export const FLY_EXEC_STAGING_MAX_ENTRIES = 16;
const CHANNEL = /^(?:soul|skills)$/;
const ENTRY = /^(?:soul|skills)-[a-f0-9]{32}$/;
const STAGING_ID = /^[a-f0-9]{32}$/;
const SHA256 = /^[a-f0-9]{64}$/;
const DECIMAL = /^(?:0|[1-9][0-9]{0,8})$/;
const BASE64URL = /^[A-Za-z0-9_-]+$/;
const OPEN_READ = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0);
export class FlyExecStagingError extends Error {
constructor(code) {
super(code);
this.name = "FlyExecStagingError";
this.code = code;
}
}
function rejected() {
throw new FlyExecStagingError("exec_staging_rejected");
}
function decimal(value, min, max) {
if (typeof value !== "string" || !DECIMAL.test(value)) rejected();
const parsed = Number(value);
if (!Number.isSafeInteger(parsed) || parsed < min || parsed > max) {
rejected();
}
return parsed;
}
export function isFlyExecStagingArguments(args) {
return (
Array.isArray(args) &&
(args[0] === FLY_EXEC_STAGE_MARKER || args[0] === FLY_EXEC_COMMIT_MARKER)
);
}
function parseStagingArguments(args, maxTotalBytes) {
const stage = args[0] === FLY_EXEC_STAGE_MARKER;
if (args.length !== (stage ? 7 : 5)) rejected();
const [, stagingId, ...rest] = args;
if (typeof stagingId !== "string" || !STAGING_ID.test(stagingId)) {
rejected();
}
const [indexText, countText, totalText, totalSha256, chunk] = stage
? rest
: [undefined, ...rest];
const count = decimal(countText, 2, FLY_EXEC_STAGE_MAX_CHUNKS);
const totalBytes = decimal(totalText, count, maxTotalBytes);
if (typeof totalSha256 !== "string" || !SHA256.test(totalSha256)) {
rejected();
}
if (!stage) {
return { stage, stagingId, count, totalBytes, totalSha256 };
}
const index = decimal(indexText, 0, count - 1);
if (
typeof chunk !== "string" ||
chunk.length < 1 ||
Buffer.byteLength(chunk, "utf8") > FLY_EXEC_STAGE_CHUNK_MAX_BYTES ||
!BASE64URL.test(chunk)
) {
rejected();
}
return { stage, stagingId, index, count, totalBytes, totalSha256, chunk };
}
function unavailable(error) {
if (error instanceof FlyExecStagingError) throw error;
throw new FlyExecStagingError("exec_staging_unavailable");
}
function assertOwnedDirectory(path, ownerUid) {
const stats = lstatSync(path);
if (
!stats.isDirectory() ||
stats.isSymbolicLink() ||
stats.uid !== ownerUid ||
(stats.mode & 0o077) !== 0
) {
throw new FlyExecStagingError("exec_staging_unsafe");
}
}
function ensureOwnedDirectory(path, ownerUid) {
try {
mkdirSync(path, { mode: 0o700 });
} catch (error) {
if (error?.code !== "EEXIST") throw error;
}
assertOwnedDirectory(path, ownerUid);
}
function pruneStaleEntries(root, keep, now) {
let live = 0;
for (const name of readdirSync(root)) {
if (name === keep) continue;
const path = join(root, name);
let stale = !ENTRY.test(name);
if (!stale) {
try {
stale = now - lstatSync(path).mtimeMs > FLY_EXEC_STAGING_TTL_MS;
} catch {
continue;
}
}
if (stale) {
rmSync(path, { recursive: true, force: true });
} else {
live += 1;
}
}
if (live >= FLY_EXEC_STAGING_MAX_ENTRIES) {
throw new FlyExecStagingError("exec_staging_full");
}
}
function metaText(request) {
return `${request.count}:${request.totalBytes}:${request.totalSha256}\n`;
}
function readOwnedFile(path, ownerUid, maxBytes) {
let fd;
try {
fd = openSync(path, OPEN_READ);
} catch (error) {
if (error?.code === "ENOENT") {
throw new FlyExecStagingError("exec_staging_incomplete");
}
throw error;
}
try {
const stats = fstatSync(fd);
if (!stats.isFile() || stats.uid !== ownerUid || stats.size > maxBytes) {
throw new FlyExecStagingError("exec_staging_unsafe");
}
return readFileSync(fd, "utf8");
} finally {
closeSync(fd);
}
}
function writeOwnedFile(directory, name, content, pid) {
const temporary = join(directory, `.${name}.${pid}.tmp`);
rmSync(temporary, { force: true });
writeFileSync(temporary, content, { mode: 0o600, flag: "wx" });
renameSync(temporary, join(directory, name));
}
function stageChunk(request, { root, entry, ownerUid, pid }) {
const metaPath = join(entry, "meta");
try {
writeFileSync(metaPath, metaText(request), { mode: 0o600, flag: "wx" });
} catch (error) {
if (error?.code !== "EEXIST") throw error;
if (readOwnedFile(metaPath, ownerUid, 256) !== metaText(request)) {
rejected();
}
}
writeOwnedFile(entry, String(request.index), request.chunk, pid);
assertOwnedDirectory(root, ownerUid);
return Object.freeze({ ok: true, operation: "stage", index: request.index });
}
function commitChunks(request, { entry, ownerUid }) {
try {
assertOwnedDirectory(entry, ownerUid);
} catch (error) {
if (error?.code === "ENOENT") {
throw new FlyExecStagingError("exec_staging_incomplete");
}
throw error;
}
if (readOwnedFile(join(entry, "meta"), ownerUid, 256) !== metaText(request)) {
rejected();
}
let encoded = "";
for (let index = 0; index < request.count; index += 1) {
encoded += readOwnedFile(
join(entry, String(index)),
ownerUid,
FLY_EXEC_STAGE_CHUNK_MAX_BYTES
);
if (encoded.length > request.totalBytes) break;
}
if (
Buffer.byteLength(encoded, "utf8") !== request.totalBytes ||
!BASE64URL.test(encoded) ||
createHash("sha256").update(encoded).digest("hex") !== request.totalSha256
) {
throw new FlyExecStagingError("exec_staging_digest_mismatch");
}
return encoded;
}
/**
* Runs one staging call. A stage call stores one piece and returns its receipt.
* A commit call returns the reassembled request, and always removes its
* staging entry, whether the pieces were complete or not.
*
* @param {string[]} args
* @param {{
* channel: "soul" | "skills";
* maxTotalBytes: number;
* root?: string;
* ownerUid?: number;
* now?: () => number;
* processImpl?: { getuid: () => number; pid: number };
* }} options
* @returns {{ kind: "staged"; receipt: { ok: true; operation: "stage"; index: number } } | { kind: "committed"; encoded: string }}
*/
export function runFlyExecStagingArguments(
args,
{
channel,
maxTotalBytes,
root = FLY_EXEC_STAGING_ROOT,
ownerUid = 0,
now = Date.now,
processImpl = process,
}
) {
if (
!CHANNEL.test(channel ?? "") ||
!Number.isSafeInteger(maxTotalBytes) ||
maxTotalBytes < 2
) {
rejected();
}
if (!isFlyExecStagingArguments(args)) rejected();
const request = parseStagingArguments(args, maxTotalBytes);
if (
typeof processImpl.getuid !== "function" ||
processImpl.getuid() !== ownerUid
) {
throw new FlyExecStagingError("exec_staging_privilege_rejected");
}
const name = `${channel}-${request.stagingId}`;
const entry = join(root, name);
try {
ensureOwnedDirectory(root, ownerUid);
if (request.stage) {
pruneStaleEntries(root, name, now());
ensureOwnedDirectory(entry, ownerUid);
return {
kind: "staged",
receipt: stageChunk(request, {
root,
entry,
ownerUid,
pid: processImpl.pid,
}),
};
}
try {
return {
kind: "committed",
encoded: commitChunks(request, { entry, ownerUid }),
};
} finally {
rmSync(entry, { recursive: true, force: true });
}
} catch (error) {
return unavailable(error);
}
}