mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-25 08:32:45 +00:00
fix(cli): a received project's registry is fetched only from public addresses (#8683)
* fix(cli): a received project's registry is fetched only from public addresses * fix(cli): a received registry connects only to the address it checked, never via a proxy * fix(cli): catalog search vectors download through the registry transport * fix(cli): catalog downloads no search vectors from a received project's registry * refactor(cli): add and catalog share their install printout * fix(cli): the shared install header prints its verb as text
This commit is contained in:
@@ -11,6 +11,8 @@ import {
|
||||
} from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { createServer, isIP, type AddressInfo } from "node:net";
|
||||
import { publicRequest } from "@hyperframes/engine/public-network";
|
||||
import type { RegistryItem, RegistryManifest } from "@hyperframes/core";
|
||||
import { lintHyperframeHtml } from "@hyperframes/lint";
|
||||
import type { RunAddResult } from "./add.js";
|
||||
@@ -48,6 +50,19 @@ vi.mock("../registry/publication.js", async (importOriginal) => {
|
||||
};
|
||||
});
|
||||
|
||||
// The stubbed fetch stands in for public hosts; a numeric host meets the real public-address check.
|
||||
vi.mock("@hyperframes/engine/public-network", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@hyperframes/engine/public-network")>();
|
||||
return {
|
||||
...actual,
|
||||
publicRequest: vi.fn((url: string | URL, init?: RequestInit) =>
|
||||
isIP(new URL(url).hostname)
|
||||
? actual.publicRequest(url, init)
|
||||
: fetch(url, { ...init, redirect: "manual" }),
|
||||
),
|
||||
};
|
||||
});
|
||||
|
||||
// ── Fixtures ────────────────────────────────────────────────────────────────
|
||||
|
||||
const MANIFEST: RegistryManifest = {
|
||||
@@ -889,6 +904,51 @@ describe("installs from the registry a received hyperframes.json names", () => {
|
||||
expect([...staged.keys()].filter((key) => key.startsWith("_ext/"))).toEqual([]);
|
||||
});
|
||||
|
||||
// fails without the fix: a received registry's file was fetched from whatever host its manifest named
|
||||
it.each(["directly", "through a redirect"])(
|
||||
"reaches no private address %s for a received registry, and writes nothing",
|
||||
async (how) => {
|
||||
let connections = 0;
|
||||
const server = createServer((socket) => {
|
||||
connections += 1;
|
||||
socket.destroy();
|
||||
});
|
||||
await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));
|
||||
const internal = `https://127.0.0.1:${(server.address() as AddressInfo).port}/secret`;
|
||||
const base = uniqueBase();
|
||||
writeConfig(base);
|
||||
receive(["hyperframes.json"]);
|
||||
const fileUrl = how === "directly" ? internal : `${base}/redirect`;
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async (input: string | URL) => {
|
||||
const url = new URL(input);
|
||||
if (url.pathname.endsWith("/registry.json")) return Response.json(MANIFEST);
|
||||
if (url.pathname.endsWith("/blocks/my-block/registry-item.json"))
|
||||
return Response.json({
|
||||
...BLOCK_ITEM,
|
||||
files: [{ ...BLOCK_ITEM.files[0]!, url: fileUrl }],
|
||||
});
|
||||
if (url.pathname.endsWith("/redirect"))
|
||||
return new Response(null, { status: 302, headers: { location: internal } });
|
||||
return new Response("internal answer");
|
||||
}),
|
||||
);
|
||||
try {
|
||||
await expect(
|
||||
runAdd({ name: "my-block", projectDir: dir, skipClipboard: true }),
|
||||
).rejects.toThrow("not a public address");
|
||||
expect(connections).toBe(0);
|
||||
expect(existsSync(join(dir, "compositions"))).toBe(false);
|
||||
expect(vi.mocked(publicRequest).mock.calls.map(([url]) => String(url))).toContain(
|
||||
`${base}/registry.json`,
|
||||
);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("lists what an install by tag writes", async () => {
|
||||
writeConfig(uniqueBase());
|
||||
receive(["hyperframes.json"]);
|
||||
|
||||
@@ -312,7 +312,7 @@ function assertCompatibleOrThrow(items: RegistryItem[], cliVersion?: string): st
|
||||
|
||||
// A registry that a received hyperframes.json names serves files that came from its sender; a config that cannot be
|
||||
// read is not proven to be the person's own.
|
||||
function fromReceivedRegistry(projectDir: string, registry: string): boolean {
|
||||
export function fromReceivedRegistry(projectDir: string, registry: string): boolean {
|
||||
if (readProjectConfigWithStatus(projectDir).status === "unreadable") return true;
|
||||
return !isPublicRegistry(registry) && receivedFiles(projectDir)(PROJECT_CONFIG_FILENAME);
|
||||
}
|
||||
@@ -368,6 +368,7 @@ async function installAll(
|
||||
await prepareItem(planItem, {
|
||||
destDir,
|
||||
baseUrl,
|
||||
publicOnly: received,
|
||||
force,
|
||||
// Only the item the user named. A dependency dragged in behind it never
|
||||
// declared these variables and must not be rewritten by them.
|
||||
@@ -427,6 +428,22 @@ export function describeInstallFailure(err: unknown, registry?: string): string
|
||||
);
|
||||
}
|
||||
|
||||
export function printInstalledHeader(result: RunAddResult, verb: "Added" | "Installed"): void {
|
||||
for (const warning of result.warnings) {
|
||||
console.warn(c.warn(`Warning: ${terminalText(warning)}`));
|
||||
}
|
||||
console.log("");
|
||||
console.log(
|
||||
`${c.success("✓")} ${terminalText(verb)} ${c.accent(terminalText(result.name))} (${terminalText(result.type)})`,
|
||||
);
|
||||
}
|
||||
|
||||
export function printSnippet(snippet: string): void {
|
||||
console.log("");
|
||||
console.log(c.dim("Include snippet:"));
|
||||
console.log(` ${terminalText(snippet)}`);
|
||||
}
|
||||
|
||||
export async function runAdd(opts: RunAddArgs): Promise<RunAddResult> {
|
||||
return (await addToProject(opts)).result;
|
||||
}
|
||||
@@ -448,9 +465,13 @@ export async function addToProject(
|
||||
// 2. Resolve the requested item and its transitive registryDependencies.
|
||||
// The list comes back topologically sorted: dependencies first, the
|
||||
// requested item last.
|
||||
const received = fromReceivedRegistry(projectDir, config.registry);
|
||||
let resolved: RegistryItem[];
|
||||
try {
|
||||
resolved = await resolveItemWithDependencies(opts.name, { baseUrl: config.registry });
|
||||
resolved = await resolveItemWithDependencies(opts.name, {
|
||||
baseUrl: config.registry,
|
||||
publicOnly: received,
|
||||
});
|
||||
} catch (err) {
|
||||
throw new AddError(err instanceof Error ? err.message : String(err), "unknown-item");
|
||||
}
|
||||
@@ -496,7 +517,7 @@ export async function addToProject(
|
||||
item.name,
|
||||
variableValues,
|
||||
[config.paths.blocks, config.paths.components, config.paths.assets],
|
||||
fromReceivedRegistry(projectDir, config.registry),
|
||||
received,
|
||||
);
|
||||
|
||||
// Report what landed, not what was asked for: a failed install throws above,
|
||||
@@ -665,13 +686,7 @@ export default defineCommand({
|
||||
if (wroteConfig) {
|
||||
console.log(c.dim(`Wrote default ${terminalText(projectConfigPath(projectDir))}`));
|
||||
}
|
||||
for (const warning of result.warnings) {
|
||||
console.warn(c.warn(`Warning: ${terminalText(warning)}`));
|
||||
}
|
||||
console.log("");
|
||||
console.log(
|
||||
`${c.success("✓")} Added ${c.accent(terminalText(result.name))} (${terminalText(result.type)})`,
|
||||
);
|
||||
printInstalledHeader(result, "Added");
|
||||
const root = realpath(projectDir);
|
||||
for (const file of result.preserved) {
|
||||
console.log(
|
||||
@@ -691,9 +706,7 @@ export default defineCommand({
|
||||
);
|
||||
}
|
||||
if (result.snippet) {
|
||||
console.log("");
|
||||
console.log(c.dim("Include snippet:"));
|
||||
console.log(` ${terminalText(result.snippet)}`);
|
||||
printSnippet(result.snippet);
|
||||
console.log("");
|
||||
console.log(
|
||||
result.clipboardCopied
|
||||
@@ -718,7 +731,11 @@ export default defineCommand({
|
||||
|
||||
let items: Awaited<ReturnType<typeof resolveItemsByTag>>;
|
||||
try {
|
||||
items = await resolveItemsByTag(args.name, { baseUrl: config.registry, skipCache: true });
|
||||
items = await resolveItemsByTag(args.name, {
|
||||
baseUrl: config.registry,
|
||||
skipCache: true,
|
||||
publicOnly: fromReceivedRegistry(projectDir, config.registry),
|
||||
});
|
||||
} catch {
|
||||
items = [];
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
// fallow-ignore-file code-duplication
|
||||
import { beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";
|
||||
import { runCommand, type CommandDef } from "citty";
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import type { RegistryItem } from "@hyperframes/core";
|
||||
import { catalogRow, countUnindexed, pickByName, searchMissReport } from "./catalog.js";
|
||||
@@ -108,7 +111,8 @@ vi.mock("../registry/resolver.js", () => ({
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("../registry/remote.js", () => ({
|
||||
vi.mock("../registry/remote.js", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("../registry/remote.js")>()),
|
||||
readRegistryManifest: async () => {
|
||||
if (state.registryUnreadable) throw new Error(state.registryUnreadable);
|
||||
return { items: state.registry, catalogArtifact: { revision: state.artifactRevision } };
|
||||
@@ -501,6 +505,29 @@ describe("catalog --json meaning search", () => {
|
||||
expect(state.consentRecorded).toEqual([]);
|
||||
});
|
||||
|
||||
// fails without the fix: the catalog downloaded search vectors from the registry a received project names
|
||||
it("downloads no search vectors from a received project's registry", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "hf-catalog-received-"));
|
||||
writeFileSync(
|
||||
join(dir, "hyperframes.json"),
|
||||
JSON.stringify({ registry: "https://registry.test/r" }),
|
||||
);
|
||||
mkdirSync(join(dir, ".hyperframes"));
|
||||
writeFileSync(
|
||||
join(dir, ".hyperframes", "received-files.json"),
|
||||
JSON.stringify({ files: ["hyperframes.json"] }),
|
||||
);
|
||||
const cwd = vi.spyOn(process, "cwd").mockReturnValue(dir);
|
||||
state.cachedVectorRevision = "revision-previous";
|
||||
try {
|
||||
await runEnvelope({ query: "count up" });
|
||||
expect(state.vectorFetches).toBe(0);
|
||||
} finally {
|
||||
cwd.mockRestore();
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("replaces a changed model revision under existing consent", async () => {
|
||||
state.modelStatus = "unavailable";
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ import { relative, resolve } from "node:path";
|
||||
import { CliUsageError, finishCommand } from "../utils/commandResult.js";
|
||||
import { printFailureLine } from "../utils/jsonError.js";
|
||||
import { isUnattended } from "../utils/attendedTerminal.js";
|
||||
import { runAdd } from "./add.js";
|
||||
import { fromReceivedRegistry, printInstalledHeader, printSnippet, runAdd } from "./add.js";
|
||||
import { hasNoSearchableTokens, searchByWords } from "../registry/localSearch.js";
|
||||
import {
|
||||
assumeLocalModelConsent,
|
||||
@@ -58,6 +58,9 @@ const ON_DEVICE_SETUP_COMMAND = "hyperframes catalog --on-device";
|
||||
* Warnings are returned as well as printed so `--json` can carry the same
|
||||
* reasons the terminal shows.
|
||||
*/
|
||||
const fetchRegistryVectors = (registry: string, publicOnly: boolean, expectedRevision?: string) =>
|
||||
publicOnly ? Promise.resolve(false) : fetchLocalVectors(registry, { expectedRevision });
|
||||
|
||||
// a consent gate: each branch is a distinct reason the tier cannot run, and each has to be reported separately
|
||||
// fallow-ignore-next-line complexity
|
||||
async function prepareOnDeviceTier(opts: {
|
||||
@@ -67,6 +70,7 @@ async function prepareOnDeviceTier(opts: {
|
||||
/** Only an explicit --on-device installs the runtime; a plain search never waits on it. */
|
||||
installRuntime: boolean;
|
||||
registry: string;
|
||||
publicOnly: boolean;
|
||||
registryNames: ReadonlySet<string>;
|
||||
status: LocalModelStatus;
|
||||
}): Promise<string[]> {
|
||||
@@ -154,7 +158,7 @@ async function prepareOnDeviceTier(opts: {
|
||||
revisionStale ||
|
||||
countUnindexed(opts.registryNames, localVectorNames()) > 0
|
||||
) {
|
||||
await fetchLocalVectors(opts.registry, { expectedRevision: opts.artifactRevision });
|
||||
await fetchRegistryVectors(opts.registry, opts.publicOnly, opts.artifactRevision);
|
||||
}
|
||||
// Deliberately not the fetch's own answer. A refresh that fails still leaves
|
||||
// the previous vectors on disk, and those still rank: reporting the tier
|
||||
@@ -228,6 +232,7 @@ export default defineCommand({
|
||||
const interactive = args["human-friendly"] === true;
|
||||
const dir = resolve(process.cwd());
|
||||
const config = loadProjectConfig(dir) ?? DEFAULT_PROJECT_CONFIG;
|
||||
const publicOnly = fromReceivedRegistry(dir, config.registry);
|
||||
|
||||
let typeFilter: ItemType | undefined;
|
||||
if (args.type === "block") typeFilter = "hyperframes:block";
|
||||
@@ -239,10 +244,12 @@ export default defineCommand({
|
||||
|
||||
// Asked for the whole manifest on purpose: its item list defines coverage,
|
||||
// and its artifact revision is the one owner of vector freshness.
|
||||
const manifest = await readRegistryManifest(config.registry).catch((error: unknown) => {
|
||||
printFailureLine((show) => show(error instanceof Error ? error.message : String(error)));
|
||||
return finishCommand(1);
|
||||
});
|
||||
const manifest = await readRegistryManifest(config.registry, { publicOnly }).catch(
|
||||
(error: unknown) => {
|
||||
printFailureLine((show) => show(error instanceof Error ? error.message : String(error)));
|
||||
return finishCommand(1);
|
||||
},
|
||||
);
|
||||
const entries = manifest.items;
|
||||
const artifactRevision = manifest.catalogArtifact?.revision;
|
||||
const catalog = entries.filter((e) => e.type !== "hyperframes:example");
|
||||
@@ -255,7 +262,7 @@ export default defineCommand({
|
||||
return;
|
||||
}
|
||||
|
||||
const items = await loadAllItems(filtered, { baseUrl: config.registry });
|
||||
const items = await loadAllItems(filtered, { baseUrl: config.registry, publicOnly });
|
||||
|
||||
const tagFilter = args.tag?.toLowerCase();
|
||||
const tagged = tagFilter
|
||||
@@ -284,6 +291,7 @@ export default defineCommand({
|
||||
canPrompt: !isUnattended() && !json,
|
||||
installRuntime: args["on-device"] === true,
|
||||
registry: config.registry,
|
||||
publicOnly,
|
||||
registryNames,
|
||||
status: searchContext.status,
|
||||
});
|
||||
@@ -381,7 +389,7 @@ export default defineCommand({
|
||||
}
|
||||
}
|
||||
}
|
||||
if (query) await offerLocalModel(0, json, config.registry, artifactRevision);
|
||||
if (query) await offerLocalModel(0, json, config.registry, publicOnly, artifactRevision);
|
||||
// A query with no searchable words is bad input, not an empty shelf, so it
|
||||
// exits non-zero like an invalid --type does. An agent that only checks the
|
||||
// exit code would otherwise read "searched successfully, catalog has
|
||||
@@ -457,7 +465,13 @@ export default defineCommand({
|
||||
if (warnings.length === 0) {
|
||||
const hint = localModelHint(json, effectiveStatus);
|
||||
if (hint) console.error(terminalLines(hint));
|
||||
await offerLocalModel(matching.length, json, config.registry, artifactRevision);
|
||||
await offerLocalModel(
|
||||
matching.length,
|
||||
json,
|
||||
config.registry,
|
||||
publicOnly,
|
||||
artifactRevision,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (query) {
|
||||
@@ -496,22 +510,12 @@ export default defineCommand({
|
||||
skipClipboard: false,
|
||||
});
|
||||
|
||||
for (const warning of result.warnings) {
|
||||
console.warn(c.warn(`Warning: ${terminalText(warning)}`));
|
||||
}
|
||||
console.log("");
|
||||
console.log(
|
||||
`${c.success("✓")} Installed ${c.accent(terminalText(result.name))} (${terminalText(result.type)})`,
|
||||
);
|
||||
printInstalledHeader(result, "Installed");
|
||||
const root = realpath(dir);
|
||||
for (const file of result.written) {
|
||||
console.log(` ${c.dim(terminalText(relative(root, file)))}`);
|
||||
}
|
||||
if (result.snippet) {
|
||||
console.log("");
|
||||
console.log(c.dim("Include snippet:"));
|
||||
console.log(` ${terminalText(result.snippet)}`);
|
||||
}
|
||||
if (result.snippet) printSnippet(result.snippet);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -734,6 +738,7 @@ async function offerLocalModel(
|
||||
matchCount: number,
|
||||
json: boolean,
|
||||
registryBaseUrl: string,
|
||||
publicOnly: boolean,
|
||||
artifactRevision?: string,
|
||||
): Promise<void> {
|
||||
if (json || isUnattended()) return;
|
||||
@@ -759,7 +764,7 @@ async function offerLocalModel(
|
||||
// is an offline tier the user turned on that silently never ranks anything.
|
||||
const vectors =
|
||||
hasLocalVectors() ||
|
||||
(await fetchLocalVectors(registryBaseUrl, { expectedRevision: artifactRevision }));
|
||||
(await fetchRegistryVectors(registryBaseUrl, publicOnly, artifactRevision));
|
||||
console.log(
|
||||
c.dim(
|
||||
vectors
|
||||
|
||||
@@ -31,6 +31,7 @@ export interface InstallOptions {
|
||||
destDir: string;
|
||||
/** Base URL of the registry. Defaults to the official public registry. */
|
||||
baseUrl?: string;
|
||||
publicOnly?: boolean;
|
||||
/** Overwrite files the project has changed since they were installed. */
|
||||
force?: boolean;
|
||||
/**
|
||||
@@ -376,7 +377,7 @@ async function prepareOneFile(
|
||||
return { destPath, target: file.target, preserved: true, hash: null, vars: null, bytes: null };
|
||||
}
|
||||
|
||||
let bytes = await fetchItemFile(item, file, baseUrl, budget);
|
||||
let bytes = await fetchItemFile(item, file, baseUrl, budget, options.publicOnly);
|
||||
if (isInstalledRegistryBlockComposition(item, file)) {
|
||||
bytes = Buffer.from(addRegistryItemMarker(bytes.toString("utf8"), item));
|
||||
}
|
||||
|
||||
@@ -123,8 +123,12 @@ function writeCache<T>(path: string, source: string, data: T): void {
|
||||
|
||||
// ── Fetchers ────────────────────────────────────────────────────────────────
|
||||
|
||||
async function fetchJson<T>(url: string, validate: (value: unknown) => value is T): Promise<T> {
|
||||
const res = await fetchRegistryHttps(url, AbortSignal.timeout(FETCH_TIMEOUT_MS));
|
||||
async function fetchJson<T>(
|
||||
url: string,
|
||||
validate: (value: unknown) => value is T,
|
||||
publicOnly = false,
|
||||
): Promise<T> {
|
||||
const res = await fetchRegistryHttps(url, AbortSignal.timeout(FETCH_TIMEOUT_MS), publicOnly);
|
||||
if (!res.ok) {
|
||||
throw new Error(`Registry fetch failed: ${url} — HTTP ${res.status}`);
|
||||
}
|
||||
@@ -147,14 +151,14 @@ async function fetchJson<T>(url: string, validate: (value: unknown) => value is
|
||||
*/
|
||||
export const fetchRegistryManifest = (
|
||||
baseUrl: string = DEFAULT_REGISTRY_URL,
|
||||
options?: { skipCache?: boolean },
|
||||
options?: { skipCache?: boolean; publicOnly?: boolean },
|
||||
): Promise<RegistryManifest | undefined> =>
|
||||
readRegistryManifest(baseUrl, options).catch(() => undefined);
|
||||
|
||||
/** The manifest as fetchRegistryManifest gives it, but unreachable and never cached throws why, never undefined. */
|
||||
export async function readRegistryManifest(
|
||||
baseUrl: string = DEFAULT_REGISTRY_URL,
|
||||
options?: { skipCache?: boolean },
|
||||
options?: { skipCache?: boolean; publicOnly?: boolean },
|
||||
): Promise<RegistryManifest> {
|
||||
const url = registryPathUrl(baseUrl, "registry.json");
|
||||
const cacheFile = cachePath(baseUrl, "registry");
|
||||
@@ -162,7 +166,7 @@ export async function readRegistryManifest(
|
||||
if (!options?.skipCache && cached && isFresh(cached)) return cached.data;
|
||||
|
||||
try {
|
||||
const manifest = await fetchJson(url, validRegistryManifest);
|
||||
const manifest = await fetchJson(url, validRegistryManifest, options?.publicOnly);
|
||||
writeCache(cacheFile, baseUrl, manifest);
|
||||
return manifest;
|
||||
} catch (err) {
|
||||
@@ -181,7 +185,7 @@ export async function fetchItemManifest(
|
||||
name: string,
|
||||
type: ItemType,
|
||||
baseUrl: string = DEFAULT_REGISTRY_URL,
|
||||
options?: { skipCache?: boolean; cacheOnly?: boolean },
|
||||
options?: { skipCache?: boolean; cacheOnly?: boolean; publicOnly?: boolean },
|
||||
): Promise<RegistryItem> {
|
||||
if (!validRegistryName(name) || !Object.hasOwn(ITEM_TYPE_DIRS, type))
|
||||
throw new Error("Invalid registry item name or type");
|
||||
@@ -195,7 +199,7 @@ export async function fetchItemManifest(
|
||||
if (options?.cacheOnly) throw new Error("not fetched after an earlier registry timeout");
|
||||
|
||||
try {
|
||||
const item = await fetchJson(url, validate);
|
||||
const item = await fetchJson(url, validate, options?.publicOnly);
|
||||
writeCache(cacheFile, baseUrl, item);
|
||||
return item;
|
||||
} catch (err) {
|
||||
@@ -228,12 +232,12 @@ function isRetryableTransport(err: unknown): boolean {
|
||||
* the whole command, which is a bad trade for two extra attempts costing under
|
||||
* a second when the network is healthy.
|
||||
*/
|
||||
async function fetchWithRetry(url: string, attempts = 3): Promise<Response> {
|
||||
async function fetchWithRetry(url: string, publicOnly: boolean, attempts = 3): Promise<Response> {
|
||||
let lastErr: unknown;
|
||||
const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS);
|
||||
for (let attempt = 1; attempt <= attempts; attempt++) {
|
||||
try {
|
||||
return await fetchRegistryHttps(url, signal);
|
||||
return await fetchRegistryHttps(url, signal, publicOnly);
|
||||
} catch (err) {
|
||||
lastErr = err;
|
||||
if (attempt === attempts || !isRetryableTransport(err)) break;
|
||||
@@ -282,6 +286,7 @@ export async function fetchItemFile(
|
||||
file: FileTarget,
|
||||
baseUrl: string = DEFAULT_REGISTRY_URL,
|
||||
budget: DownloadByteBudget = { remainingBytes: 512 * 1024 * 1024 },
|
||||
publicOnly = false,
|
||||
): Promise<Buffer> {
|
||||
// Reject path-traversal in file.path (mirrors assertSafeTarget for file.target).
|
||||
if (/(^|[/\\])\.\.([/\\]|$)/.test(file.path)) {
|
||||
@@ -290,7 +295,7 @@ export async function fetchItemFile(
|
||||
const url = assetSourceUrl(item, file, baseUrl);
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetchWithRetry(url);
|
||||
res = await fetchWithRetry(url, publicOnly);
|
||||
} catch (err) {
|
||||
// undici throws a bare "fetch failed" and buries the real reason in
|
||||
// `cause`, sometimes a level deeper again. That is where the diagnosis
|
||||
|
||||
@@ -18,6 +18,8 @@ export interface ResolveOptions {
|
||||
baseUrl?: string;
|
||||
/** Bypass the 24h manifest cache and fetch fresh data from the registry. */
|
||||
skipCache?: boolean;
|
||||
/** Reach the registry only on public addresses (`fetchRegistryHttps`). */
|
||||
publicOnly?: boolean;
|
||||
/**
|
||||
* Called once with a summary when items fail to load inside `loadAllItems`.
|
||||
* Defaults to writing a diagnostic line to stderr. Pass a quieter
|
||||
@@ -39,7 +41,10 @@ export async function listRegistryItems(
|
||||
options: ResolveOptions = {},
|
||||
): Promise<RegistryManifestEntry[]> {
|
||||
const baseUrl = options.baseUrl ?? DEFAULT_REGISTRY_URL;
|
||||
const manifest = await fetchRegistryManifest(baseUrl, { skipCache: options.skipCache });
|
||||
const manifest = await fetchRegistryManifest(baseUrl, {
|
||||
skipCache: options.skipCache,
|
||||
publicOnly: options.publicOnly,
|
||||
});
|
||||
if (!manifest) return [];
|
||||
if (!filter?.type) return manifest.items;
|
||||
return manifest.items.filter((item) => item.type === filter.type);
|
||||
@@ -67,6 +72,7 @@ export async function loadAllItems(
|
||||
return await fetchItemManifest(e.name, e.type, baseUrl, {
|
||||
skipCache: options.skipCache,
|
||||
cacheOnly: timedOut,
|
||||
publicOnly: options.publicOnly,
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof Error && err.name === "TimeoutError") timedOut = true;
|
||||
@@ -188,6 +194,7 @@ export async function resolveItemWithDependencies(
|
||||
|
||||
const pending = fetchItemManifest(registryEntry.name, registryEntry.type, options.baseUrl, {
|
||||
skipCache: options.skipCache,
|
||||
publicOnly: options.publicOnly,
|
||||
});
|
||||
itemCache.set(itemName, pending);
|
||||
return pending;
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { registryPathUrl, registryHttpsUrl, fetchRegistryHttps } from "./transport.js";
|
||||
|
||||
const network = vi.hoisted(() => ({ publicRequest: vi.fn() }));
|
||||
vi.mock("@hyperframes/engine/public-network", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@hyperframes/engine/public-network")>()),
|
||||
publicRequest: network.publicRequest,
|
||||
}));
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
it("preserves private registries and signed CDN URLs while encoding path segments", () => {
|
||||
expect(
|
||||
@@ -40,3 +46,14 @@ it("follows a relative HTTPS redirect", async () => {
|
||||
).toBe("ok");
|
||||
expect(fetchMock.mock.calls[1]?.[0]).toBe("https://private.example/asset");
|
||||
});
|
||||
// fails without the fix: a public-only hop let a configured capture proxy pick the address
|
||||
it("sends a public-only hop down the pinned route, never a configured proxy", async () => {
|
||||
network.publicRequest.mockResolvedValueOnce(new Response("ok"));
|
||||
const response = await fetchRegistryHttps(
|
||||
"https://registry.example.com/x",
|
||||
AbortSignal.timeout(1000),
|
||||
true,
|
||||
);
|
||||
expect(await response.text()).toBe("ok");
|
||||
expect(network.publicRequest).toHaveBeenCalledWith(expect.any(URL), expect.anything(), null);
|
||||
});
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { NonPublicHostError, publicRequest } from "@hyperframes/engine/public-network";
|
||||
|
||||
/** Registry hosts may be private; authenticate the HTTPS transport, not public IP reachability. */
|
||||
export function registryHttpsUrl(value: string): URL {
|
||||
const url = new URL(value);
|
||||
@@ -29,10 +31,16 @@ export function registryPathUrl(base: string, ...parts: string[]): string {
|
||||
return url.href;
|
||||
}
|
||||
|
||||
export async function fetchRegistryHttps(value: string, signal: AbortSignal): Promise<Response> {
|
||||
export async function fetchRegistryHttps(
|
||||
value: string,
|
||||
signal: AbortSignal,
|
||||
publicOnly = false,
|
||||
): Promise<Response> {
|
||||
let url = registryHttpsUrl(value);
|
||||
for (let redirects = 0; redirects <= 5; redirects++) {
|
||||
const response = await fetch(url.href, { signal, redirect: "manual" });
|
||||
const response = publicOnly
|
||||
? await publicRegistryRequest(url, signal)
|
||||
: await fetch(url.href, { signal, redirect: "manual" });
|
||||
if (![301, 302, 303, 307, 308].includes(response.status)) return response;
|
||||
const location = response.headers.get("location");
|
||||
await response.body?.cancel();
|
||||
@@ -41,3 +49,15 @@ export async function fetchRegistryHttps(value: string, signal: AbortSignal): Pr
|
||||
}
|
||||
throw new Error("Too many registry redirects");
|
||||
}
|
||||
|
||||
async function publicRegistryRequest(url: URL, signal: AbortSignal): Promise<Response> {
|
||||
try {
|
||||
return await publicRequest(url, { signal }, null);
|
||||
} catch (error) {
|
||||
if (!(error instanceof NonPublicHostError)) throw error;
|
||||
throw new Error(
|
||||
`${url.host} is not a public address. The registry in a received hyperframes.json is only fetched from public addresses.`,
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { createServer, type AddressInfo } from "node:net";
|
||||
import { trackRegistryItemAdded } from "../telemetry/events.js";
|
||||
import { createStudioServer, type StudioServer } from "./studioServer.js";
|
||||
|
||||
@@ -200,6 +201,31 @@ describe("Studio catalog install", () => {
|
||||
expect(fetched.every((url) => url.startsWith(registry))).toBe(true);
|
||||
});
|
||||
|
||||
// fails without the fix: the panel listed a received project's registry from any host
|
||||
it("lists nothing from a received project's registry on a private address, and connects to none", async () => {
|
||||
let connections = 0;
|
||||
const listener = createServer((socket) => {
|
||||
connections += 1;
|
||||
socket.destroy();
|
||||
});
|
||||
await new Promise<void>((done) => listener.listen(0, "127.0.0.1", done));
|
||||
const { real, fetched } = projectWithRegistry();
|
||||
const registry = `https://127.0.0.1:${(listener.address() as AddressInfo).port}/r`;
|
||||
writeFileSync(join(real, "hyperframes.json"), JSON.stringify({ registry }));
|
||||
mkdirSync(join(real, ".hyperframes"), { recursive: true });
|
||||
writeFileSync(
|
||||
join(real, ".hyperframes", "received-files.json"),
|
||||
JSON.stringify({ files: ["hyperframes.json"] }),
|
||||
);
|
||||
try {
|
||||
expect(await server!.adapter.listRegistryCatalog!()).toEqual([]);
|
||||
expect(connections).toBe(0);
|
||||
expect(fetched.filter((url) => url.startsWith(registry))).toEqual([]);
|
||||
} finally {
|
||||
listener.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("installs a block sized unlike the project twice, and leaves a real edit alone", async () => {
|
||||
const { link, real } = projectWithRegistry();
|
||||
const install = installer(link);
|
||||
|
||||
@@ -946,8 +946,10 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
|
||||
async listRegistryCatalog() {
|
||||
const { listRegistryItems, loadAllItems } = await import("../registry/resolver.js");
|
||||
const { loadProjectConfig } = await import("../utils/projectConfig.js");
|
||||
const { fromReceivedRegistry } = await import("../commands/add.js");
|
||||
// The same registry `add` installs from, so the panel lists what can be installed.
|
||||
const registry = { baseUrl: loadProjectConfig(projectDir).registry };
|
||||
const baseUrl = loadProjectConfig(projectDir).registry;
|
||||
const registry = { baseUrl, publicOnly: fromReceivedRegistry(projectDir, baseUrl) };
|
||||
const entries = await listRegistryItems(undefined, registry);
|
||||
const blockAndComponentEntries = entries.filter(
|
||||
(e) => e.type === "hyperframes:block" || e.type === "hyperframes:component",
|
||||
|
||||
@@ -231,6 +231,23 @@ describe("pinned request", () => {
|
||||
expect(response.status).toBe(302);
|
||||
expect(await response.text()).toBe("redirect");
|
||||
});
|
||||
// fails without the fix: a set capture proxy took the request, so no address here was checked or pinned
|
||||
it("checks and pins the address itself when told to use no proxy, even with one configured", async () => {
|
||||
vi.stubEnv("HYPERFRAMES_CAPTURE_PROXY", "http://127.0.0.1:3128");
|
||||
try {
|
||||
mocks.resolve4.mockResolvedValueOnce(["10.0.0.1"]);
|
||||
await expect(publicRequest("https://example.com/", {}, null)).rejects.toThrow(
|
||||
NonPublicHostError,
|
||||
);
|
||||
expect(mocks.request).not.toHaveBeenCalled();
|
||||
mocks.resolve4.mockResolvedValueOnce(["8.8.8.8"]);
|
||||
fakeRequest();
|
||||
await publicRequest("https://example.com/", {}, null);
|
||||
expect(mocks.request.mock.calls[0]?.[0]).toMatchObject({ hostname: "8.8.8.8" });
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
}
|
||||
});
|
||||
it.each(["file:///tmp/a", "http://user:secret@example.com"])(
|
||||
"rejects unsafe URL %s",
|
||||
async (url) => {
|
||||
|
||||
@@ -234,7 +234,11 @@ async function upstreamRoute(
|
||||
}
|
||||
|
||||
/** Pinned asset transport, or the opt-in upstream proxy; redirects are returned for caller validation. */
|
||||
export async function publicRequest(url: string | URL, init: RequestInit = {}): Promise<Response> {
|
||||
export async function publicRequest(
|
||||
url: string | URL,
|
||||
init: RequestInit = {},
|
||||
upstream: UpstreamProxy | null = captureUpstreamProxy() ?? null,
|
||||
): Promise<Response> {
|
||||
const target = new URL(url);
|
||||
if (!["http:", "https:"].includes(target.protocol) || target.username || target.password) {
|
||||
throw new Error("Capture requires an HTTP(S) URL without credentials");
|
||||
@@ -258,9 +262,8 @@ export async function publicRequest(url: string | URL, init: RequestInit = {}):
|
||||
headers.delete(name);
|
||||
headers.set("host", target.host);
|
||||
headers.set("accept-encoding", "identity");
|
||||
const proxy = captureUpstreamProxy();
|
||||
const { options, tunnel } = proxy
|
||||
? await upstreamRoute(target, proxy, headers, signal)
|
||||
const { options, tunnel } = upstream
|
||||
? await upstreamRoute(target, upstream, headers, signal)
|
||||
: await pinnedRoute(target, signal);
|
||||
return new Promise<Response>((resolve, reject) => {
|
||||
const request = target.protocol === "https:" ? httpsRequest : httpRequest;
|
||||
|
||||
Reference in New Issue
Block a user