@valbuild/server 0.153.5 → 0.154.0

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.
Files changed (27) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/browser/dist/valbuild-server-browser.cjs.dev.js +2 -2
  3. package/browser/dist/valbuild-server-browser.cjs.prod.js +2 -2
  4. package/browser/dist/valbuild-server-browser.esm.js +2 -2
  5. package/dist/{ValRouter-2ff58de9.cjs.dev.js → ValRouter-1f427c38.cjs.dev.js} +90 -8
  6. package/dist/{ValRouter-072c3dee.esm.js → ValRouter-558dc66d.esm.js} +90 -8
  7. package/dist/{ValRouter-60ee2fa5.cjs.prod.js → ValRouter-cd6e854a.cjs.prod.js} +90 -8
  8. package/dist/{ValRouterCore-4e3757ac.cjs.dev.js → ValRouterCore-0c088c9e.cjs.dev.js} +325 -21
  9. package/dist/{ValRouterCore-d658dc75.cjs.prod.js → ValRouterCore-4be8eaf1.cjs.prod.js} +325 -21
  10. package/dist/{ValRouterCore-257f140c.esm.js → ValRouterCore-fe985e4c.esm.js} +320 -22
  11. package/dist/declarations/src/patch/ts/syntax.d.ts +22 -0
  12. package/dist/{inTabFetch-0157c4a1.esm.js → inTabFetch-877e7d11.esm.js} +1 -1
  13. package/dist/{inTabFetch-09f7ae69.cjs.dev.js → inTabFetch-c8966e73.cjs.dev.js} +1 -1
  14. package/dist/{inTabFetch-7f2c9455.cjs.prod.js → inTabFetch-f6694ad2.cjs.prod.js} +1 -1
  15. package/dist/{publishKit-89923030.esm.js → publishKit-0709423c.esm.js} +3 -3
  16. package/dist/{publishKit-5227c288.cjs.dev.js → publishKit-cfe1273d.cjs.dev.js} +2 -2
  17. package/dist/{publishKit-26231426.cjs.prod.js → publishKit-e7f7db7c.cjs.prod.js} +2 -2
  18. package/dist/valbuild-server.cjs.dev.js +2 -2
  19. package/dist/valbuild-server.cjs.prod.js +2 -2
  20. package/dist/valbuild-server.esm.js +4 -4
  21. package/internal/browser/dist/valbuild-server-internal-browser.cjs.dev.js +2 -2
  22. package/internal/browser/dist/valbuild-server-internal-browser.cjs.prod.js +2 -2
  23. package/internal/browser/dist/valbuild-server-internal-browser.esm.js +2 -2
  24. package/internal/dist/valbuild-server-internal.cjs.dev.js +2 -2
  25. package/internal/dist/valbuild-server-internal.cjs.prod.js +2 -2
  26. package/internal/dist/valbuild-server-internal.esm.js +2 -2
  27. package/package.json +5 -5
@@ -761,6 +761,66 @@ function parseRangeHeader(header, size) {
761
761
  };
762
762
  }
763
763
 
