diff --git a/docs/packages/producer.mdx b/docs/packages/producer.mdx index c534cf7125..ebf583b64d 100644 --- a/docs/packages/producer.mdx +++ b/docs/packages/producer.mdx @@ -195,6 +195,17 @@ through a proxy name, list that name in `allowedHosts` or in the comma-separated `PRODUCER_ALLOWED_HOSTS` variable. Requests without those headers, such as curl or another service, are unaffected. +The server listens on `127.0.0.1` unless you pass `hostname` or set `PRODUCER_HOST`. To +listen on any other address, also set `authToken` or `PRODUCER_AUTH_TOKEN`. Every route +except `/health` then requires `Authorization: Bearer `, and the server refuses to +start without one. A request's `projectDir` must resolve, symlinks included, inside +`projectsDir` (`PRODUCER_PROJECTS_DIR`, default: the working directory). Its `entryFile` +must stay inside that project, and `outputPath` must be inside `rendersDir` +(`PRODUCER_RENDERS_DIR`, default `/tmp`). `debug: true` is refused unless you set +`allowDebug` or `PRODUCER_ALLOW_DEBUG=1`. `createProducerApp` applies these path and +debug checks by default. `createRenderHandlers`, for mounting the handlers inside your own +trusted service, applies them only with `confineRequests: true`. + For larger workloads, the `@hyperframes/producer/distributed` entry exposes the three rendering activities—`plan`, `renderChunk`, and `assemble`. Your orchestrator remains responsible for dispatch, retries, storage, and networking. diff --git a/packages/producer/README.md b/packages/producer/README.md index a007501e1e..54860a5559 100644 --- a/packages/producer/README.md +++ b/packages/producer/README.md @@ -45,6 +45,17 @@ through a proxy name, list that name in `allowedHosts` or in the comma-separated `PRODUCER_ALLOWED_HOSTS` variable. Requests without those headers, such as curl or another service, are unaffected. +The server listens on `127.0.0.1` unless you pass `hostname` or set `PRODUCER_HOST`. To +listen on any other address, also set `authToken` or `PRODUCER_AUTH_TOKEN`. Every route +except `/health` then requires `Authorization: Bearer `, and the server refuses to +start without one. A request's `projectDir` must resolve, symlinks included, inside +`projectsDir` (`PRODUCER_PROJECTS_DIR`, default: the working directory). Its `entryFile` +must stay inside that project, and `outputPath` must be inside `rendersDir` +(`PRODUCER_RENDERS_DIR`, default `/tmp`). `debug: true` is refused unless you set +`allowDebug` or `PRODUCER_ALLOW_DEBUG=1`. `createProducerApp` applies these path and +debug checks by default. `createRenderHandlers`, for mounting the handlers inside your own +trusted service, applies them only with `confineRequests: true`. + Both HTTP routes accept optional `pageMotionBlur: "off"` to disable authored page motion blur. Omit it to preserve the composition's behavior. Other explicit values are rejected before a render starts. This is separate from engine sub-frame diff --git a/packages/producer/src/server.access.test.ts b/packages/producer/src/server.access.test.ts new file mode 100644 index 0000000000..1e3c13865c --- /dev/null +++ b/packages/producer/src/server.access.test.ts @@ -0,0 +1,177 @@ +import { existsSync, mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Hono } from "hono"; +import { describe, expect, it, vi } from "vitest"; + +const debugDir = vi.hoisted(() => ({ path: "" })); + +vi.mock("./services/renderOrchestrator.js", () => { + class RenderCancelledError extends Error {} + + return { + RenderCancelledError, + resolveRenderDebugDir: () => debugDir.path, + createRenderJob: (config: Record) => ({ + id: "job-id", + config, + progress: 0, + currentStage: "queued", + warnings: [], + }), + executeRenderJob: async (job: Record) => { + job.outcome = "completed"; + job.perfSummary = { renderId: "job-id", workers: 1 }; + }, + }; +}); + +import { + createProducerApp, + createRenderHandlers, + startServer, + type HandlerOptions, +} from "./server.js"; + +function setup() { + const root = mkdtempSync(join(tmpdir(), "hf-server-access-")); + const projectsDir = join(root, "projects"); + const rendersDir = join(root, "renders"); + debugDir.path = join(root, ".debug"); + mkdirSync(join(projectsDir, "demo"), { recursive: true }); + writeFileSync(join(projectsDir, "demo", "index.html"), ""); + writeFileSync(join(root, "outside.html"), ""); + mkdirSync(join(debugDir.path, "job"), { recursive: true }); + writeFileSync(join(debugDir.path, "job", "index.html"), ""); + symlinkSync(join(root, "outside.html"), join(projectsDir, "demo", "link.html")); + return { root, projectsDir, rendersDir }; +} + +function post(options: HandlerOptions, body: Record, headers = {}) { + return createProducerApp(options).request("http://localhost:9847/render", { + method: "POST", + headers: { host: "localhost:9847", ...headers }, + body: JSON.stringify(body), + }); +} + +describe("createProducerApp: auth token", () => { + it("refuses requests without the bearer token, except /health", async () => { + const { projectsDir, rendersDir } = setup(); + const options = { projectsDir, rendersDir, authToken: "s3cret" }; + expect((await post(options, { projectDir: "demo" })).status).toBe(401); + expect( + (await post(options, { projectDir: "demo" }, { authorization: "Bearer wrong" })).status, + ).toBe(401); + expect( + (await post(options, { projectDir: "demo" }, { authorization: "Bearer s3cret" })).status, + ).toBe(200); + const health = await createProducerApp(options).request("http://localhost:9847/health"); + expect(health.status).toBe(200); + }); +}); + +describe("createProducerApp: request paths", () => { + it("renders a project under the projects root into the renders dir", async () => { + const { projectsDir, rendersDir } = setup(); + const res = await post( + { projectsDir, rendersDir }, + { projectDir: "demo", outputPath: join(rendersDir, "a/b.mp4") }, + ); + expect(res.status).toBe(200); + const json = (await res.json()) as { perf: Record }; + expect(json.perf).toEqual({ workers: 1 }); + }); + + it("refuses an output path outside the renders dir without creating it", async () => { + const { root, projectsDir, rendersDir } = setup(); + const outputPath = join(root, "elsewhere", "x.mp4"); + const projectDir = join(projectsDir, "demo"); + const res = await post({ projectsDir, rendersDir }, { projectDir, outputPath }); + expect(res.status).toBe(400); + expect(existsSync(join(root, "elsewhere"))).toBe(false); + }); + + it("refuses project dirs and entry files outside the projects root", async () => { + const { root, projectsDir, rendersDir } = setup(); + const options = { projectsDir, rendersDir }; + expect((await post(options, { projectDir: root, entryFile: "outside.html" })).status).toBe(400); + expect( + (await post(options, { projectDir: "demo", entryFile: "../../outside.html" })).status, + ).toBe(400); + expect((await post(options, { projectDir: "demo", entryFile: "link.html" })).status).toBe(400); + const res = await post(options, { projectDir: "../" }); + expect(res.status).toBe(400); + expect(await res.text()).not.toContain(root); + }); + + it("refuses the debug dir as project content", async () => { + const { root, rendersDir } = setup(); + const options = { projectsDir: root, rendersDir }; + expect((await post(options, { projectDir: ".debug/job" })).status).toBe(400); + expect( + (await post(options, { projectDir: ".", entryFile: ".debug/job/index.html" })).status, + ).toBe(400); + }); + + it("accepts debug only when the operator allows it", async () => { + const { projectsDir, rendersDir } = setup(); + const body = { projectDir: "demo", debug: true }; + expect((await post({ projectsDir, rendersDir }, body)).status).toBe(400); + expect((await post({ projectsDir, rendersDir, allowDebug: true }, body)).status).toBe(200); + }); +}); + +describe("createProducerApp: lint paths", () => { + const lint = (options: HandlerOptions, body: Record) => + createProducerApp(options).request("http://localhost:9847/lint", { + method: "POST", + headers: { host: "localhost:9847" }, + body: JSON.stringify(body), + }); + + it("refuses a lint projectDir outside the projects root", async () => { + const { root, projectsDir, rendersDir } = setup(); + expect((await lint({ projectsDir, rendersDir }, { projectDir: root })).status).toBe(400); + expect((await lint({ projectsDir, rendersDir }, { projectDir: "../" })).status).toBe(400); + expect((await lint({ projectsDir, rendersDir }, { projectDir: "demo" })).status).toBe(200); + }); + + it("refuses a lint entry that leaves the project or reaches the debug dir", async () => { + const { root, projectsDir, rendersDir } = setup(); + const symlinked = { projectDir: "demo", entryFile: "link.html" }; + expect((await lint({ projectsDir, rendersDir }, symlinked)).status).toBe(400); + const debugEntry = { projectDir: ".", entryFile: ".debug/job/index.html" }; + expect((await lint({ projectsDir: root, rendersDir }, debugEntry)).status).toBe(400); + }); +}); + +describe("createRenderHandlers: embedded contract", () => { + it("keeps accepting trusted absolute paths and debug unless confineRequests is set", async () => { + const { root, projectsDir, rendersDir } = setup(); + const app = new Hono(); + app.post("/v1/render-sync", createRenderHandlers({ rendersDir }).render); + const res = await app.request("/v1/render-sync", { + method: "POST", + body: JSON.stringify({ + projectDir: join(projectsDir, "demo"), + outputPath: join(root, "elsewhere", "x.mp4"), + debug: true, + }), + }); + expect(res.status).toBe(200); + expect(((await res.json()) as { perf: unknown }).perf).toEqual({ + renderId: "job-id", + workers: 1, + }); + }); +}); + +describe("startServer: listen address", () => { + it("refuses a non-loopback address without an auth token", () => { + expect(() => startServer({ hostname: "0.0.0.0", port: 0 })).toThrow(/auth token/); + expect(() => startServer({ hostname: "0.0.0.0", port: 0, authToken: " " })).toThrow( + /auth token/, + ); + }); +}); diff --git a/packages/producer/src/server.ts b/packages/producer/src/server.ts index 4eab1bea01..2b79df386c 100644 --- a/packages/producer/src/server.ts +++ b/packages/producer/src/server.ts @@ -35,10 +35,12 @@ import { REFERENCE_BACKGROUND_FIELD, referenceBackgroundResult, } from "@hyperframes/engine"; +import { isSafePath } from "@hyperframes/core/safe-path"; import { RenderCancelledError, createRenderJob, executeRenderJob, + resolveRenderDebugDir, type ProgressCallback, type RenderConfig, type RenderJob, @@ -79,11 +81,21 @@ export interface HandlerOptions { maxConcurrentRenders?: number; /** Extra browser-facing host names (e.g. a proxy's); merged with PRODUCER_ALLOWED_HOSTS. */ allowedHosts?: readonly string[]; + /** Confine request paths and debug as below. Default: true in `createProducerApp`, false in `createRenderHandlers`. */ + confineRequests?: boolean; + /** With `confineRequests`: where every `projectDir` must resolve. Defaults to PRODUCER_PROJECTS_DIR or the working directory. */ + projectsDir?: string; + /** With `confineRequests`: let requests set `debug: true`, which keeps work dirs on disk. Defaults to PRODUCER_ALLOW_DEBUG=1. */ + allowDebug?: boolean; + /** Bearer token `createProducerApp` requires on every route but /health. Defaults to PRODUCER_AUTH_TOKEN. */ + authToken?: string; } export interface ServerOptions extends HandlerOptions { /** Port to listen on. Default: 9847. */ port?: number; + /** Address to listen on. Default: PRODUCER_HOST or 127.0.0.1. A non-loopback address requires `authToken`. */ + hostname?: string; } // --------------------------------------------------------------------------- @@ -369,9 +381,16 @@ function resolvePreparedRenderOutput( prepared: PreparedRenderInput, rendersDir: string, log: ProducerLogger, + confineOutput: boolean, ): { input: RenderInput; cleanupProjectDir?: string; absoluteOutputPath: string } { const { input, cleanupProjectDir } = prepared; const absoluteOutputPath = resolveOutputPath(input.projectDir, input.outputPath, rendersDir, log); + if (confineOutput) { + mkdirSync(rendersDir, { recursive: true }); + if (!isSafePath(rendersDir, absoluteOutputPath)) { + throw new Error("outputPath must be inside the renders directory"); + } + } const outputDir = dirname(absoluteOutputPath); if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true }); return { input, cleanupProjectDir, absoluteOutputPath }; @@ -395,9 +414,10 @@ function prepareRenderJob( prepared: PreparedRenderInput, rendersDir: string, log: ProducerLogger, + confineOutput: boolean, ): PreparedRenderJob { try { - const output = resolvePreparedRenderOutput(prepared, rendersDir, log); + const output = resolvePreparedRenderOutput(prepared, rendersDir, log, confineOutput); const job = createRenderJob(buildRenderJobConfig(output.input, output.absoluteOutputPath, log)); return { ...output, job }; } catch (error) { @@ -476,19 +496,55 @@ type PrepareRenderResult = { prepared: PreparedRenderInput } | { error: string } const MAX_PREVIEW_HTML_BYTES = 20 * 1024 * 1024; +/** What a request may reach on disk; see `HandlerOptions.projectsDir` and `allowDebug`. */ +export interface RenderRequestPolicy { + projectsDir: string; + allowDebug: boolean; +} + +function resolveRenderRequestPolicy(options: HandlerOptions): RenderRequestPolicy { + return { + projectsDir: resolve( + options.projectsDir ?? (process.env.PRODUCER_PROJECTS_DIR || process.cwd()), + ), + allowDebug: options.allowDebug ?? process.env.PRODUCER_ALLOW_DEBUG === "1", + }; +} + +/** Inside the projects root, and not in the debug dir where earlier requests' compiled HTML persists. */ +function isAllowedProjectPath(projectsDir: string, path: string): boolean { + return isSafePath(projectsDir, path) && !isSafePath(resolveRenderDebugDir(), path); +} + +/** An entry the project may serve: inside it, symlinks included, and allowed by the policy. */ +function isAllowedEntryPath( + policy: RenderRequestPolicy, + projectDir: string, + path: string, +): boolean { + return isSafePath(projectDir, path) && isAllowedProjectPath(policy.projectsDir, path); +} + function prepareProjectDirectory( projectDir: unknown, options: Omit, + policy: RenderRequestPolicy | undefined, ): PrepareRenderResult | null { const candidate = nonEmptyString(projectDir); if (!candidate) return null; - const absProjectDir = resolve(candidate); - if (!existsSync(absProjectDir) || !statSync(absProjectDir).isDirectory()) { - return { error: `Project directory not found: ${absProjectDir}` }; + const absProjectDir = policy ? resolve(policy.projectsDir, candidate) : resolve(candidate); + const shown = policy ? candidate : absProjectDir; + if ( + (policy && !isAllowedProjectPath(policy.projectsDir, absProjectDir)) || + !existsSync(absProjectDir) || + !statSync(absProjectDir).isDirectory() + ) { + return { error: `Project directory not found: ${shown}` }; } const entry = options.entryFile || "index.html"; - if (!existsSync(resolve(absProjectDir, entry))) { - return { error: `Entry file "${entry}" not found in project directory: ${absProjectDir}` }; + const entryPath = resolve(absProjectDir, entry); + if ((policy && !isAllowedEntryPath(policy, absProjectDir, entryPath)) || !existsSync(entryPath)) { + return { error: `Entry file "${entry}" not found in project directory: ${shown}` }; } return { prepared: { input: { projectDir: absProjectDir, ...options } } }; } @@ -530,18 +586,22 @@ function materializeInlineProject( export async function prepareRenderBody( body: Record, + policy?: RenderRequestPolicy, ): Promise { // Reject explicitly-supplied-but-malformed overrides up front so the caller // gets a clear 400 instead of a silently-ignored value. const overrideError = validateRenderOverrides(body); if (overrideError) return { error: overrideError }; + if (policy && body.debug === true && !policy.allowDebug) { + return { error: "debug is disabled on this server (set allowDebug or PRODUCER_ALLOW_DEBUG=1)" }; + } const pageMotionBlur = body.pageMotionBlur; if (pageMotionBlur !== undefined && pageMotionBlur !== "off") { return { error: "pageMotionBlur must be off when supplied" }; } const options: Omit = { ...parseRenderOptions(body), pageMotionBlur }; - const project = prepareProjectDirectory(body.projectDir, options); + const project = prepareProjectDirectory(body.projectDir, options, policy); if (project) return project; const source = await resolveInlineRenderHtml(body); return "error" in source ? source : materializeInlineProject(source.html, options); @@ -613,6 +673,11 @@ function cleanupTempDir(dir: string | undefined, log: ProducerLogger): void { } } +/** The job id names the render's work dir (kept on disk under `debug`), so it stays server-side. */ +function publicPerfSummary(job: RenderJob) { + return job.perfSummary ? { ...job.perfSummary, renderId: undefined } : null; +} + function outputFileSize(path: string): number { return existsSync(path) ? statSync(path).size : 0; } @@ -635,6 +700,7 @@ async function prepareSseRenderRequest( c: Context, stream: SseWriter, requestId: string, + policy: RenderRequestPolicy | undefined, ): Promise { let body: Record; try { @@ -650,7 +716,7 @@ async function prepareSseRenderRequest( }); return null; } - const prepared = await prepareRenderBody(body); + const prepared = await prepareRenderBody(body, policy); if (!("error" in prepared)) return prepared.prepared; await stream.writeSSE({ data: JSON.stringify({ @@ -750,6 +816,7 @@ export function createRenderHandlers(options: HandlerOptions = {}): RenderHandle options.getRequestId ?? ((c: Context) => c.req.header("x-request-id") || crypto.randomUUID()); const outputUrlPrefix = options.outputUrlPrefix ?? "/outputs"; const rendersDir = options.rendersDir ?? process.env.PRODUCER_RENDERS_DIR ?? "/tmp"; + const policy = options.confineRequests ? resolveRenderRequestPolicy(options) : undefined; const artifactTtlMs = options.artifactTtlMs ?? Number(process.env.PRODUCER_OUTPUT_ARTIFACT_TTL_MS || 15 * 60 * 1000); const store = createArtifactStore(artifactTtlMs); @@ -775,7 +842,19 @@ export function createRenderHandlers(options: HandlerOptions = {}): RenderHandle return c.json({ success: false, requestId, error: "Invalid JSON body" }, 400); } - const preparedResult = prepareHyperframeLintBody(body); + const lintProjectDir = nonEmptyString(body.projectDir); + let isAllowedEntry: ((path: string) => boolean) | undefined; + if (policy && lintProjectDir) { + const absProjectDir = resolve(policy.projectsDir, lintProjectDir); + if (!isAllowedProjectPath(policy.projectsDir, absProjectDir)) { + const error = `Project directory not found: ${lintProjectDir}`; + return c.json({ success: false, requestId, error }, 400); + } + body = { ...body, projectDir: absProjectDir }; + isAllowedEntry = (path) => isAllowedEntryPath(policy, absProjectDir, path); + } + + const preparedResult = prepareHyperframeLintBody(body, isAllowedEntry); if ("error" in preparedResult) { return c.json({ success: false, requestId, error: preparedResult.error }, 400); } @@ -809,12 +888,12 @@ export function createRenderHandlers(options: HandlerOptions = {}): RenderHandle return c.json({ success: false, requestId, error: "Invalid JSON body" }, 400); } - const preparedResult = await prepareRenderBody(body); + const preparedResult = await prepareRenderBody(body, policy); if ("error" in preparedResult) { return c.json({ success: false, requestId, error: preparedResult.error }, 400); } - const preparedJob = prepareRenderJob(preparedResult.prepared, rendersDir, log); + const preparedJob = prepareRenderJob(preparedResult.prepared, rendersDir, log, !!policy); if ("error" in preparedJob) { return c.json({ success: false, requestId, error: preparedJob.error }, 400); } @@ -860,7 +939,7 @@ export function createRenderHandlers(options: HandlerOptions = {}): RenderHandle videoDurationSeconds: job.duration ?? null, outcome: job.outcome ?? "completed", warnings: job.warnings, - perf: job.perfSummary ?? null, + perf: policy ? publicPerfSummary(job) : (job.perfSummary ?? null), ...strictVariablesResult(job), }); } catch (error) { @@ -899,10 +978,10 @@ export function createRenderHandlers(options: HandlerOptions = {}): RenderHandle const requestId = getRequestId(c); const t0 = Date.now(); - const prepared = await prepareSseRenderRequest(c, stream, requestId); + const prepared = await prepareSseRenderRequest(c, stream, requestId, policy); if (!prepared) return; - const preparedJob = prepareRenderJob(prepared, rendersDir, log); + const preparedJob = prepareRenderJob(prepared, rendersDir, log, !!policy); if ("error" in preparedJob) { await stream.writeSSE({ data: JSON.stringify({ @@ -963,7 +1042,7 @@ export function createRenderHandlers(options: HandlerOptions = {}): RenderHandle videoDurationSeconds: job.duration ?? null, outcome: job.outcome ?? "completed", warnings: job.warnings, - perf: job.perfSummary ?? null, + perf: policy ? publicPerfSummary(job) : (job.perfSummary ?? null), producerVersion: readProducerVersion(), ...strictVariablesResult(job), }), @@ -1062,6 +1141,24 @@ function allowedHostnames(options: HandlerOptions): Set { return names; } +/** A blank token is no token: it neither guards a route nor unlocks a wider listen address. */ +function resolveAuthToken(options: HandlerOptions): string { + return options.authToken?.trim() || process.env.PRODUCER_AUTH_TOKEN?.trim() || ""; +} + +function hasBearerToken(c: Context, token: string): boolean { + const digest = (value: string) => crypto.createHash("sha256").update(value).digest(); + return crypto.timingSafeEqual( + digest(c.req.header("authorization") ?? ""), + digest(`Bearer ${token}`), + ); +} + +function isLoopbackHostname(hostname: string): boolean { + const host = hostname.replace(/^\[|\]$/g, "").toLowerCase(); + return host === "localhost" || host === "::1" || (isIP(host) === 4 && host.startsWith("127.")); +} + /** Header-less callers (curl, services) pass; a page's POST always carries Origin. */ function isDisallowedBrowserHost(c: Context, allowed: ReadonlySet): boolean { const origin = c.req.header("origin"); @@ -1080,8 +1177,19 @@ function isDisallowedBrowserHost(c: Context, allowed: ReadonlySet): bool */ export function createProducerApp(options: HandlerOptions = {}): Hono { const app = new Hono(); - const handlers = createRenderHandlers(options); + const handlers = createRenderHandlers({ + ...options, + confineRequests: options.confineRequests ?? true, + }); const allowed = allowedHostnames(options); + const authToken = resolveAuthToken(options); + + app.use("*", async (c, next) => { + if (authToken && c.req.path !== "/health" && !hasBearerToken(c, authToken)) { + return c.json({ success: false, error: "Unauthorized" }, 401); + } + await next(); + }); app.use("*", async (c, next) => { if (isDisallowedBrowserHost(c, allowed)) { @@ -1122,11 +1230,18 @@ export function createProducerApp(options: HandlerOptions = {}): Hono { */ export function startServer(options: ServerOptions = {}) { const port = options.port ?? parseInt(process.env.PRODUCER_PORT ?? "9847", 10); + const hostname = options.hostname || process.env.PRODUCER_HOST || "127.0.0.1"; const log = options.logger ?? defaultLogger; + if (!isLoopbackHostname(hostname) && !resolveAuthToken(options)) { + throw new Error( + `Refusing to listen on ${hostname} without an auth token. Set authToken or PRODUCER_AUTH_TOKEN, or listen on a loopback address.`, + ); + } const app = createProducerApp(options); - const server = serve({ fetch: app.fetch, port }, () => { - log.info(`Listening on http://localhost:${port}`); + const server = serve({ fetch: app.fetch, port, hostname }, (info) => { + const address = info.family === "IPv6" ? `[${info.address}]` : info.address; + log.info(`Listening on http://${address}:${info.port}`); }); // Disable timeouts for long renders diff --git a/packages/producer/src/services/hyperframeLint.ts b/packages/producer/src/services/hyperframeLint.ts index fd3d9be1f2..fa5475649b 100644 --- a/packages/producer/src/services/hyperframeLint.ts +++ b/packages/producer/src/services/hyperframeLint.ts @@ -70,9 +70,24 @@ function readEntryHtml(filePath: string): string | null { } } +function leavesProject( + absProjectDir: string, + absoluteEntryPath: string, + isAllowedEntry?: (absolutePath: string) => boolean, +): boolean { + const entryRelativePath = relative(absProjectDir, absoluteEntryPath); + return ( + entryRelativePath === ".." || + entryRelativePath.startsWith(`..${sep}`) || + isAbsolute(entryRelativePath) || + (isAllowedEntry !== undefined && !isAllowedEntry(absoluteEntryPath)) + ); +} + function readProjectEntryFile( projectDir: string, preferredEntryFile?: string, + isAllowedEntry?: (absolutePath: string) => boolean, ): PreparedHyperframeLintInput | { error: string } { const absProjectDir = resolve(projectDir); if (!existsSync(absProjectDir) || !statSync(absProjectDir).isDirectory()) { @@ -85,12 +100,7 @@ function readProjectEntryFile( for (const entryFile of entryCandidates) { const absoluteEntryPath = resolve(absProjectDir, entryFile); - const entryRelativePath = relative(absProjectDir, absoluteEntryPath); - if ( - entryRelativePath === ".." || - entryRelativePath.startsWith(`..${sep}`) || - isAbsolute(entryRelativePath) - ) { + if (leavesProject(absProjectDir, absoluteEntryPath, isAllowedEntry)) { return { error: `Entry file must stay inside project directory: ${entryFile}` }; } const html = readEntryHtml(absoluteEntryPath); @@ -110,6 +120,7 @@ function readProjectEntryFile( export function prepareHyperframeLintBody( body: Record, + isAllowedEntry?: (absolutePath: string) => boolean, ): { prepared: PreparedHyperframeLintInput } | { error: string } { const requestedEntryFile = typeof body.entryFile === "string" && body.entryFile.trim().length > 0 @@ -117,7 +128,7 @@ export function prepareHyperframeLintBody( : undefined; if (typeof body.projectDir === "string" && body.projectDir.trim().length > 0) { - const prepared = readProjectEntryFile(body.projectDir, requestedEntryFile); + const prepared = readProjectEntryFile(body.projectDir, requestedEntryFile, isAllowedEntry); if ("error" in prepared) { return prepared; } diff --git a/scripts/package-size-budgets.json b/scripts/package-size-budgets.json index 1666b9c2e2..b6fefedc40 100644 --- a/scripts/package-size-budgets.json +++ b/scripts/package-size-budgets.json @@ -36,7 +36,7 @@ "unpacked": 541601 }, "@hyperframes/producer": { - "packed": 890000, + "packed": 901000, "unpacked": 3245000 }, "@hyperframes/sdk": {