@hyperframes/producer 0.9.52 → 0.9.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,6 +13,7 @@ import {
13
13
  import { resolve as resolve10, dirname as dirname16, join as join37 } from "node:path";
14
14
  import { tmpdir as tmpdir3 } from "node:os";
15
15
  import { parseArgs } from "node:util";
16
+ import { isIP } from "node:net";
16
17
  import crypto from "node:crypto";
17
18
  import { Hono as Hono2 } from "hono";
18
19
  import { streamSSE } from "hono/streaming";
@@ -22,6 +23,7 @@ import {
22
23
  REFERENCE_BACKGROUND_FIELD as REFERENCE_BACKGROUND_FIELD3,
23
24
  referenceBackgroundResult as referenceBackgroundResult5
24
25
  } from "@hyperframes/engine";
26
+ import { isSafePath as isSafePath3 } from "@hyperframes/core/safe-path";
25
27
 
26
28
  // src/services/renderOrchestrator.ts
27
29
  import { audioFailureDiagnostics as audioFailureDiagnostics2 } from "@hyperframes/engine";
@@ -332,6 +334,7 @@ var MIME_TYPES = {
332
334
  ".css": "text/css; charset=utf-8",
333
335
  ".js": "application/javascript; charset=utf-8",
334
336
  ".mjs": "application/javascript; charset=utf-8",
337
+ ".cjs": "application/javascript; charset=utf-8",
335
338
  ".json": "application/json; charset=utf-8",
336
339
  ".cube": "text/plain; charset=utf-8",
337
340
  ".png": "image/png",
@@ -875,6 +878,10 @@ function createFileServer(options) {
875
878
  const bodyScripts = options.bodyScripts ?? [buildRenderModeScript(options.fps), HF_BRIDGE_SCRIPT];
876
879
  const app = new Hono();
877
880
  const warnLeftOut = (line) => console.warn(`[FileServer] ${line}`);
881
+ app.use(async function loadEachFileOnlyAsItsNamedType(c, next) {
882
+ await next();
883
+ c.res.headers.set("X-Content-Type-Options", "nosniff");
884
+ });
878
885
  app.get("/*", async (c) => {
879
886
  let requestPath = c.req.path;
880
887
  if (requestPath === "/") requestPath = "/index.html";
@@ -1133,6 +1140,9 @@ import {
1133
1140
  import {
1134
1141
  mediaIdPathSegment
1135
1142
  } from "@hyperframes/engine";
1143
+ function audioWorkDir(workDir) {
1144
+ return join3(workDir, "audio-work");
1145
+ }
1136
1146
  var BROWSER_MEDIA_EPSILON = 1e-4;
1137
1147
  function resolveBrowserMediaEnd(start, end, duration) {
1138
1148
  return Number.isFinite(duration) && duration > 0 ? start + duration : end;
@@ -6529,12 +6539,26 @@ function countAuthoredTimedClips(html) {
6529
6539
  // src/services/render/stages/compileStage.ts
6530
6540
  import { existsSync as existsSync12, writeFileSync as writeFileSync5 } from "node:fs";
6531
6541
  import { join as join20, relative as relative3 } from "node:path";
6542
+ import { privateCacheRoot } from "@hyperframes/engine";
6532
6543
  import { suggestMatchingPreset } from "@hyperframes/core";
6533
6544
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
6534
6545
  import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolution";
6535
6546
 
6536
6547
  // src/services/htmlCompiler.ts
6537
6548
  import { decodedUrlPath } from "@hyperframes/parsers/asset-paths";
6549
+ import {
6550
+ cssRuleMatches,
6551
+ cssUrlMatches,
6552
+ fontFaceBlockMatches,
6553
+ hasBackgroundImageDeclaration,
6554
+ importRuleMatches,
6555
+ localFontFaceUrlMatches,
6556
+ remoteBackgroundUrlMatches,
6557
+ remoteFontFaceUrlMatches,
6558
+ replaceMatches,
6559
+ styleBlockMatches,
6560
+ stylesheetLinkMatches
6561
+ } from "@hyperframes/parsers/css-url-scans";
6538
6562
  import { createHash as createHash6 } from "node:crypto";
6539
6563
  import { createReadStream as createReadStream2, existsSync as existsSync11, mkdirSync as mkdirSync9, readFileSync as readFileSync8 } from "fs";
6540
6564
  import { join as join19, dirname as dirname8, resolve as resolve7, basename as basename5, relative as relative2, sep as sep3 } from "path";
@@ -6560,7 +6584,6 @@ import {
6560
6584
  extractResolvedMedia,
6561
6585
  clampDurations,
6562
6586
  shouldClampResolvedMediaDuration,
6563
- CSS_URL_RE,
6564
6587
  isNonRelativeUrl,
6565
6588
  parseStrictFiniteTimingNumber,
6566
6589
  readMediaStart,
@@ -7638,10 +7661,16 @@ function normalizeCompositionSrcs(html, projectDir) {
7638
7661
  return `${name}${quote}${relative2(projectDir, file).split(sep3).join("/")}${quote}`;
7639
7662
  });
7640
7663
  }
7641
- function resolveCompositionFile(projectDir, src, assetRoot) {
7664
+ var COMPOSITION_FILE = /\.html?$/i;
7665
+ var NOT_A_COMPOSITION_FILE = "it is not an .html file, so it is refused";
7666
+ function resolveCompositionPath(projectDir, src, assetRoot) {
7642
7667
  const file = resolveCompositionSrc(projectDir, src);
7643
7668
  return file === null || escapesAssetRoot(file, assetRoot) ? null : file;
7644
7669
  }
7670
+ function resolveCompositionFile(projectDir, src, assetRoot) {
7671
+ const file = resolveCompositionPath(projectDir, src, assetRoot);
7672
+ return file !== null && COMPOSITION_FILE.test(file) ? file : null;
7673
+ }
7645
7674
  var isPrivateCompositionFile = (projectDir, filePath) => isPrivateFileUnder2(projectDir, filePath, isVcsOrSecretPath2);
7646
7675
  function assertSubCompositionsUsable(html, projectDir, assetRoot, visited = /* @__PURE__ */ new Set()) {
7647
7676
  const { document: document2 } = parseHTML5(html);
@@ -7651,7 +7680,7 @@ function assertSubCompositionsUsable(html, projectDir, assetRoot, visited = /* @
7651
7680
  const srcPath = el.getAttribute("data-composition-src");
7652
7681
  if (!srcPath) continue;
7653
7682
  if (isUnresolvedAssetPlaceholder(srcPath)) continue;
7654
- const filePath = resolveCompositionFile(projectDir, srcPath, assetRoot);
7683
+ const filePath = resolveCompositionPath(projectDir, srcPath, assetRoot);
7655
7684
  if (filePath === null) {
7656
7685
  problems.push({ srcPath, detail: "it is outside the project folder" });
7657
7686
  continue;
@@ -7664,6 +7693,10 @@ function assertSubCompositionsUsable(html, projectDir, assetRoot, visited = /* @
7664
7693
  problems.push({ srcPath, detail: "it is git metadata or an env file" });
7665
7694
  continue;
7666
7695
  }
7696
+ if (!COMPOSITION_FILE.test(filePath)) {
7697
+ problems.push({ srcPath, detail: NOT_A_COMPOSITION_FILE });
7698
+ continue;
7699
+ }
7667
7700
  if (visited.has(filePath)) continue;
7668
7701
  const read = readProjectFile(filePath);
7669
7702
  if (read.kind === "missing") {
@@ -7759,7 +7792,6 @@ var THREE_D_CONTEXT_PATTERN = /transform-style\s*:\s*preserve-3d|backface-visibi
7759
7792
  function detectThreeDTransformUsage(html) {
7760
7793
  return THREE_D_CONTEXT_PATTERN.test(html);
7761
7794
  }
7762
- var BACKGROUND_IMAGE_DECL_PATTERN = /(?:^|;|\{)\s*background(?:-image)?\s*:[^;}]*(?:\bgradient\s*\(|url\s*\()/i;
7763
7795
  function detectAncestorBackgroundImage(html) {
7764
7796
  const { document: document2 } = parseHTML5(html);
7765
7797
  const root = document2.querySelector("[data-composition-id]");
@@ -7771,13 +7803,13 @@ function detectAncestorBackgroundImage(html) {
7771
7803
  }
7772
7804
  for (const el of ancestors) {
7773
7805
  const style = el.getAttribute("style");
7774
- if (style && BACKGROUND_IMAGE_DECL_PATTERN.test(`{${style}}`)) return true;
7806
+ if (style && hasBackgroundImageDeclaration(`{${style}}`)) return true;
7775
7807
  }
7776
7808
  for (const styleEl of document2.querySelectorAll("style")) {
7777
7809
  const css = styleEl.textContent ?? "";
7778
- for (const rule of css.matchAll(/([^{}]+)\{([^}]*)\}/g)) {
7779
- const [, selectorList = "", declarations = ""] = rule;
7780
- if (!BACKGROUND_IMAGE_DECL_PATTERN.test(`{${declarations}}`)) continue;
7810
+ for (const { parts: rule } of cssRuleMatches(css)) {
7811
+ const [, selectorList, declarations] = rule;
7812
+ if (!hasBackgroundImageDeclaration(`{${declarations}}`)) continue;
7781
7813
  for (const selector of selectorList.split(",")) {
7782
7814
  const sel = selector.trim();
7783
7815
  if (!sel || sel.startsWith("@")) continue;
@@ -8098,7 +8130,6 @@ function coalesceHeadStylesAndBodyScripts(html) {
8098
8130
  el.textContent = dedupedStyles[i] ?? "";
8099
8131
  });
8100
8132
  const styleEls = head ? Array.from(head.querySelectorAll("style")) : [];
8101
- const importRe = /@import\s+url\([^)]*\)\s*;|@import\s+["'][^"']+["']\s*;/gi;
8102
8133
  for (const run of styleEls.length > 1 ? headStyleRuns(styleEls) : []) {
8103
8134
  const imports = [];
8104
8135
  const cssParts = [];
@@ -8106,7 +8137,7 @@ function coalesceHeadStylesAndBodyScripts(html) {
8106
8137
  for (const el of run) {
8107
8138
  const raw = (el.textContent || "").trim();
8108
8139
  if (!raw) continue;
8109
- const nonImportCss = raw.replace(importRe, (match) => {
8140
+ const nonImportCss = replaceMatches(raw, importRuleMatches(raw), (match) => {
8110
8141
  const cleaned = match.trim();
8111
8142
  if (!seenImports.has(cleaned)) {
8112
8143
  seenImports.add(cleaned);
@@ -8416,7 +8447,7 @@ function collectExternalAssets(html, projectDir, log = defaultLogger, file = "in
8416
8447
  for (const styleEl of document2.querySelectorAll("style")) {
8417
8448
  const css = styleEl.textContent || "";
8418
8449
  if (!css.includes("url(")) continue;
8419
- const rewritten = css.replace(CSS_URL_RE, (full, quote, rawUrl) => {
8450
+ const rewritten = replaceMatches(css, cssUrlMatches(css), (full, quote, rawUrl) => {
8420
8451
  const result = processPath((rawUrl || "").trim());
8421
8452
  if (!result) return full;
8422
8453
  return `url(${quote || ""}${result}${quote || ""})`;
@@ -8426,7 +8457,7 @@ function collectExternalAssets(html, projectDir, log = defaultLogger, file = "in
8426
8457
  for (const el of document2.querySelectorAll("[style]")) {
8427
8458
  const style = el.getAttribute("style") || "";
8428
8459
  if (!style.includes("url(")) continue;
8429
- const rewritten = style.replace(CSS_URL_RE, (full, quote, rawUrl) => {
8460
+ const rewritten = replaceMatches(style, cssUrlMatches(style), (full, quote, rawUrl) => {
8430
8461
  const result = processPath((rawUrl || "").trim());
8431
8462
  if (!result) return full;
8432
8463
  return `url(${quote || ""}${result}${quote || ""})`;
@@ -8529,13 +8560,10 @@ async function localizeRemoteImageSources(html, downloadDir) {
8529
8560
  "Localized remote image source(s)"
8530
8561
  );
8531
8562
  }
8532
- var REMOTE_BG_URL_RE = /background(?:-image)?\s*:\s*[^;}"']*?url\(\s*["']?(https?:\/\/[^"')]+)["']?\s*\)/gi;
8533
8563
  async function localizeRemoteBackgroundImages(html, downloadDir) {
8534
8564
  const urlSet = /* @__PURE__ */ new Set();
8535
- const re = new RegExp(REMOTE_BG_URL_RE.source, REMOTE_BG_URL_RE.flags);
8536
- let m;
8537
- while ((m = re.exec(html)) !== null) {
8538
- if (m[1] && !isGoogleFontsUrl(m[1])) urlSet.add(m[1]);
8565
+ for (const { parts } of remoteBackgroundUrlMatches(html)) {
8566
+ if (parts[1] && !isGoogleFontsUrl(parts[1])) urlSet.add(parts[1]);
8539
8567
  }
8540
8568
  return downloadAndRewriteUrls(
8541
8569
  urlSet,
@@ -8548,7 +8576,6 @@ async function localizeRemoteBackgroundImages(html, downloadDir) {
8548
8576
  (h, url, rel) => h.replaceAll(`url(${url})`, `url(${rel})`)
8549
8577
  );
8550
8578
  }
8551
- var REMOTE_FONTFACE_URL_RE = /url\(["']?(https?:\/\/[^"')]+)["']?\)/gi;
8552
8579
  function isGoogleFontsUrl(href) {
8553
8580
  try {
8554
8581
  const host = new URL(href).hostname.toLowerCase();
@@ -8576,31 +8603,33 @@ async function fetchExternalStylesheetCss(href) {
8576
8603
  }
8577
8604
  function extractFontFaceBlocks(css) {
8578
8605
  const blocks = [];
8606
+ const closes = matchingBraces(css);
8579
8607
  const atRule = /@font-face\s*/gi;
8580
- let m;
8581
- while ((m = atRule.exec(css)) !== null) {
8582
- const openIdx = css.indexOf("{", m.index + m[0].length);
8583
- if (openIdx === -1) break;
8584
- let depth = 1;
8585
- let i = openIdx + 1;
8586
- for (; i < css.length && depth > 0; i++) {
8587
- if (css[i] === "{") depth++;
8588
- else if (css[i] === "}") depth--;
8589
- }
8590
- if (depth === 0) {
8591
- blocks.push(css.slice(m.index, i));
8592
- atRule.lastIndex = i;
8593
- }
8608
+ let open = -1;
8609
+ for (let m = atRule.exec(css); m; m = atRule.exec(css)) {
8610
+ if (open < atRule.lastIndex) open = css.indexOf("{", atRule.lastIndex);
8611
+ if (open === -1) break;
8612
+ const close = closes.get(open);
8613
+ if (close === void 0) continue;
8614
+ blocks.push(css.slice(m.index, close + 1));
8615
+ atRule.lastIndex = close + 1;
8594
8616
  }
8595
8617
  return blocks;
8596
8618
  }
8619
+ function matchingBraces(css) {
8620
+ const closes = /* @__PURE__ */ new Map();
8621
+ const unclosed = [];
8622
+ for (let i = 0; i < css.length; i++) {
8623
+ if (css[i] === "{") unclosed.push(i);
8624
+ else if (css[i] === "}" && unclosed.length > 0) closes.set(unclosed.pop(), i);
8625
+ }
8626
+ return closes;
8627
+ }
8597
8628
  async function inlineExternalFontStylesheets(html) {
8598
- const linkRe = /<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi;
8599
8629
  const hrefRe = /\bhref=["']([^"']+)["']/i;
8600
8630
  const linkMatches = [];
8601
- let linkMatch;
8602
- while ((linkMatch = linkRe.exec(html)) !== null) {
8603
- const tag = linkMatch[0];
8631
+ for (const { parts } of stylesheetLinkMatches(html)) {
8632
+ const tag = parts[0];
8604
8633
  const hrefMatch = hrefRe.exec(tag);
8605
8634
  if (!hrefMatch?.[1]) continue;
8606
8635
  const href = hrefMatch[1];
@@ -8641,14 +8670,16 @@ ${fontFaceBlocks.join("\n")}
8641
8670
  }
8642
8671
  function projectStylesheetFontFamilies(html, projectDir) {
8643
8672
  const families = [];
8644
- for (const [tag] of html.matchAll(/<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi)) {
8673
+ for (const {
8674
+ parts: [tag]
8675
+ } of stylesheetLinkMatches(html)) {
8645
8676
  const href = /\bhref=["']([^"']+)["']/i.exec(tag)?.[1];
8646
8677
  if (!href || /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href)) continue;
8647
8678
  const sheet = resolve7(projectDir, decodedUrlPath(href).replace(/^(?:\.?\/)+/, ""));
8648
8679
  if (!isPathInside(sheet, projectDir) || !existsSync11(sheet)) continue;
8649
8680
  for (const face of extractFontFaceBlocks(readFileSync8(sheet, "utf8"))) {
8650
8681
  const family = /font-family\s*:\s*([^;}]+)/i.exec(face)?.[1]?.trim().replace(/^['"]|['"]$/g, "");
8651
- const shipsFile = [...face.matchAll(LOCAL_FONTFACE_URL_RE)].some(([, url = ""]) => {
8682
+ const shipsFile = [...localFontFaceUrlMatches(face)].some(({ parts: [, url = ""] }) => {
8652
8683
  const path = decodedUrlPath(url);
8653
8684
  const file = path.startsWith("/") ? resolve7(projectDir, `.${path}`) : resolve7(dirname8(sheet), path);
8654
8685
  return isPathInside(file, projectDir) && existsSync11(file);
@@ -8659,11 +8690,9 @@ function projectStylesheetFontFamilies(html, projectDir) {
8659
8690
  return families;
8660
8691
  }
8661
8692
  function collectFontFaceUrls(html) {
8662
- const styleBlockRe = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
8663
8693
  const urlSet = /* @__PURE__ */ new Set();
8664
- let styleMatch;
8665
- while ((styleMatch = styleBlockRe.exec(html)) !== null) {
8666
- const cssText = styleMatch[1] ?? "";
8694
+ for (const { parts } of styleBlockMatches(html)) {
8695
+ const cssText = parts[1];
8667
8696
  let i = 0;
8668
8697
  while (i < cssText.length) {
8669
8698
  const atIdx = cssText.indexOf("@font-face", i);
@@ -8678,10 +8707,8 @@ function collectFontFaceUrls(html) {
8678
8707
  j++;
8679
8708
  }
8680
8709
  const block = cssText.slice(braceStart + 1, j - 1);
8681
- const urlRe = new RegExp(REMOTE_FONTFACE_URL_RE.source, REMOTE_FONTFACE_URL_RE.flags);
8682
- let urlMatch;
8683
- while ((urlMatch = urlRe.exec(block)) !== null) {
8684
- if (urlMatch[1]) urlSet.add(urlMatch[1]);
8710
+ for (const { parts: parts2 } of remoteFontFaceUrlMatches(block)) {
8711
+ if (parts2[1]) urlSet.add(parts2[1]);
8685
8712
  }
8686
8713
  i = j;
8687
8714
  }
@@ -8698,7 +8725,6 @@ function localizeFontFaceUrls(html, downloadDir) {
8698
8725
  (h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`)
8699
8726
  );
8700
8727
  }
8701
- var LOCAL_FONTFACE_URL_RE = /url\(["']?(?!data:|file:|https?:\/\/)([^"')]+)["']?\)/gi;
8702
8728
  function urlOccurrenceRe(localPath) {
8703
8729
  const escaped = localPath.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8704
8730
  return new RegExp(`url\\((["']?)${escaped}\\1\\)`, "g");
@@ -8719,23 +8745,15 @@ async function readLocalFont(absPath) {
8719
8745
  }
8720
8746
  async function embedLocalFontFaces(html, projectDir, assetRoot, log = defaultLogger) {
8721
8747
  const { fontToDataUri: toDataUri } = await import("@hyperframes/core/fonts/embed");
8722
- const styleBlockRe = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
8723
- const fontFaceRe = /@font-face\s*\{([^}]*)\}/gi;
8724
8748
  let result = html;
8725
8749
  const embeddedPaths = /* @__PURE__ */ new Set();
8726
8750
  const dataUriByAbsolutePath = /* @__PURE__ */ new Map();
8727
8751
  const fileBackedAbsolutePaths = /* @__PURE__ */ new Set();
8728
- let styleMatch;
8729
- while ((styleMatch = styleBlockRe.exec(html)) !== null) {
8730
- const cssText = styleMatch[1] ?? "";
8731
- const ffRe = new RegExp(fontFaceRe.source, fontFaceRe.flags);
8732
- let ffMatch;
8733
- while ((ffMatch = ffRe.exec(cssText)) !== null) {
8734
- const block = ffMatch[1] ?? "";
8735
- const urlRe = new RegExp(LOCAL_FONTFACE_URL_RE.source, LOCAL_FONTFACE_URL_RE.flags);
8736
- let urlMatch;
8737
- while ((urlMatch = urlRe.exec(block)) !== null) {
8738
- const localPath = urlMatch[1];
8752
+ for (const { parts: style } of styleBlockMatches(html)) {
8753
+ for (const { parts: face } of fontFaceBlockMatches(style[1])) {
8754
+ const block = face[1];
8755
+ for (const { parts } of localFontFaceUrlMatches(block)) {
8756
+ const localPath = parts[1];
8739
8757
  if (!localPath || embeddedPaths.has(localPath)) continue;
8740
8758
  const absPath = localPath.startsWith("/") ? localPath : resolve7(projectDir, localPath);
8741
8759
  if (!isPathInside(absPath, projectDir) || escapesAssetRoot(absPath, assetRoot)) continue;
@@ -8854,6 +8872,9 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
8854
8872
  if (isPathInside(htmlPath, projectDir) && escapesAssetRoot(htmlPath, assetRoot)) {
8855
8873
  throw new Error(`Entry file ${htmlPath} leads outside the project folder`);
8856
8874
  }
8875
+ if (!COMPOSITION_FILE.test(htmlPath)) {
8876
+ throw new Error(`Entry file ${htmlPath} is not an .html file, so it is refused`);
8877
+ }
8857
8878
  const entryHtml = rebaseDirectEntryAssetPaths(readTextFile(htmlPath), projectDir, htmlPath);
8858
8879
  const rawHtml = bindVariableMediaSources(
8859
8880
  normalizeCompositionSrcs(rewriteUnresolvableGsapToCdn(entryHtml, projectDir), projectDir),
@@ -9409,6 +9430,14 @@ async function recompileWithResolutions(compiled, resolutions, projectDir, downl
9409
9430
  }
9410
9431
 
9411
9432
  // src/services/render/stages/compileStage.ts
9433
+ function animatedGifCacheDir(extractCacheDir) {
9434
+ try {
9435
+ const root = extractCacheDir && privateCacheRoot(extractCacheDir);
9436
+ return root ? join20(root, "animated-gif") : void 0;
9437
+ } catch {
9438
+ return void 0;
9439
+ }
9440
+ }
9412
9441
  function adaptAspectAgnosticResolution(requested, aspectAgnostic, width, height, log) {
9413
9442
  if (!requested || !aspectAgnostic) return requested;
9414
9443
  const flipped = suggestMatchingPreset(width, height, requested);
@@ -9488,7 +9517,7 @@ async function runCompileStage(input) {
9488
9517
  variables: input.variables,
9489
9518
  urlByAbsentLocalPath: input.urlByAbsentLocalPath,
9490
9519
  pageMotionBlur: input.pageMotionBlur,
9491
- animatedGifCacheDir: cfg.extractCacheDir ? join20(cfg.extractCacheDir, "animated-gif") : void 0,
9520
+ animatedGifCacheDir: animatedGifCacheDir(cfg.extractCacheDir),
9492
9521
  ffmpegProcessTimeout: cfg.ffmpegProcessTimeout,
9493
9522
  allowOutsideProjectAssets: job.config.allowOutsideProjectAssets
9494
9523
  });
@@ -10336,6 +10365,10 @@ import {
10336
10365
  resolveVideoExtractionWindow as resolveVideoExtractionWindow2,
10337
10366
  isHttpUrl as isHttpUrl2,
10338
10367
  assertPublicHttpsUrl,
10368
+ downloadToTemp as downloadToTemp2,
10369
+ resolveRestrictPageNetwork,
10370
+ isUrlNotPermittedError,
10371
+ writeUrlDownloadTelemetry as writeUrlDownloadTelemetry2,
10339
10372
  resolveProjectRelativeSrc as resolveProjectRelativeSrc4,
10340
10373
  runVideoExtractionWithRetry as runVideoExtractionWithRetry2,
10341
10374
  safeVideoExtractionSourceIdentity,
@@ -10571,6 +10604,7 @@ async function runExtractVideosStage(input) {
10571
10604
  deferRangeExtraction,
10572
10605
  shownBoxes,
10573
10606
  urlByAbsentLocalPath,
10607
+ audioDownloadDir,
10574
10608
  skipFrameExtractionIds = []
10575
10609
  } = input;
10576
10610
  const stage2Start = Date.now();
@@ -10643,7 +10677,15 @@ async function runExtractVideosStage(input) {
10643
10677
  imageColorSpaces.push(...probed);
10644
10678
  }
10645
10679
  if (skipFrameExtractionIds.length > 0) {
10646
- await appendVideoAudioFromProbe({ projectDir, compiledDir, composition, urlByAbsentLocalPath });
10680
+ await appendVideoAudioFromProbe({
10681
+ projectDir,
10682
+ compiledDir,
10683
+ composition,
10684
+ urlByAbsentLocalPath,
10685
+ downloadDir: audioDownloadDir,
10686
+ signal: abortSignal,
10687
+ log
10688
+ });
10647
10689
  videoReadinessSkipIds = [...skipFrameExtractionIds];
10648
10690
  } else if (composition.videos.length > 0) {
10649
10691
  const totalVideos = composition.videos.length;
@@ -10750,17 +10792,37 @@ function isPublicHttpsUrl(url) {
10750
10792
  return false;
10751
10793
  }
10752
10794
  }
10795
+ function localProbeSource(src, input) {
10796
+ const path = resolveProjectRelativeSrc4(src, input.projectDir, input.compiledDir);
10797
+ const readFrom = input.urlByAbsentLocalPath?.get(path) ?? path;
10798
+ return isHttpUrl2(readFrom) || existsSync13(readFrom) ? readFrom : null;
10799
+ }
10800
+ async function remoteProbeSource(video, input) {
10801
+ if (!isPublicHttpsUrl(video.src)) return null;
10802
+ if (!resolveRestrictPageNetwork()) return video.src;
10803
+ if (!video.hasAudio || video.hidden) return null;
10804
+ const downloadDir = input.downloadDir ?? join22(input.compiledDir, REMOTE_MEDIA_SUBDIR);
10805
+ try {
10806
+ return await downloadToTemp2(video.src, downloadDir, void 0, input.signal, void 0, {
10807
+ onTelemetry: writeUrlDownloadTelemetry2
10808
+ });
10809
+ } catch (error) {
10810
+ if (!isUrlNotPermittedError(error)) throw error;
10811
+ input.log?.warn("Video sound skipped: its URL is outside the download address rules", {
10812
+ videoId: video.id
10813
+ });
10814
+ return null;
10815
+ }
10816
+ }
10753
10817
  async function appendVideoAudioFromProbe(input) {
10754
- const { projectDir, compiledDir, composition, urlByAbsentLocalPath } = input;
10818
+ const { composition } = input;
10755
10819
  const videos = composition.videos.filter(
10756
10820
  (video) => !isVideoPastTimelineEnd(video, composition.duration)
10757
10821
  );
10758
10822
  const probed = await Promise.all(
10759
10823
  videos.map(async (video) => {
10760
- if (isHttpUrl2(video.src) && !isPublicHttpsUrl(video.src)) return null;
10761
- const path = isHttpUrl2(video.src) ? video.src : resolveProjectRelativeSrc4(video.src, projectDir, compiledDir);
10762
- const readFrom = urlByAbsentLocalPath?.get(path) ?? path;
10763
- if (!isHttpUrl2(readFrom) && !existsSync13(readFrom)) return null;
10824
+ const readFrom = isHttpUrl2(video.src) ? await remoteProbeSource(video, input) : localProbeSource(video.src, input);
10825
+ if (readFrom === null) return null;
10764
10826
  const metadata = await extractMediaMetadata4(readFrom);
10765
10827
  const window2 = await resolveFinalFrameExtractionWindow2(
10766
10828
  readFrom,
@@ -11538,7 +11600,7 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
11538
11600
  audioResult = await processCompositionAudio(
11539
11601
  audios,
11540
11602
  projectDir,
11541
- join25(workDir, "audio-work"),
11603
+ audioWorkDir(workDir),
11542
11604
  audioOutputPath,
11543
11605
  duration,
11544
11606
  abortSignal,
@@ -14436,6 +14498,19 @@ function resolveCaptureForceScreenshotForPageSideCompositing(args) {
14436
14498
  function shouldDiscardProbeSessionForPageSideCompositing(args) {
14437
14499
  return args.hasProbeSession && args.usePageSideCompositing;
14438
14500
  }
14501
+ var PAGE_SIDE_COMPOSITOR_CANVAS_ID = "__hf-page-side-compositor";
14502
+ async function pageInstallsShaderCompositor(open, session = { initializeSession: initializeSession8, closeCaptureSession: closeCaptureSession8 }) {
14503
+ const probe = await open();
14504
+ try {
14505
+ await session.initializeSession(probe);
14506
+ return await probe.page.evaluate(
14507
+ (id) => document.getElementById(id) !== null,
14508
+ PAGE_SIDE_COMPOSITOR_CANVAS_ID
14509
+ );
14510
+ } finally {
14511
+ await session.closeCaptureSession(probe);
14512
+ }
14513
+ }
14439
14514
  function deVerifyFallbackTelemetry(err) {
14440
14515
  const details = getDrawElementVerificationDetails(err);
14441
14516
  return {
@@ -14866,6 +14941,7 @@ async function executeRenderPipeline(input) {
14866
14941
  log,
14867
14942
  composition,
14868
14943
  skipFrameExtractionIds: videoLayer ? [videoLayer.videoId] : [],
14944
+ audioDownloadDir: audioWorkDir(workDir),
14869
14945
  abortSignal: executionSignal,
14870
14946
  assertNotAborted,
14871
14947
  // Local staging can use links; distributed plan() alone requires real copies.
@@ -15571,7 +15647,7 @@ async function executeRenderPipeline(input) {
15571
15647
  };
15572
15648
  const videoExt = FORMAT_EXT[outputFormat] ?? ".mp4";
15573
15649
  const videoOnlyPath = join32(workDir, `video-only${videoExt}`);
15574
- const usePageSideCompositingForTransitions = (cfg.enablePageSideCompositing || isGif) && compiled.hasShaderTransitions && !hasHdrContent && outputSupportsPageSideShaderCompositing(outputFormat);
15650
+ let usePageSideCompositingForTransitions = (cfg.enablePageSideCompositing || isGif) && compiled.hasShaderTransitions && !hasHdrContent && outputSupportsPageSideShaderCompositing(outputFormat);
15575
15651
  if (usePageSideCompositingForTransitions) {
15576
15652
  activeFileServer.addPreHeadScript(HF_PAGE_SIDE_COMPOSITING_STUB);
15577
15653
  if (shouldDiscardProbeSessionForPageSideCompositing({
@@ -15585,6 +15661,26 @@ async function executeRenderPipeline(input) {
15585
15661
  "[Render] Recreating capture session so page-side compositing pre-head script is loaded."
15586
15662
  );
15587
15663
  }
15664
+ try {
15665
+ usePageSideCompositingForTransitions = await pageInstallsShaderCompositor(
15666
+ () => createCaptureSession8(activeFileServer.url, framesDir, buildPrepCaptureOptions(), null, {
15667
+ ...cfg,
15668
+ forceScreenshot: true
15669
+ })
15670
+ );
15671
+ } catch (error) {
15672
+ assertNotAborted();
15673
+ log.warn("[Render] Shader compositor check failed; keeping page-side compositing.", {
15674
+ error: error instanceof Error ? error.message : String(error)
15675
+ });
15676
+ }
15677
+ if (!usePageSideCompositingForTransitions) {
15678
+ log.warn(
15679
+ "[Render] The page's shader-transitions build cannot composite in this browser; shader transitions blend on the Node-side layered path."
15680
+ );
15681
+ }
15682
+ }
15683
+ if (usePageSideCompositingForTransitions) {
15588
15684
  captureForceScreenshot = resolveCaptureForceScreenshotForPageSideCompositing({
15589
15685
  forceScreenshot: captureForceScreenshot,
15590
15686
  usePageSideCompositing: true
@@ -16645,7 +16741,11 @@ function readEntryHtml(filePath) {
16645
16741
  closeSync5(fd);
16646
16742
  }
16647
16743
  }
16648
- function readProjectEntryFile(projectDir, preferredEntryFile) {
16744
+ function leavesProject(absProjectDir, absoluteEntryPath, isAllowedEntry) {
16745
+ const entryRelativePath = relative4(absProjectDir, absoluteEntryPath);
16746
+ return entryRelativePath === ".." || entryRelativePath.startsWith(`..${sep4}`) || isAbsolute3(entryRelativePath) || isAllowedEntry !== void 0 && !isAllowedEntry(absoluteEntryPath);
16747
+ }
16748
+ function readProjectEntryFile(projectDir, preferredEntryFile, isAllowedEntry) {
16649
16749
  const absProjectDir = resolve9(projectDir);
16650
16750
  if (!existsSync22(absProjectDir) || !statSync11(absProjectDir).isDirectory()) {
16651
16751
  return { error: `Project directory not found: ${absProjectDir}` };
@@ -16655,8 +16755,7 @@ function readProjectEntryFile(projectDir, preferredEntryFile) {
16655
16755
  );
16656
16756
  for (const entryFile of entryCandidates) {
16657
16757
  const absoluteEntryPath = resolve9(absProjectDir, entryFile);
16658
- const entryRelativePath = relative4(absProjectDir, absoluteEntryPath);
16659
- if (entryRelativePath === ".." || entryRelativePath.startsWith(`..${sep4}`) || isAbsolute3(entryRelativePath)) {
16758
+ if (leavesProject(absProjectDir, absoluteEntryPath, isAllowedEntry)) {
16660
16759
  return { error: `Entry file must stay inside project directory: ${entryFile}` };
16661
16760
  }
16662
16761
  const html = readEntryHtml(absoluteEntryPath);
@@ -16672,10 +16771,10 @@ function readProjectEntryFile(projectDir, preferredEntryFile) {
16672
16771
  error: `No HTML entry file found in project directory: ${join33(absProjectDir, preferredEntryFile || "index.html")}`
16673
16772
  };
16674
16773
  }
16675
- function prepareHyperframeLintBody(body) {
16774
+ function prepareHyperframeLintBody(body, isAllowedEntry) {
16676
16775
  const requestedEntryFile = typeof body.entryFile === "string" && body.entryFile.trim().length > 0 ? body.entryFile.trim() : void 0;
16677
16776
  if (typeof body.projectDir === "string" && body.projectDir.trim().length > 0) {
16678
- const prepared = readProjectEntryFile(body.projectDir, requestedEntryFile);
16777
+ const prepared = readProjectEntryFile(body.projectDir, requestedEntryFile, isAllowedEntry);
16679
16778
  if ("error" in prepared) {
16680
16779
  return prepared;
16681
16780
  }
@@ -17390,16 +17489,22 @@ function buildRenderJobConfig(input, outputPath, log) {
17390
17489
  });
17391
17490
  return renderConfigFromRequest(request, { logger: log });
17392
17491
  }
17393
- function resolvePreparedRenderOutput(prepared, rendersDir, log) {
17492
+ function resolvePreparedRenderOutput(prepared, rendersDir, log, confineOutput) {
17394
17493
  const { input, cleanupProjectDir } = prepared;
17395
17494
  const absoluteOutputPath = resolveOutputPath(input.projectDir, input.outputPath, rendersDir, log);
17495
+ if (confineOutput) {
17496
+ mkdirSync13(rendersDir, { recursive: true });
17497
+ if (!isSafePath3(rendersDir, absoluteOutputPath)) {
17498
+ throw new Error("outputPath must be inside the renders directory");
17499
+ }
17500
+ }
17396
17501
  const outputDir = dirname16(absoluteOutputPath);
17397
17502
  if (!existsSync25(outputDir)) mkdirSync13(outputDir, { recursive: true });
17398
17503
  return { input, cleanupProjectDir, absoluteOutputPath };
17399
17504
  }
17400
- function prepareRenderJob(prepared, rendersDir, log) {
17505
+ function prepareRenderJob(prepared, rendersDir, log, confineOutput) {
17401
17506
  try {
17402
- const output = resolvePreparedRenderOutput(prepared, rendersDir, log);
17507
+ const output = resolvePreparedRenderOutput(prepared, rendersDir, log, confineOutput);
17403
17508
  const job = createRenderJob(buildRenderJobConfig(output.input, output.absoluteOutputPath, log));
17404
17509
  return { ...output, job };
17405
17510
  } catch (error) {
@@ -17450,16 +17555,32 @@ function validateOutputResolutionOverride(body) {
17450
17555
  return void 0;
17451
17556
  }
17452
17557
  var MAX_PREVIEW_HTML_BYTES = 20 * 1024 * 1024;
17453
- function prepareProjectDirectory(projectDir, options) {
17558
+ function resolveRenderRequestPolicy(options) {
17559
+ return {
17560
+ projectsDir: resolve10(
17561
+ options.projectsDir ?? (process.env.PRODUCER_PROJECTS_DIR || process.cwd())
17562
+ ),
17563
+ allowDebug: options.allowDebug ?? process.env.PRODUCER_ALLOW_DEBUG === "1"
17564
+ };
17565
+ }
17566
+ function isAllowedProjectPath(projectsDir, path) {
17567
+ return isSafePath3(projectsDir, path) && !isSafePath3(resolveRenderDebugDir(), path);
17568
+ }
17569
+ function isAllowedEntryPath(policy, projectDir, path) {
17570
+ return isSafePath3(projectDir, path) && isAllowedProjectPath(policy.projectsDir, path);
17571
+ }
17572
+ function prepareProjectDirectory(projectDir, options, policy) {
17454
17573
  const candidate = nonEmptyString(projectDir);
17455
17574
  if (!candidate) return null;
17456
- const absProjectDir = resolve10(candidate);
17457
- if (!existsSync25(absProjectDir) || !statSync12(absProjectDir).isDirectory()) {
17458
- return { error: `Project directory not found: ${absProjectDir}` };
17575
+ const absProjectDir = policy ? resolve10(policy.projectsDir, candidate) : resolve10(candidate);
17576
+ const shown = policy ? candidate : absProjectDir;
17577
+ if (policy && !isAllowedProjectPath(policy.projectsDir, absProjectDir) || !existsSync25(absProjectDir) || !statSync12(absProjectDir).isDirectory()) {
17578
+ return { error: `Project directory not found: ${shown}` };
17459
17579
  }
17460
17580
  const entry = options.entryFile || "index.html";
17461
- if (!existsSync25(resolve10(absProjectDir, entry))) {
17462
- return { error: `Entry file "${entry}" not found in project directory: ${absProjectDir}` };
17581
+ const entryPath = resolve10(absProjectDir, entry);
17582
+ if (policy && !isAllowedEntryPath(policy, absProjectDir, entryPath) || !existsSync25(entryPath)) {
17583
+ return { error: `Entry file "${entry}" not found in project directory: ${shown}` };
17463
17584
  }
17464
17585
  return { prepared: { input: { projectDir: absProjectDir, ...options } } };
17465
17586
  }
@@ -17488,15 +17609,18 @@ function materializeInlineProject(html, options) {
17488
17609
  }
17489
17610
  };
17490
17611
  }
17491
- async function prepareRenderBody(body) {
17612
+ async function prepareRenderBody(body, policy) {
17492
17613
  const overrideError = validateRenderOverrides(body);
17493
17614
  if (overrideError) return { error: overrideError };
17615
+ if (policy && body.debug === true && !policy.allowDebug) {
17616
+ return { error: "debug is disabled on this server (set allowDebug or PRODUCER_ALLOW_DEBUG=1)" };
17617
+ }
17494
17618
  const pageMotionBlur = body.pageMotionBlur;
17495
17619
  if (pageMotionBlur !== void 0 && pageMotionBlur !== "off") {
17496
17620
  return { error: "pageMotionBlur must be off when supplied" };
17497
17621
  }
17498
17622
  const options = { ...parseRenderOptions(body), pageMotionBlur };
17499
- const project = prepareProjectDirectory(body.projectDir, options);
17623
+ const project = prepareProjectDirectory(body.projectDir, options, policy);
17500
17624
  if (project) return project;
17501
17625
  const source = await resolveInlineRenderHtml(body);
17502
17626
  return "error" in source ? source : materializeInlineProject(source.html, options);
@@ -17549,6 +17673,9 @@ function cleanupTempDir(dir, log) {
17549
17673
  });
17550
17674
  }
17551
17675
  }
17676
+ function publicPerfSummary(job) {
17677
+ return job.perfSummary ? { ...job.perfSummary, renderId: void 0 } : null;
17678
+ }
17552
17679
  function outputFileSize(path) {
17553
17680
  return existsSync25(path) ? statSync12(path).size : 0;
17554
17681
  }
@@ -17561,7 +17688,7 @@ function createBlockingProgressReporter(log, requestId) {
17561
17688
  log.info(`render progress ${pct}%`, { requestId, stage: job.currentStage, message });
17562
17689
  };
17563
17690
  }
17564
- async function prepareSseRenderRequest(c, stream, requestId) {
17691
+ async function prepareSseRenderRequest(c, stream, requestId, policy) {
17565
17692
  let body;
17566
17693
  try {
17567
17694
  body = await c.req.json();
@@ -17576,7 +17703,7 @@ async function prepareSseRenderRequest(c, stream, requestId) {
17576
17703
  });
17577
17704
  return null;
17578
17705
  }
17579
- const prepared = await prepareRenderBody(body);
17706
+ const prepared = await prepareRenderBody(body, policy);
17580
17707
  if (!("error" in prepared)) return prepared.prepared;
17581
17708
  await stream.writeSSE({
17582
17709
  data: JSON.stringify({
@@ -17648,6 +17775,7 @@ function createRenderHandlers(options = {}) {
17648
17775
  const getRequestId = options.getRequestId ?? ((c) => c.req.header("x-request-id") || crypto.randomUUID());
17649
17776
  const outputUrlPrefix = options.outputUrlPrefix ?? "/outputs";
17650
17777
  const rendersDir = options.rendersDir ?? process.env.PRODUCER_RENDERS_DIR ?? "/tmp";
17778
+ const policy = options.confineRequests ? resolveRenderRequestPolicy(options) : void 0;
17651
17779
  const artifactTtlMs = options.artifactTtlMs ?? Number(process.env.PRODUCER_OUTPUT_ARTIFACT_TTL_MS || 15 * 60 * 1e3);
17652
17780
  const store = createArtifactStore(artifactTtlMs);
17653
17781
  const maxConcurrentRenders = options.maxConcurrentRenders ?? Number(process.env.PRODUCER_MAX_CONCURRENT_RENDERS || 2);
@@ -17666,7 +17794,18 @@ function createRenderHandlers(options = {}) {
17666
17794
  } catch {
17667
17795
  return c.json({ success: false, requestId, error: "Invalid JSON body" }, 400);
17668
17796
  }
17669
- const preparedResult = prepareHyperframeLintBody(body);
17797
+ const lintProjectDir = nonEmptyString(body.projectDir);
17798
+ let isAllowedEntry;
17799
+ if (policy && lintProjectDir) {
17800
+ const absProjectDir = resolve10(policy.projectsDir, lintProjectDir);
17801
+ if (!isAllowedProjectPath(policy.projectsDir, absProjectDir)) {
17802
+ const error = `Project directory not found: ${lintProjectDir}`;
17803
+ return c.json({ success: false, requestId, error }, 400);
17804
+ }
17805
+ body = { ...body, projectDir: absProjectDir };
17806
+ isAllowedEntry = (path) => isAllowedEntryPath(policy, absProjectDir, path);
17807
+ }
17808
+ const preparedResult = prepareHyperframeLintBody(body, isAllowedEntry);
17670
17809
  if ("error" in preparedResult) {
17671
17810
  return c.json({ success: false, requestId, error: preparedResult.error }, 400);
17672
17811
  }
@@ -17695,11 +17834,11 @@ function createRenderHandlers(options = {}) {
17695
17834
  } catch {
17696
17835
  return c.json({ success: false, requestId, error: "Invalid JSON body" }, 400);
17697
17836
  }
17698
- const preparedResult = await prepareRenderBody(body);
17837
+ const preparedResult = await prepareRenderBody(body, policy);
17699
17838
  if ("error" in preparedResult) {
17700
17839
  return c.json({ success: false, requestId, error: preparedResult.error }, 400);
17701
17840
  }
17702
- const preparedJob = prepareRenderJob(preparedResult.prepared, rendersDir, log);
17841
+ const preparedJob = prepareRenderJob(preparedResult.prepared, rendersDir, log, !!policy);
17703
17842
  if ("error" in preparedJob) {
17704
17843
  return c.json({ success: false, requestId, error: preparedJob.error }, 400);
17705
17844
  }
@@ -17740,7 +17879,7 @@ function createRenderHandlers(options = {}) {
17740
17879
  videoDurationSeconds: job.duration ?? null,
17741
17880
  outcome: job.outcome ?? "completed",
17742
17881
  warnings: job.warnings,
17743
- perf: job.perfSummary ?? null,
17882
+ perf: policy ? publicPerfSummary(job) : job.perfSummary ?? null,
17744
17883
  ...strictVariablesResult(job)
17745
17884
  });
17746
17885
  } catch (error) {
@@ -17777,9 +17916,9 @@ function createRenderHandlers(options = {}) {
17777
17916
  return streamSSE(c, async (stream) => {
17778
17917
  const requestId = getRequestId(c);
17779
17918
  const t0 = Date.now();
17780
- const prepared = await prepareSseRenderRequest(c, stream, requestId);
17919
+ const prepared = await prepareSseRenderRequest(c, stream, requestId, policy);
17781
17920
  if (!prepared) return;
17782
- const preparedJob = prepareRenderJob(prepared, rendersDir, log);
17921
+ const preparedJob = prepareRenderJob(prepared, rendersDir, log, !!policy);
17783
17922
  if ("error" in preparedJob) {
17784
17923
  await stream.writeSSE({
17785
17924
  data: JSON.stringify({
@@ -17836,7 +17975,7 @@ function createRenderHandlers(options = {}) {
17836
17975
  videoDurationSeconds: job.duration ?? null,
17837
17976
  outcome: job.outcome ?? "completed",
17838
17977
  warnings: job.warnings,
17839
- perf: job.perfSummary ?? null,
17978
+ perf: policy ? publicPerfSummary(job) : job.perfSummary ?? null,
17840
17979
  producerVersion: readProducerVersion(),
17841
17980
  ...strictVariablesResult(job)
17842
17981
  })
@@ -17894,9 +18033,79 @@ function isCrossOriginBrowserRequest(c) {
17894
18033
  return true;
17895
18034
  }
17896
18035
  }
18036
+ function hostnameOf(host) {
18037
+ try {
18038
+ return new URL(`http://${host}`).hostname.toLowerCase();
18039
+ } catch {
18040
+ return null;
18041
+ }
18042
+ }
18043
+ function isAllowedBrowserHostname(hostname2, allowed) {
18044
+ if (!hostname2) return false;
18045
+ if (hostname2 === "localhost" || hostname2.endsWith(".localhost")) return true;
18046
+ if (isIP(hostname2.replace(/^\[|\]$/g, "")) !== 0) return true;
18047
+ return allowed.has(hostname2);
18048
+ }
18049
+ function allowedHostnames(options) {
18050
+ const fromEnv = (process.env.PRODUCER_ALLOWED_HOSTS ?? "").split(",");
18051
+ const names = /* @__PURE__ */ new Set();
18052
+ for (const entry of [...options.allowedHosts ?? [], ...fromEnv]) {
18053
+ const hostname2 = entry.trim() ? hostnameOf(entry.trim()) : null;
18054
+ if (hostname2) names.add(hostname2);
18055
+ }
18056
+ return names;
18057
+ }
18058
+ function resolveAuthToken(options) {
18059
+ return options.authToken?.trim() || process.env.PRODUCER_AUTH_TOKEN?.trim() || "";
18060
+ }
18061
+ function hasBearerToken(c, token) {
18062
+ const digest = (value) => crypto.createHash("sha256").update(value).digest();
18063
+ return crypto.timingSafeEqual(
18064
+ digest(c.req.header("authorization") ?? ""),
18065
+ digest(`Bearer ${token}`)
18066
+ );
18067
+ }
18068
+ function isLoopbackHostname(hostname2) {
18069
+ const host = hostname2.replace(/^\[|\]$/g, "").toLowerCase();
18070
+ return host === "localhost" || host === "::1" || isIP(host) === 4 && host.startsWith("127.");
18071
+ }
18072
+ function isDisallowedBrowserHost(c, allowed) {
18073
+ const origin = c.req.header("origin");
18074
+ if (!origin && !c.req.header("sec-fetch-site")) return false;
18075
+ if (!isAllowedBrowserHostname(hostnameOf(c.req.header("host") ?? ""), allowed)) return true;
18076
+ if (!origin) return false;
18077
+ try {
18078
+ return !isAllowedBrowserHostname(new URL(origin).hostname.toLowerCase(), allowed);
18079
+ } catch {
18080
+ return true;
18081
+ }
18082
+ }
17897
18083
  function createProducerApp(options = {}) {
17898
18084
  const app = new Hono2();
17899
- const handlers = createRenderHandlers(options);
18085
+ const handlers = createRenderHandlers({
18086
+ ...options,
18087
+ confineRequests: options.confineRequests ?? true
18088
+ });
18089
+ const allowed = allowedHostnames(options);
18090
+ const authToken = resolveAuthToken(options);
18091
+ app.use("*", async (c, next) => {
18092
+ if (authToken && c.req.path !== "/health" && !hasBearerToken(c, authToken)) {
18093
+ return c.json({ success: false, error: "Unauthorized" }, 401);
18094
+ }
18095
+ await next();
18096
+ });
18097
+ app.use("*", async (c, next) => {
18098
+ if (isDisallowedBrowserHost(c, allowed)) {
18099
+ return c.json(
18100
+ {
18101
+ success: false,
18102
+ error: "Host not allowed. Add it to allowedHosts or PRODUCER_ALLOWED_HOSTS."
18103
+ },
18104
+ 403
18105
+ );
18106
+ }
18107
+ await next();
18108
+ });
17900
18109
  app.post("*", async (c, next) => {
17901
18110
  if (isCrossOriginBrowserRequest(c)) {
17902
18111
  return c.json({ success: false, error: "Cross-origin requests are not allowed" }, 403);
@@ -17913,10 +18122,17 @@ function createProducerApp(options = {}) {
17913
18122
  }
17914
18123
  function startServer(options = {}) {
17915
18124
  const port = options.port ?? parseInt(process.env.PRODUCER_PORT ?? "9847", 10);
18125
+ const hostname2 = options.hostname || process.env.PRODUCER_HOST || "127.0.0.1";
17916
18126
  const log = options.logger ?? defaultLogger;
18127
+ if (!isLoopbackHostname(hostname2) && !resolveAuthToken(options)) {
18128
+ throw new Error(
18129
+ `Refusing to listen on ${hostname2} without an auth token. Set authToken or PRODUCER_AUTH_TOKEN, or listen on a loopback address.`
18130
+ );
18131
+ }
17917
18132
  const app = createProducerApp(options);
17918
- const server = serve2({ fetch: app.fetch, port }, () => {
17919
- log.info(`Listening on http://localhost:${port}`);
18133
+ const server = serve2({ fetch: app.fetch, port, hostname: hostname2 }, (info) => {
18134
+ const address = info.family === "IPv6" ? `[${info.address}]` : info.address;
18135
+ log.info(`Listening on http://${address}:${info.port}`);
17920
18136
  });
17921
18137
  server.setTimeout(0);
17922
18138
  server.requestTimeout = 0;