764
+ /**
765
+ * Which paths a request may name, where the path ends up joined onto a
766
+ * directory on disk or handed to the content service as a file to read.
767
+ *
768
+ * A media file's path arrives from the client three ways: in the URL of
769
+ * `/files`, in the body of `/upload/patches`, and as the `filePath` of a
770
+ * patch's `file` op. None of them was checked. `/files` answered any path
771
+ * under the project root (`.env`, the source), and an upload's `filePath` was
772
+ * joined onto the staging directory as it was, so `../../../../src/x` wrote
773
+ * outside it. In fs mode there is no session to stop either.
774
+ *
775
+ * So the rule is on the PATH, and it is the one media already follows: a local
776
+ * file lives under `/public` (`MediaDir` in core), and a remote one is named by
777
+ * its ref, which is a URL and never starts with a slash.
778
+ */
779
+
780
+ /** No segment that climbs or stays put, and nothing a path API reads as a separator. */
781
+ function hasOnlyPlainSegments(filePath) {
782
+ if (filePath.includes("\\") || filePath.includes("\0")) {
783
+ return false;
784
+ }
785
+ return filePath.split("/").every(segment => segment !== ".." && segment !== ".");
786
+ }
787
+
788
+ /**
789
+ * A local media path: `/public/...`, with nothing in it that leaves `/public`.
790
+ *
791
+ * What `/files` serves when it is asked for a published file, and where a
792
+ * publish may write an uploaded one.
793
+ */
794
+ function isPublicFilePath(filePath) {
795
+ return filePath.startsWith("/public/") && hasOnlyPlainSegments(filePath);
796
+ }
797
+
798
+ /**
799
+ * What a `file` op or an upload may name: a local media path, or a remote ref.
800
+ *
801
+ * A remote ref is stored in the patch directory under its own text, so it is
802
+ * held to the same segments rule. It cannot start with a slash, which is what
803
+ * keeps `/etc/x` and `/src/x` from passing as one.
804
+ */
805
+ function isMediaFilePath(filePath) {
806
+ if (filePath.startsWith("/")) {
807
+ return isPublicFilePath(filePath);
808
+ }
809
+ return filePath.length > 0 && hasOnlyPlainSegments(filePath);
810
+ }
811
+
812
+ /**
813
+ * A patch id as a directory name: one segment, and not a climbing one.
814
+ *
815
+ * Patch ids are UUIDs here and whatever the content service mints there, so
816
+ * this does not say what an id IS, only what it cannot be while it is used as
817
+ * the name of a directory under `.val/patches`.
818
+ */
819
+ function isSafePatchId(patchId) {
820
+ return patchId.length > 0 && patchId !== "." && patchId !== ".." && !/[/\\\0]/.test(patchId);
821
+ }
822
+ const MEDIA_FILE_PATH_ACCEPTS = "A file's path must be under /public (/public/val/photo.jpg) or be a remote file's ref, with no '..' in it.";
823
+
764
824
  /**
765
825
  * The little of HLS (RFC 8216) the server has to read: the variants of a
766
826
  * master playlist, the segment durations of a media playlist, and every URI a
@@ -4640,17 +4700,24 @@ class ValOps {
4640
4700
  return fp.result.ok(entries);
4641
4701
  };
4642
4702
  const collectPatchError = (err, patchId, op) => {
4703
+ /*
4704
+ * A `ValSyntaxError` holds the TypeScript node it is about, and a
4705
+ * node's `parent` points back up the tree: it is a cycle, so it must
4706
+ * never reach `JSON.stringify` - here, in the response, or in the
4707
+ * caller's own logging. Turn it into the message and the place in the
4708
+ * file it was about, which is all anyone downstream can use anyway.
4709
+ */
4710
+ const reported = err instanceof patch.PatchError ? [err] : flattenSyntaxErrors(err).map(syntaxError => ({
4711
+ message: formatSyntaxErrorAt(path, tsSourceFile, syntaxError),
4712
+ filePath: path
4713
+ }));
4643
4714
  core.Internal.log.error("Could not patch", JSON.stringify({
4644
4715
  path,
4645
4716
  patchId,
4646
- error: err,
4717
+ errors: reported.map(formatPatchSourceError),
4647
4718
  op
4648
4719
  }, null, 2));
4649
- if (Array.isArray(err)) {
4650
- errors.push(...err);
4651
- } else {
4652
- errors.push(err);
4653
- }
4720
+ errors.push(...reported);
4654
4721
  };
4655
4722
  const appliedPatches = [];
4656
4723
  const triedPatches = [];
