fix(cli): add refuses block and component scripts the project's Node tooling may run (#8703)

* fix(cli): add refuses block and component scripts the project's Node tooling may run

A block or component never installs a TypeScript, JSX or CommonJS file. From a
registry other than the public one, a .js or .mjs file is also refused where a
package.json above the target brings Node tooling, the rule Studio saves follow.
The rule moves into core so the installer and Studio share one copy.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* test(cli): add refuses a page whose own file link leads to a Node-only script

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
James Russo
2026-11-24 12:21:24 +00:00
committed by GitHub
co-authored by Claude Fable 5.2
parent 01074d93c6
commit 260a8d81cc
7 changed files with 233 additions and 93 deletions
+9
View File
@@ -324,6 +324,15 @@ first, resolving them transitively. Before installing any item files, it checks
incompatible CLI. A `deprecated` message produces a warning without blocking
installation.
A block or component never installs a TypeScript, JSX or CommonJS file
(`.ts`, `.tsx`, `.mts`, `.cts`, `.jsx`, `.cjs`). A `.js` or `.mjs` file, such
as a vendored browser library, always installs from the public registry. From
a registry you set in `hyperframes.json`, it installs unless the project folder
or a folder above it has a `package.json` with more than the one `init` writes
(for example, dependencies or a test script): there, the project's own Node
tooling could pick the file up. A refused install fails with `Unsafe target`
before anything is written. Studio saves follow the stricter rule.
### `catalog`
Browse the registry.
@@ -20,6 +20,7 @@ import type { RegistryItem } from "@hyperframes/core";
const remote = vi.hoisted(() => ({ contents: "REGISTRY VERSION\n" }));
vi.mock("./remote.js", () => ({
DEFAULT_REGISTRY_URL: "https://example.test/r",
isPublicRegistry: (registry: string) => registry === "https://example.test/r",
fetchItemFile: vi.fn(async () => Buffer.from(remote.contents)),
}));
@@ -139,6 +140,95 @@ describe("installItem", () => {
expect(readdirSync(dir)).toEqual([]);
});
const withTarget = (planted: string) => ({
...item,
files: [{ ...item.files[0]!, target: planted }],
});
const scaffoldManifest = { name: "film", private: true, scripts: { dev: "hyperframes preview" } };
const nodeManifest = { name: "app", devDependencies: { vitest: "^3.0.0" } };
const otherRegistry = "https://registry.other.test/r";
const registries = [undefined, otherRegistry];
it.each([
"compositions/chart.test.ts",
"lib/widget.tsx",
"compositions/loader.mts",
"assets/setup.cts",
"lib/view.jsx",
"compositions/hook.cjs",
"lib/UPPER.TS",
"lib\\trailing.ts.",
"scenes/extra.spec.ts",
])(
"refuses the Node-only script %s from any registry, in a scaffolded project and a bare folder",
async (planted) => {
for (const baseUrl of registries) {
for (const manifest of [null, scaffoldManifest]) {
const dir = project();
if (manifest) writeFileSync(join(dir, "package.json"), JSON.stringify(manifest));
const options = { destDir: dir, force: true, installDirs: ["scenes"], baseUrl };
await expect(installItem(withTarget(planted), options)).rejects.toThrow(
/Unsafe target.*script Node tooling may run/,
);
expect(readdirSync(dir)).toEqual(manifest ? ["package.json"] : []);
}
}
},
);
it.each(["lib/shaders.iife.js", "compositions/__tests__/chart.test.js", "assets/motion.mjs"])(
"installs the browser script %s from another registry unless the project brings its own Node tooling",
async (planted) => {
const from = { baseUrl: otherRegistry };
for (const manifest of [null, scaffoldManifest]) {
const dir = project();
if (manifest) writeFileSync(join(dir, "package.json"), JSON.stringify(manifest));
await installItem(withTarget(planted), { destDir: dir, ...from });
expect(existsSync(join(dir, planted))).toBe(true);
}
const dir = project();
writeFileSync(join(dir, "package.json"), JSON.stringify(nodeManifest));
await expect(
installItem(withTarget(planted), { destDir: dir, force: true, ...from }),
).rejects.toThrow(/Unsafe target.*script Node tooling may run/);
expect(readdirSync(dir)).toEqual(["package.json"]);
},
);
it("installs a public registry browser script in a project with its own Node tooling", async () => {
const dir = project();
writeFileSync(join(dir, "package.json"), JSON.stringify(nodeManifest));
await installItem(withTarget("lib/shaders.iife.js"), { destDir: dir });
expect(existsSync(join(dir, "lib", "shaders.iife.js"))).toBe(true);
});
it("refuses a browser script the project's own link leads below a Node package", async () => {
const dir = project();
mkdirSync(join(dir, "tools", "pkg"), { recursive: true });
writeFileSync(join(dir, "tools", "package.json"), JSON.stringify(nodeManifest));
symlinkSync(join(dir, "tools", "pkg"), join(dir, "lib"), "junction");
await expect(
installItem(withTarget("lib/shaders.iife.js"), {
destDir: dir,
force: true,
baseUrl: otherRegistry,
}),
).rejects.toThrow(/Unsafe target.*script Node tooling may run/);
expect(readdirSync(join(dir, "tools", "pkg"))).toEqual([]);
});
it("refuses a page whose own file link leads to a Node-only script", async () => {
const dir = project();
mkdirSync(join(dir, "tools"));
mkdirSync(join(dir, "compositions"));
writeFileSync(join(dir, "tools", "run.ts"), "export {};\n");
symlinkSync(join(dir, "tools", "run.ts"), join(dir, "compositions", "data-chart.html"));
await expect(installItem(item, { destDir: dir, force: true })).rejects.toThrow(
/Unsafe target.*script Node tooling may run/,
);
expect(readFileSync(join(dir, "tools", "run.ts"), "utf8")).toBe("export {};\n");
});
it("writes into the standard folders, the configured ones and root notes", async () => {
const dir = project();
const targets = [
+29 -6
View File
@@ -13,8 +13,13 @@ import { createHash } from "node:crypto";
import { existsSync, readFileSync } from "node:fs";
import { resolve, relative, isAbsolute } from "node:path";
import type { FileTarget, RegistryItem } from "@hyperframes/core";
import { toolTrustedFileKind, type ToolTrustedKind } from "@hyperframes/core/safe-path";
import { fetchItemFile, DEFAULT_REGISTRY_URL } from "./remote.js";
import {
nodeMayRun,
nodeOnlyScript,
toolTrustedFileKind,
type ToolTrustedKind,
} from "@hyperframes/core/safe-path";
import { fetchItemFile, DEFAULT_REGISTRY_URL, isPublicRegistry } from "./remote.js";
import {
applyVariableDefaults,
InvalidVariableValuesError,
@@ -268,6 +273,7 @@ function assertSafeTarget(
target: string,
type: RegistryItem["type"],
installDirs: string[][],
script: ScriptRule,
): void {
if (isAbsolute(target)) {
throw new Error(`Unsafe target "${target}": absolute paths are not allowed.`);
@@ -283,10 +289,24 @@ function assertSafeTarget(
if (rel.startsWith("..") || isAbsolute(rel)) {
throw new Error(`Unsafe target "${target}": resolves outside destDir ${destDir}.`);
}
const configError = configTargetError(target, type, installDirs);
const configError = configTargetError(target, type, installDirs) ?? script(destDir, target);
if (configError) throw new Error(`Unsafe target "${target}": ${configError}.`);
}
/** Which block and component scripts an install refuses: Node-only ones always, and from a registry other than the public one, any the project's Node tooling may run, the rule Studio's writes follow. */
type ScriptRule = (root: string, target: string) => string | null;
function scriptRule(type: RegistryItem["type"], baseUrl: string): ScriptRule {
if (type === "hyperframes:example") return () => null;
const refused = isPublicRegistry(baseUrl)
? (_: string, spelled: string) => nodeOnlyScript(spelled)
: (root: string, spelled: string) => nodeMayRun(root, spelled, "file");
return (root, target) =>
refused(root, targetSegments(target).join("/"))
? "it writes a script Node tooling may run"
: null;
}
/** A component's pasteable markup: the file whose declared defaults `--vars` edits. */
function isInstalledComponentSnippet(item: RegistryItem, file: FileTarget): boolean {
return item.type === "hyperframes:component" && file.target.toLowerCase().endsWith(".html");
@@ -407,12 +427,13 @@ export async function prepareItem(
...STANDARD_INSTALL_DIRS,
...(options.installDirs ?? []),
]);
const script = scriptRule(item.type, baseUrl);
for (const file of item.files) {
assertSafeTarget(destDir, file.target, item.type, installDirs);
assertSafeTarget(destDir, file.target, item.type, installDirs, script);
}
const root = registryRoot(destDir);
validatePhysicalTargets(root, item.files, item.type);
validatePhysicalTargets(root, item.files, item.type, script);
const record = readInstallRecord(root);
const budget = { remainingBytes: 512 * 1024 * 1024 };
@@ -471,6 +492,7 @@ function validatePhysicalTargets(
root: string,
files: FileTarget[],
type: RegistryItem["type"],
script: ScriptRule,
): void {
const targets = new Set<string>();
const aliasKey = (path: string): string =>
@@ -481,7 +503,8 @@ function validatePhysicalTargets(
for (const file of files) {
const path = registryTargetPath(root, file.target);
// Where the project's own links lead: still never into node_modules, hidden folders, agent files or programs.
const configError = configTargetError(relative(root, path), type, null);
const physical = relative(root, path);
const configError = configTargetError(physical, type, null) ?? script(root, physical);
if (configError) throw new Error(`Unsafe target "${file.target}": ${configError}.`);
const key = aliasKey(path);
if (targets.has(key) || key === recordKey)
+1
View File
@@ -509,6 +509,7 @@ describe("isPublicRegistry", () => {
`${DEFAULT_REGISTRY_URL}-mirror`,
`${DEFAULT_REGISTRY_URL}/../../../../someone/else/main/registry`,
`${DEFAULT_REGISTRY_URL}/%2e%2e/%2e%2e/%2e%2e/%2e%2e/someone/else/main/registry`,
`${DEFAULT_REGISTRY_URL}/..%2f..%2fpackages`,
`${DEFAULT_REGISTRY_URL}?from=elsewhere`,
DEFAULT_REGISTRY_URL.replace("https://", "https://user@"),
"not a url",
+2 -1
View File
@@ -42,7 +42,8 @@ export function isPublicRegistry(registry: string): boolean {
} catch {
return false;
}
if (url.username || url.password || url.search || url.hash) return false;
const leavesFolderOnHost = url.pathname.includes("%");
if (url.username || url.password || url.search || url.hash || leavesFolderOnHost) return false;
const href = url.href.replace(/\/+$/, "");
return href === DEFAULT_REGISTRY_URL || href.startsWith(`${DEFAULT_REGISTRY_URL}/`);
}
+96 -1
View File
@@ -1,5 +1,12 @@
import { resolve, sep, join, dirname, basename, relative, isAbsolute, parse } from "node:path";
import { lstatSync, mkdirSync, realpath as realpathWalk, realpathSync, statSync } from "node:fs";
import {
lstatSync,
mkdirSync,
readFileSync,
realpath as realpathWalk,
realpathSync,
statSync,
} from "node:fs";
import { realpath as realpathNative } from "node:fs/promises";
import { promisify } from "node:util";
import { projectPathSegments } from "@hyperframes/parsers/private-path";
@@ -316,3 +323,91 @@ export function mkdirWithinProject(root: string, dir: string): void {
}
}
}
/** The real path; for a path not there (yet, or any more), the nearest existing folder's real path plus the rest. */
export function realFilePath(filePath: string): string {
try {
return realpath(filePath);
} catch {
const dir = dirname(filePath);
return dir === filePath ? filePath : join(realFilePath(dir), basename(filePath));
}
}
export type EntryKind = "file" | "folder";
const NODE_ONLY_SCRIPT = /\.(?:[cm]?ts|tsx|jsx|cjs)$/;
const BROWSER_OR_NODE_SCRIPT = /\.m?js$/;
const isExtensionless = (name: string) => name !== "" && !name.includes(".");
/** A script only Node runs, whatever folder holds it. */
export function nodeOnlyScript(relPath: string): boolean {
return NODE_ONLY_SCRIPT.test(foldedPath(relPath).split("/").at(-1) ?? "");
}
/** A Node-only script, or `.js`/`.mjs` or an extensionless file below (at any depth, past the project too) a package.json that is not the scaffold's. */
export function nodeMayRun(projectDir: string, relPath: string, kind: EntryKind): boolean {
if (nodeOnlyScript(relPath)) return true;
const name = foldedPath(relPath).split("/").at(-1) ?? "";
const sharedWithNode =
BROWSER_OR_NODE_SCRIPT.test(name) || (kind === "file" && isExtensionless(name));
if (!sharedWithNode) return false;
const folder = dirname(resolve(projectDir, relPath));
return [folder, realFilePath(folder)].some((from) => foldersUp(from).some(manifestBringsNode));
}
function foldersUp(from: string): string[] {
const parent = dirname(from);
return parent === from ? [from] : [from, ...foldersUp(parent)];
}
const manifests = new Map<string, { stat: string; bringsNode: boolean }>();
function manifestBringsNode(folder: string): boolean {
const path = join(folder, "package.json");
const stat = statSync(path, { throwIfNoEntry: false });
if (!stat?.isFile()) return false;
const key = `${stat.ino}:${stat.size}:${stat.mtimeMs}`;
const cached = manifests.get(path);
if (cached?.stat === key) return cached.bringsNode;
const bringsNode = !isScaffoldManifest(readPackageJson(path));
manifests.set(path, { stat: key, bringsNode });
return bringsNode;
}
function readPackageJson(path: string): unknown {
try {
return JSON.parse(readFileSync(path, "utf-8"));
} catch {
return null;
}
}
const INERT_FIELDS = new Set(
"name version private type description license author contributors keywords homepage repository bugs engines".split(
" ",
),
);
const HYPERFRAMES_COMMAND = /^(?:npx (?:--yes |-y )?)?hyperframes(?:@[\w.+-]+)?(?: [\w@=:./+-]+)*$/;
/** A manifest with nothing but inert fields and scripts that only call the hyperframes CLI, as `hyperframes init` writes. */
function isScaffoldManifest(pkg: unknown): boolean {
if (!pkg || typeof pkg !== "object" || Array.isArray(pkg)) return false;
return Object.entries(pkg).every(([field, value]) =>
field === "scripts" ? onlyHyperframesScripts(value) : INERT_FIELDS.has(field),
);
}
function onlyHyperframesScripts(scripts: unknown): boolean {
if (!scripts || typeof scripts !== "object" || Array.isArray(scripts)) return false;
return Object.values(scripts).every(
(script) =>
typeof script === "string" &&
script.split(" && ").every((command) => HYPERFRAMES_COMMAND.test(command.trim())),
);
}
const foldedPath = (path: string): string =>
projectPathSegments(path)
.filter((segment) => segment !== "" && segment !== ".")
.join("/");
+6 -85
View File
@@ -1,4 +1,4 @@
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import {
closeSync,
constants,
@@ -14,10 +14,12 @@ import {
import {
isStudioPrivatePath,
mkdirWithinProject,
nodeMayRun,
projectPathSegments,
realpath,
realFilePath,
resolveWithinProject as resolveInProject,
toolTrustedFileKind,
type EntryKind,
} from "@hyperframes/core/safe-path";
import { RENDER_TEMP_DIR } from "@hyperframes/core/project-folders";
@@ -29,8 +31,10 @@ export {
isProjectRootMissing,
isSafePath,
mkdirWithinProject,
realFilePath,
realpath,
realProjectRoot,
type EntryKind,
} from "@hyperframes/core/safe-path";
/** Core's `resolveWithinProject`, closed to the desktop app's private files for every route a request path reaches. */
@@ -44,16 +48,6 @@ export function projectRelativePath(base: string, file: string): string {
return relative(resolve(base), resolve(file)).split(sep).join("/");
}
/** The real path; for a path not there (yet, or any more), the nearest existing folder's real path plus the rest. */
export function realFilePath(filePath: string): string {
try {
return realpath(filePath);
} catch {
const dir = dirname(filePath);
return dir === filePath ? filePath : join(realFilePath(dir), basename(filePath));
}
}
/** For a project-relative path with `/` separators; the bundler applies the same rule to preview builds. */
export const isPrivateProjectPath = isStudioPrivatePath;
@@ -80,8 +74,6 @@ export function isWritableProjectPath(relPath: string): boolean {
);
}
export type EntryKind = "file" | "folder";
const entryKindAt = (path: string): EntryKind =>
statSync(path, { throwIfNoEntry: false })?.isDirectory() ? "folder" : "file";
@@ -104,77 +96,6 @@ export function isWritableInProject(
return isWritableProjectPath(relPath) && !nodeMayRun(projectDir, relPath, kind);
}
const NODE_ONLY_SCRIPT = /\.(?:[cm]?ts|tsx|jsx|cjs)$/;
const BROWSER_OR_NODE_SCRIPT = /\.m?js$/;
const isExtensionless = (name: string) => name !== "" && !name.includes(".");
/** A Node-only script, or `.js`/`.mjs` or an extensionless file below (at any depth, past the project too) a package.json that is not the scaffold's. */
function nodeMayRun(projectDir: string, relPath: string, kind: EntryKind): boolean {
const name = foldedPath(relPath).split("/").at(-1) ?? "";
if (NODE_ONLY_SCRIPT.test(name)) return true;
const sharedWithNode =
BROWSER_OR_NODE_SCRIPT.test(name) || (kind === "file" && isExtensionless(name));
if (!sharedWithNode) return false;
const folder = dirname(resolve(projectDir, relPath));
return [folder, realFilePath(folder)].some((from) => foldersUp(from).some(manifestBringsNode));
}
function foldersUp(from: string): string[] {
const parent = dirname(from);
return parent === from ? [from] : [from, ...foldersUp(parent)];
}
const manifests = new Map<string, { stat: string; bringsNode: boolean }>();
function manifestBringsNode(folder: string): boolean {
const path = join(folder, "package.json");
const stat = statSync(path, { throwIfNoEntry: false });
if (!stat?.isFile()) return false;
const key = `${stat.ino}:${stat.size}:${stat.mtimeMs}`;
const cached = manifests.get(path);
if (cached?.stat === key) return cached.bringsNode;
const bringsNode = !isScaffoldManifest(readPackageJson(path));
manifests.set(path, { stat: key, bringsNode });
return bringsNode;
}
function readPackageJson(path: string): unknown {
try {
return JSON.parse(readFileSync(path, "utf-8"));
} catch {
return null;
}
}
const INERT_FIELDS = new Set(
"name version private type description license author contributors keywords homepage repository bugs engines".split(
" ",
),
);
const HYPERFRAMES_COMMAND = /^(?:npx (?:--yes |-y )?)?hyperframes(?:@[\w.+-]+)?(?: [\w@=:./+-]+)*$/;
/** A manifest with nothing but inert fields and scripts that only call the hyperframes CLI, as `hyperframes init` writes. */
function isScaffoldManifest(pkg: unknown): boolean {
if (!pkg || typeof pkg !== "object" || Array.isArray(pkg)) return false;
return Object.entries(pkg).every(([field, value]) =>
field === "scripts" ? onlyHyperframesScripts(value) : INERT_FIELDS.has(field),
);
}
function onlyHyperframesScripts(scripts: unknown): boolean {
if (!scripts || typeof scripts !== "object" || Array.isArray(scripts)) return false;
return Object.values(scripts).every(
(script) =>
typeof script === "string" &&
script.split(" && ").every((command) => HYPERFRAMES_COMMAND.test(command.trim())),
);
}
const foldedPath = (path: string): string =>
projectPathSegments(path)
.filter((segment) => segment !== "" && segment !== ".")
.join("/");
/**
* The first entry below `dir` a folder delete or move must not take along: one a direct delete or rename refuses, a
* `toolTrustedFileKind` file or a script Node tooling may run, or `node_modules` or `.git`. Given `to`, a move's