@@ -5209,6 +5276,27 @@ class ValOps {
5209
5276
 
5210
5277
  // #region createPatch
5211
5278
  async createPatch(path, patch, patchId, parentRef, sessionId, authorId) {
5279
+ // The id names a directory and each `file` op names a file in it, and
5280
+ // later a file a publish writes. Checked here, the one door every patch
5281
+ // comes through (the Studio, MCP), rather than at each of them.
5282
+ if (!isSafePatchId(patchId)) {
5283
+ return fp.result.err({
5284
+ errorType: "other",
5285
+ error: {
5286
+ message: "This change's id is not a valid patch id."
5287
+ }
5288
+ });
5289
+ }
5290
+ for (const op of patch) {
5291
+ if (op.op === "file" && !isMediaFilePath(op.filePath)) {
5292
+ return fp.result.err({
5293
+ errorType: "other",
5294
+ error: {
5295
+ message: `This change names a file at '${op.filePath}', which is not somewhere Val stores files. ${MEDIA_FILE_PATH_ACCEPTS}`
5296
+ }
5297
+ });
5298
+ }
5299
+ }
5212
5300
  const saveRes = await this.saveSourceFilePatch(path, patch, patchId, parentRef, authorId, sessionId);
5213
5301
  if (fp.result.isErr(saveRes)) {
5214
5302
  if (saveRes.error.errorType === "plan-refused") {
@@ -5588,6 +5676,26 @@ function isFileSource(value) {
5588
5676
  * only wants a sentence reads it the same way.
5589
5677
  */
5590
5678
 
5679
+ function flattenSyntaxErrors(tree) {
5680
+ return Array.isArray(tree) ? tree.flatMap(flattenSyntaxErrors) : [tree];
5681
+ }
5682
+
5683
+ /**
5684
+ * `formatSyntaxError` without importing `./patch/ts/syntax`, which imports
5685
+ * `typescript` - this file has to bundle for a browser (see demo mode).
5686
+ * The node's own methods are all it needs.
5687
+ */
5688
+ function formatSyntaxErrorAt(path, sourceFile, error) {
5689
+ if (error.node.pos < 0) {
5690
+ // A node made by a factory has no place in the file.
5691
+ return `${path}: ${error.message}`;
5692
+ }
5693
+ const {
5694
+ line,
5695
+ character
5696
+ } = sourceFile.getLineAndCharacterOfPosition(error.node.getStart(sourceFile));
5697
+ return `${path}:${line + 1}:${character + 1} ${error.message}`;
5698
+ }
5591
5699
  function formatPatchSourceError(error) {
5592
5700
  if ("message" in error) {
5593
5701
  return error.message;
@@ -6301,7 +6409,7 @@ var packageJson = {
6301
6409
  ],
6302
6410
  exports: true
6303
6411
  },
6304
- version: "0.153.5",
6412
+ version: "0.154.0",
6305
6413
  scripts: {
6306
6414
  typecheck: "tsc --noEmit",
6307
6415
  test: "jest",
@@ -6317,11 +6425,11 @@ var packageJson = {
6317
6425
  "@valbuild/shared": "workspace:*",
6318
6426
  "@valbuild/ui": "workspace:*",
6319
6427
  chokidar: "^5.0.0",
6320
- "image-size": "^2.0.2",
6428
+ "image-size": "^2.0.3",
6321
6429
  minimatch: "^10.2.6",
6322
6430
  sucrase: "^3.35.1",
6323
6431
  typescript: "^6.0.3",
6324
- zod: "^4.4.3",
6432
+ zod: "^4.6.6",
6325
6433
  "zod-validation-error": "^5.0.0"
6326
6434
  },
6327
6435
  engines: {
@@ -7245,7 +7353,8 @@ const ValServer = (valModules, options, callbacks, platform) => {
7245
7353
  const token = crypto.randomUUID();
7246
7354
  const redirectUrl = new URL(redirectTo);
7247
7355
  const appAuthorizeUrl = getAuthorizeUrl(`${redirectUrl.origin}${options.route}`, token);
7248
- await callbacks.onEnable(true);
7356
+ // Draft mode is NOT turned on here: nobody has signed in yet, and this
7357
+ // is reachable by anyone. `/callback` turns it on, once they have.
7249
7358
  return {
7250
7359
  cookies: {
7251
7360
  [internal.VAL_ENABLE_COOKIE_NAME]: ENABLE_COOKIE_VALUE,
@@ -8422,6 +8531,9 @@ const ValServer = (valModules, options, callbacks, platform) => {
8422
8531
  ...data,
8423
8532
  exp // this is the client side exp
8424
8533
  }, valSecret);
8534
+ // Signed in: now draft mode, which `/authorize` used to turn on for
8535
+ // whoever asked.
8536
+ await callbacks.onEnable(true);
8425
8537
  return {
8426
8538
  status: 302,
8427
8539
  cookies: {
@@ -8953,7 +9065,7 @@ const ValServer = (valModules, options, callbacks, platform) => {
8953
9065
  }
8954
9066
  const pathParts = req.path.split("/");
8955
9067
  const patchId = pathParts[1];
8956
- const isValidPatchId = patchId.length === 36;
9068
+ const isValidPatchId = patchId.length === 36 && isSafePatchId(patchId);
8957
9069
  const isValidEndpoint = pathParts[0] === "" && isValidPatchId && pathParts[2] === "files";
8958
9070
  if (!isValidEndpoint) {
8959
9071
  return {
@@ -9253,11 +9365,19 @@ const ValServer = (valModules, options, callbacks, platform) => {
9253
9365
  const createPatchRes = await serverOps.createPatch(patch.path, patch.patch, patch.patchId, parentRef, sessionId, authorId);
9254
9366
  if (fp.result.isErr(createPatchRes)) {
9255
9367
  if (createPatchRes.error.errorType === "patch-head-conflict") {
9368
+ /*
9369
+ * The patches before this one in the batch ARE saved: each is
9370
+ * its own write, and someone else's can land between two of
9371
+ * ours. Reported as a 200 would report them, so the client does
9372
+ * not send them again -- the content service refuses a patch it
9373
+ * already has.
9374
+ */
9256
9375
  return {
9257
9376
  status: 409,
9258
9377
  json: {
9259
9378
  type: "patch-head-conflict",
9260
- message: "The change was written against a different starting point than the server has."
9379
+ message: "The change was written against a different starting point than the server has.",
9380
+ ...savedSoFar()
9261
9381
  }
9262
9382
  };
9263
9383
  } else if (createPatchRes.error.errorType === "plan-refused") {
@@ -9422,6 +9542,25 @@ const ValServer = (valModules, options, callbacks, platform) => {
9422
9542
  }
9423
9543
  const ids = query.id;
9424
9544
  const deleteRes = await serverOps.deletePatches(ids);
9545
+ if ("error" in deleteRes && deleteRes.error !== undefined) {
9546
+ /*
9547
+ * The store failed -- the content service, or in fs mode the patch
9548
+ * store's lock or log -- so nothing is known to be deleted.
9549
+ * Answered as a failure, never as the 200 below: that names every
9550
+ * id as deleted, and the Studio forgets patches that still exist --
9551
+ * a reload brings the change back, and the next publish ships it.
9552
+ */
9553
+ core.Internal.log.error("Failed to delete patches", deleteRes.error);
9554
+ return {
9555
+ status: 502,
9556
+ json: {
9557
+ message: deleteRes.error.message,
9558
+ ...(typeof deleteRes.error.details === "string" ? {
9559
+ details: deleteRes.error.details
9560
+ } : {})
9561
+ }
9562
+ };
9563
+ }
9425
9564
  if (deleteRes.errors && Object.keys(deleteRes.errors).length > 0) {
9426
9565
  core.Internal.log.error("Failed to delete patches", deleteRes.errors);
9427
9566
  return {
@@ -11108,6 +11247,19 @@ const ValServer = (valModules, options, callbacks, platform) => {
11108
11247
  // nothing fetches it backend-to-backend. Neither half of the argument
11109
11248
  // above transfers. See architecture/media.md, "Why /files has no auth,
11110
11249
  // and /history/files does".
11250
+ // Media and nothing else. This route has no auth (above), so what it
11251
+ // serves is decided by the path: a file under /public, which the site
11252
+ // serves anyway, or a draft of one. Without this it answered any path
11253
+ // in the project -- `.env`, the source -- and in http mode asked the
11254
+ // content service for it with the project's api key.
11255
+ if (!isPublicFilePath(filePath)) {
11256
+ return {
11257
+ status: 404,
11258
+ json: {
11259
+ message: "File not found"
11260
+ }
11261
+ };
11262
+ }
11111
11263
  const remote = query.remote === "true";
11112
11264
  const patchId = query.patch_id;
11113
11265
  if (!patchId && isHttpOps(serverOps) && remote) {
@@ -12668,8 +12820,9 @@ class ValOpsMemory extends ValOps {
12668
12820
 
12669
12821
  /**
12670
12822
  * What `redirect_to` may be on Val's routes (`/enable`, `/disable`,
12671
- * `/authorize`, `/draft/enable`, ...): an absolute URL, or a path on the site
12672
- * that was asked, which is made absolute against the request's own origin.
12823
+ * `/authorize`, `/draft/enable`, ...): a path on the site that was asked,
12824
+ * which is made absolute against the request's own origin, or an absolute
12825
+ * URL on that same site.
12673
12826
  *
12674
12827
  * A path used to go through as it was, and two things downstream need an
12675
12828
  * absolute URL: `/authorize` reads the origin off it to build the callback,
@@ -12682,8 +12835,13 @@ class ValOpsMemory extends ValOps {
12682
12835
  * it always was (`/logout` reads it as absent).
12683
12836
  */
12684
12837
 
12685
- const REDIRECT_TO_ACCEPTS = "redirect_to must be an absolute URL (https://example.com/page) or a path on this site starting with / (/page).";
12686
- function resolveRedirectTo(value, requestOrigin) {
12838
+ const REDIRECT_TO_ACCEPTS = "redirect_to must be a path on this site starting with / (/page), or an absolute URL on this site (https://this-site.example/page).";
12839
+
12840
+ /**
12841
+ * `siteHosts` are the other names the request knows this site by (`Host`,
12842
+ * `X-Forwarded-Host`), for a server behind a proxy whose own URL is internal.
12843
+ */
12844
+ function resolveRedirectTo(value, requestOrigin, siteHosts = []) {
12687
12845
  if (value.startsWith("/") && !value.startsWith("//")) {
12688
12846
  // A path stays on this origin. `/\host/x` also starts with one slash,
12689
12847
  // and a URL parser reads the backslash as a second one: another host,
@@ -12697,13 +12855,22 @@ function resolveRedirectTo(value, requestOrigin) {
12697
12855
  message: REDIRECT_TO_ACCEPTS
12698
12856
  };
12699
12857
  }
12700
- if (parsed(value) !== null) {
12858
+ // An absolute URL, on this site only. Any URL used to pass, which made
12859
+ // `/logout` and `/enable` redirect wherever a link said, and `/authorize`
12860
+ // send the sign-in's code to that host: it reads the callback's origin off
12861
+ // this. http(s) only: `javascript:` parses as a URL too.
12862
+ const url = parsed(value);
12863
+ if (url === null || url.protocol !== "https:" && url.protocol !== "http:") {
12701
12864
  return {
12702
- ok: true,
12703
- href: value
12865
+ ok: false,
12866
+ message: REDIRECT_TO_ACCEPTS
12704
12867
  };
12705
12868
  }
12706
- return {
12869
+ const hosts = [new URL(requestOrigin).host, ...siteHosts].filter(host => typeof host === "string" && host !== "").map(host => host.toLowerCase());
12870
+ return hosts.includes(url.host.toLowerCase()) ? {
12871
+ ok: true,
12872
+ href: value
12873
+ } : {
12707
12874
  ok: false,
12708
12875
  message: REDIRECT_TO_ACCEPTS
12709
12876
  };
@@ -12721,6 +12888,130 @@ function parsed(value, base) {
12721
12888
  }
12722
12889
  }
12723
12890
 
12891
+ /**
12892
+ * Which requests Val's API answers in fs mode, where there is no session.
12893
+ *
12894
+ * fs mode reads and writes a working tree and asks nobody who they are: it is
12895
+ * a developer's own machine. That holds only while the request really comes
12896
+ * from that developer's Studio, and three kinds do not:
12897
+ *
12898
+ * - **A deployed site.** fs is the mode an app falls into when it has no
12899
+ * `VAL_API_KEY` and `VAL_SECRET`, so a site deployed without them served
12900
+ * this API, unauthenticated, to the internet.
12901
+ * - **Another site's page**, in the developer's browser. A `text/plain` POST
12902
+ * needs no preflight, and the router reads its body as JSON, so any page
12903
+ * open in another tab could write to the working tree.
12904
+ * - **A name that resolves to 127.0.0.1** (DNS rebinding), which makes such a
12905
+ * page same-origin with the dev server as far as the browser can tell.
12906
+ *
12907
+ * The MCP endpoint has refused all three since it was written
12908
+ * (`refuseUnsafeRequest` in `@valbuild/mcp`); this is the same rule for the
12909
+ * API the Studio uses. Nothing here needs Node: `ValRouterCore` runs in a
12910
+ * browser tab too, where no server is registered and nothing is refused.
12911
+ */
12912
+
12913
+ const guards = new WeakMap();
12914
+
12915
+ /** Say how `server`'s requests are to be checked. Without it, none are. */
12916
+ function setRequestGuard(server, guard) {
12917
+ guards.set(server, guard);
12918
+ }
12919
+
12920
+ /** `VAL_ALLOWED_HOSTS`: comma separated host names, without a port. */
12921
+ function parseAllowedHosts(value) {
12922
+ return (value ?? "").split(",").map(host => host.trim().toLowerCase()).filter(host => host !== "");
12923
+ }
12924
+
12925
+ /** The refusal, or `null` when the request may go on to its route. */
12926
+ function refuseUnsafeRequest(server, req, apiPath) {
12927
+ var _req$method;
12928
+ const guard = guards.get(server);
12929
+ if (guard === undefined || guard.mode !== "fs") {
12930
+ return null;
12931
+ }
12932
+ // Beacons are not refused: in fs mode one is checked and dropped, nothing
12933
+ // is written or forwarded, and a deployed site with analytics on would fill
12934
+ // every visitor's console with errors.
12935
+ if (apiPath === "/analytics") {
12936
+ return null;
12937
+ }
12938
+ if (guard.production) {
12939
+ return refusal("Val is not set up for a deployed site here: without VAL_API_KEY and VAL_SECRET it runs in local filesystem mode, which has no sign-in and is only served by a development server. Set both (and VAL_PROJECT) on this deployment to use Val on it.");
12940
+ }
12941
+ const host = hostOf(req);
12942
+ const forwardedHost = firstOf(req.headers.get("x-forwarded-host"));
12943
+ const origin = req.headers.get("origin");
12944
+ if (origin !== null) {
12945
+ // `null` is the opaque origin (a sandboxed frame, a `file:` page). It
12946
+ // cannot be compared with anything, so it is refused.
12947
+ const originHost = origin === "null" ? null : hostOfUrl(origin);
12948
+ if (originHost === null || originHost !== host && originHost !== forwardedHost) {
12949
+ return refusal(`Val refused a request from another site (${origin}). In local filesystem mode the API only answers the Studio on its own address.`);
12950
+ }
12951
+ }
12952
+ // A request with no `Origin` can still come from another site: an `<img>`,
12953
+ // a script. Following a link here is not refused: sign-in comes back as
12954
+ // one. A link is a GET; a form posted from another site navigates too.
12955
+ const followedLink = ((_req$method = req.method) === null || _req$method === void 0 ? void 0 : _req$method.toUpperCase()) === "GET" && req.headers.get("sec-fetch-mode") === "navigate";
12956
+ if (req.headers.get("sec-fetch-site") === "cross-site" && !followedLink) {
12957
+ return refusal("Val refused a request from another site. In local filesystem mode the API only answers the Studio on its own address.");
12958
+ }
12959
+ const hostname = host === null ? null : hostnameOf(host);
12960
+ if (hostname === null || !isLocalName(hostname, guard.allowedHosts)) {
12961
+ return refusal(`Val refused a request addressed to ${host ?? "an unknown host"}. In local filesystem mode the API answers on localhost and on IP addresses, because any other name can be made to point at this machine by the site that owns it. If this is the address you develop on, add its host name to the VAL_ALLOWED_HOSTS environment variable (comma separated) and restart the dev server.`);
12962
+ }
12963
+ return null;
12964
+ }
12965
+ function refusal(message) {
12966
+ return {
12967
+ status: 403,
12968
+ json: {
12969
+ message
12970
+ }
12971
+ };
12972
+ }
12973
+ function firstOf(header) {
12974
+ var _header$split$;
12975
+ const first = header === null || header === void 0 || (_header$split$ = header.split(",")[0]) === null || _header$split$ === void 0 ? void 0 : _header$split$.trim().toLowerCase();
12976
+ return first ? first : null;
12977
+ }
12978
+ function hostOf(req) {
12979
+ const header = firstOf(req.headers.get("host"));
12980
+ if (header !== null) {
12981
+ return header;
12982
+ }
12983
+ // No Host header: the URL the framework built the request from.
12984
+ return hostOfUrl(req.url);
12985
+ }
12986
+ function hostOfUrl(url) {
12987
+ try {
12988
+ return new URL(url).host.toLowerCase();
12989
+ } catch {
12990
+ return null;
12991
+ }
12992
+ }
12993
+
12994
+ /** A host without its port. An IPv6 literal keeps its brackets. */
12995
+ function hostnameOf(host) {
12996
+ if (host.startsWith("[")) {
12997
+ const end = host.indexOf("]");
12998
+ return end === -1 ? host : host.slice(0, end + 1);
12999
+ }
13000
+ const colon = host.indexOf(":");
13001
+ return colon === -1 ? host : host.slice(0, colon);
13002
+ }
13003
+
13004
+ /**
13005
+ * localhost, an IP address, or a name the developer listed.
13006
+ *
13007
+ * An IP address is allowed because it cannot be rebound: a page that reaches
13008
+ * this server by address is on another origin, and the `Origin` check above
13009
+ * has already refused it. A phone on the same network uses one.
13010
+ */
13011
+ function isLocalName(hostname, allowedHosts) {
13012
+ return hostname === "localhost" || hostname.endsWith(".localhost") || /^\d{1,3}(\.\d{1,3}){3}$/.test(hostname) || hostname.startsWith("[") && hostname.endsWith("]") || allowedHosts.includes(hostname);
13013
+ }
13014
+
12724
13015
  /**
12725
13016
  * Val's API as a web-standard handler: a `Request` in, a converted result out.
12726
13017
  *
@@ -12804,6 +13095,10 @@ function createValRequestHandler(route, valServerPromise, convert, serveStatic)
12804
13095
  internal.Api;
12805
13096
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
12806
13097
  const anyValServer = valServer;
13098
+ const refused = refuseUnsafeRequest(valServer, req, reqApiRoutePath);
13099
+ if (refused !== null) {
13100
+ return refused;
13101
+ }
12807
13102
  const method = (_req$method = req.method) === null || _req$method === void 0 ? void 0 : _req$method.toUpperCase();
12808
13103
  let route = null;
12809
13104
  let path = undefined;
@@ -12929,7 +13224,10 @@ function createValRequestHandler(route, valServerPromise, convert, serveStatic)
12929
13224
  }
12930
13225
  // `redirect_to` is a URL or a path on this site: see `resolveRedirectTo`.
12931
13226
  if ("redirect_to" in query && typeof query.redirect_to === "string" && query.redirect_to !== "") {
12932
- const resolved = resolveRedirectTo(query.redirect_to, url.origin);
13227
+ var _req$headers$get;
13228
+ // Behind a proxy `url` can be an internal address: the site's own
13229
+ // name is then in `Host` or `X-Forwarded-Host`.
13230
+ const resolved = resolveRedirectTo(query.redirect_to, url.origin, [req.headers.get("host"), (_req$headers$get = req.headers.get("x-forwarded-host")) === null || _req$headers$get === void 0 || (_req$headers$get = _req$headers$get.split(",")[0]) === null || _req$headers$get === void 0 ? void 0 : _req$headers$get.trim()]);
12933
13231
  if (!resolved.ok) {
12934
13232
  return {
12935
13233
  status: 400,
@@ -13126,6 +13424,7 @@ exports.DEFAULT_ANALYTICS_INGEST_URL = DEFAULT_ANALYTICS_INGEST_URL;
13126
13424
  exports.HEAD_BUDGET_BYTES = HEAD_BUDGET_BYTES;
13127
13425
  exports.HEAD_VERSIONS_PER_MODULE = HEAD_VERSIONS_PER_MODULE;
13128
13426
  exports.InMemoryPatchStore = InMemoryPatchStore;
13427
+ exports.MEDIA_FILE_PATH_ACCEPTS = MEDIA_FILE_PATH_ACCEPTS;
13129
13428
  exports.VAL_CLIENT_HEADERS = VAL_CLIENT_HEADERS;
13130
13429
  exports.ValHead = ValHead;
13131
13430
  exports.ValOps = ValOps;
@@ -13152,6 +13451,9 @@ exports.guessMimeTypeFromPath = guessMimeTypeFromPath;
13152
13451
  exports.headWork = headWork;
13153
13452
  exports.isHlsMasterPlaylist = isHlsMasterPlaylist;
13154
13453
  exports.isHttpOps = isHttpOps;
13454
+ exports.isMediaFilePath = isMediaFilePath;
13455
+ exports.isPublicFilePath = isPublicFilePath;
13456
+ exports.isSafePatchId = isSafePatchId;
13155
13457
  exports.isSketchpadId = isSketchpadId;
13156
13458
  exports.largestHlsVariant = largestHlsVariant;
13157
13459
  exports.mapHlsUris = mapHlsUris;
@@ -13159,11 +13461,13 @@ exports.matchesFilter = matchesFilter;
13159
13461
  exports.movedRemoteHost = movedRemoteHost;
13160
13462
  exports.needsHostCheck = needsHostCheck;
13161
13463
  exports.newSketchpad = newSketchpad;
13464
+ exports.parseAllowedHosts = parseAllowedHosts;
13162
13465
  exports.parseHlsMasterVariants = parseHlsMasterVariants;
13163
13466
  exports.posixPath = posixPath;
13164
13467
  exports.resolveExistingJsonPath = resolveExistingJsonPath;
13165
13468
  exports.rewriteRefHost = rewriteRefHost;
13166
13469
  exports.sessionAuth = sessionAuth;
13470
+ exports.setRequestGuard = setRequestGuard;
13167
13471
  exports.sumHlsSegmentDurations = sumHlsSegmentDurations;
13168
13472
  exports.summaryOf = summaryOf;
13169
13473
  exports.uploadRemoteFile = uploadRemoteFile;