@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
@@ -755,6 +755,66 @@ function parseRangeHeader(header, size) {
755
755
  };
756
756
  }
757
757
 
758
+ /**
759
+ * Which paths a request may name, where the path ends up joined onto a
760
+ * directory on disk or handed to the content service as a file to read.
761
+ *
762
+ * A media file's path arrives from the client three ways: in the URL of
763
+ * `/files`, in the body of `/upload/patches`, and as the `filePath` of a
764
+ * patch's `file` op. None of them was checked. `/files` answered any path
765
+ * under the project root (`.env`, the source), and an upload's `filePath` was
766
+ * joined onto the staging directory as it was, so `../../../../src/x` wrote
767
+ * outside it. In fs mode there is no session to stop either.
768
+ *
769
+ * So the rule is on the PATH, and it is the one media already follows: a local
770
+ * file lives under `/public` (`MediaDir` in core), and a remote one is named by
771
+ * its ref, which is a URL and never starts with a slash.
772
+ */
773
+
774
+ /** No segment that climbs or stays put, and nothing a path API reads as a separator. */
775
+ function hasOnlyPlainSegments(filePath) {
776
+ if (filePath.includes("\\") || filePath.includes("\0")) {
777
+ return false;
778
+ }
779
+ return filePath.split("/").every(segment => segment !== ".." && segment !== ".");
780
+ }
781
+
782
+ /**
783
+ * A local media path: `/public/...`, with nothing in it that leaves `/public`.
784
+ *
785
+ * What `/files` serves when it is asked for a published file, and where a
786
+ * publish may write an uploaded one.
787
+ */
788
+ function isPublicFilePath(filePath) {
789
+ return filePath.startsWith("/public/") && hasOnlyPlainSegments(filePath);
790
+ }
791
+
792
+ /**
793
+ * What a `file` op or an upload may name: a local media path, or a remote ref.
794
+ *
795
+ * A remote ref is stored in the patch directory under its own text, so it is
796
+ * held to the same segments rule. It cannot start with a slash, which is what
797
+ * keeps `/etc/x` and `/src/x` from passing as one.
798
+ */
799
+ function isMediaFilePath(filePath) {
800
+ if (filePath.startsWith("/")) {
801
+ return isPublicFilePath(filePath);
802
+ }
803
+ return filePath.length > 0 && hasOnlyPlainSegments(filePath);
804
+ }
805
+
806
+ /**
807
+ * A patch id as a directory name: one segment, and not a climbing one.
808
+ *
809
+ * Patch ids are UUIDs here and whatever the content service mints there, so
810
+ * this does not say what an id IS, only what it cannot be while it is used as
811
+ * the name of a directory under `.val/patches`.
812
+ */
813
+ function isSafePatchId(patchId) {
814
+ return patchId.length > 0 && patchId !== "." && patchId !== ".." && !/[/\\\0]/.test(patchId);
815
+ }
816
+ 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.";
817
+
758
818
  /**
759
819
  * The little of HLS (RFC 8216) the server has to read: the variants of a
760
820
  * master playlist, the segment durations of a media playlist, and every URI a
@@ -4634,17 +4694,24 @@ class ValOps {
4634
4694
  return result.ok(entries);
4635
4695
  };
4636
4696
  const collectPatchError = (err, patchId, op) => {
4697
+ /*
4698
+ * A `ValSyntaxError` holds the TypeScript node it is about, and a
4699
+ * node's `parent` points back up the tree: it is a cycle, so it must
4700
+ * never reach `JSON.stringify` - here, in the response, or in the
4701
+ * caller's own logging. Turn it into the message and the place in the
4702
+ * file it was about, which is all anyone downstream can use anyway.
4703
+ */
4704
+ const reported = err instanceof PatchError ? [err] : flattenSyntaxErrors(err).map(syntaxError => ({
4705
+ message: formatSyntaxErrorAt(path, tsSourceFile, syntaxError),
4706
+ filePath: path
4707
+ }));
4637
4708
  Internal.log.error("Could not patch", JSON.stringify({
4638
4709
  path,
4639
4710
  patchId,
4640
- error: err,
4711
+ errors: reported.map(formatPatchSourceError),
4641
4712
  op
4642
4713
  }, null, 2));
4643
- if (Array.isArray(err)) {
4644
- errors.push(...err);
4645
- } else {
4646
- errors.push(err);
4647
- }
4714
+ errors.push(...reported);
4648
4715
  };
4649
4716
  const appliedPatches = [];
4650
4717
  const triedPatches = [];
@@ -5203,6 +5270,27 @@ class ValOps {
5203
5270
 
5204
5271
  // #region createPatch
5205
5272
  async createPatch(path, patch, patchId, parentRef, sessionId, authorId) {
5273
+ // The id names a directory and each `file` op names a file in it, and
5274
+ // later a file a publish writes. Checked here, the one door every patch
5275
+ // comes through (the Studio, MCP), rather than at each of them.
5276
+ if (!isSafePatchId(patchId)) {
5277
+ return result.err({
5278
+ errorType: "other",
5279
+ error: {
5280
+ message: "This change's id is not a valid patch id."
5281
+ }
5282
+ });
5283
+ }
5284
+ for (const op of patch) {
5285
+ if (op.op === "file" && !isMediaFilePath(op.filePath)) {
5286
+ return result.err({
5287
+ errorType: "other",
5288
+ error: {
5289
+ message: `This change names a file at '${op.filePath}', which is not somewhere Val stores files. ${MEDIA_FILE_PATH_ACCEPTS}`
5290
+ }
5291
+ });
5292
+ }
5293
+ }
5206
5294
  const saveRes = await this.saveSourceFilePatch(path, patch, patchId, parentRef, authorId, sessionId);
5207
5295
  if (result.isErr(saveRes)) {
5208
5296
  if (saveRes.error.errorType === "plan-refused") {
@@ -5582,6 +5670,26 @@ function isFileSource(value) {
5582
5670
  * only wants a sentence reads it the same way.
5583
5671
  */
5584
5672
 
5673
+ function flattenSyntaxErrors(tree) {
5674
+ return Array.isArray(tree) ? tree.flatMap(flattenSyntaxErrors) : [tree];
5675
+ }
5676
+
5677
+ /**
5678
+ * `formatSyntaxError` without importing `./patch/ts/syntax`, which imports
5679
+ * `typescript` - this file has to bundle for a browser (see demo mode).
5680
+ * The node's own methods are all it needs.
5681
+ */
5682
+ function formatSyntaxErrorAt(path, sourceFile, error) {
5683
+ if (error.node.pos < 0) {
5684
+ // A node made by a factory has no place in the file.
5685
+ return `${path}: ${error.message}`;
5686
+ }
5687
+ const {
5688
+ line,
5689
+ character
5690
+ } = sourceFile.getLineAndCharacterOfPosition(error.node.getStart(sourceFile));
5691
+ return `${path}:${line + 1}:${character + 1} ${error.message}`;
5692
+ }
5585
5693
  function formatPatchSourceError(error) {
5586
5694
  if ("message" in error) {
5587
5695
  return error.message;
@@ -6295,7 +6403,7 @@ var packageJson = {
6295
6403
  ],
6296
6404
  exports: true
6297
6405
  },
6298
- version: "0.153.5",
6406
+ version: "0.154.0",
6299
6407
  scripts: {
6300
6408
  typecheck: "tsc --noEmit",
6301
6409
  test: "jest",
@@ -6311,11 +6419,11 @@ var packageJson = {
6311
6419
  "@valbuild/shared": "workspace:*",
6312
6420
  "@valbuild/ui": "workspace:*",
6313
6421
  chokidar: "^5.0.0",
6314
- "image-size": "^2.0.2",
6422
+ "image-size": "^2.0.3",
6315
6423
  minimatch: "^10.2.6",
6316
6424
  sucrase: "^3.35.1",
6317
6425
  typescript: "^6.0.3",
6318
- zod: "^4.4.3",
6426
+ zod: "^4.6.6",
6319
6427
  "zod-validation-error": "^5.0.0"
6320
6428
  },
6321
6429
  engines: {
@@ -7239,7 +7347,8 @@ const ValServer = (valModules, options, callbacks, platform) => {
7239
7347
  const token = crypto.randomUUID();
7240
7348
  const redirectUrl = new URL(redirectTo);
7241
7349
  const appAuthorizeUrl = getAuthorizeUrl(`${redirectUrl.origin}${options.route}`, token);
7242
- await callbacks.onEnable(true);
7350
+ // Draft mode is NOT turned on here: nobody has signed in yet, and this
7351
+ // is reachable by anyone. `/callback` turns it on, once they have.
7243
7352
  return {
7244
7353
  cookies: {
7245
7354
  [VAL_ENABLE_COOKIE_NAME]: ENABLE_COOKIE_VALUE,
@@ -8416,6 +8525,9 @@ const ValServer = (valModules, options, callbacks, platform) => {
8416
8525
  ...data,
8417
8526
  exp // this is the client side exp
8418
8527
  }, valSecret);
8528
+ // Signed in: now draft mode, which `/authorize` used to turn on for
8529
+ // whoever asked.
8530
+ await callbacks.onEnable(true);
8419
8531
  return {
8420
8532
  status: 302,
8421
8533
  cookies: {
@@ -8947,7 +9059,7 @@ const ValServer = (valModules, options, callbacks, platform) => {
8947
9059
  }
8948
9060
  const pathParts = req.path.split("/");
8949
9061
  const patchId = pathParts[1];
8950
- const isValidPatchId = patchId.length === 36;
9062
+ const isValidPatchId = patchId.length === 36 && isSafePatchId(patchId);
8951
9063
  const isValidEndpoint = pathParts[0] === "" && isValidPatchId && pathParts[2] === "files";
8952
9064
  if (!isValidEndpoint) {
8953
9065
  return {
@@ -9247,11 +9359,19 @@ const ValServer = (valModules, options, callbacks, platform) => {
9247
9359
  const createPatchRes = await serverOps.createPatch(patch.path, patch.patch, patch.patchId, parentRef, sessionId, authorId);
9248
9360
  if (result.isErr(createPatchRes)) {
9249
9361
  if (createPatchRes.error.errorType === "patch-head-conflict") {
9362
+ /*
9363
+ * The patches before this one in the batch ARE saved: each is
9364
+ * its own write, and someone else's can land between two of
9365
+ * ours. Reported as a 200 would report them, so the client does
9366
+ * not send them again -- the content service refuses a patch it
9367
+ * already has.
9368
+ */
9250
9369
  return {
9251
9370
  status: 409,
9252
9371
  json: {
9253
9372
  type: "patch-head-conflict",
9254
- message: "The change was written against a different starting point than the server has."
9373
+ message: "The change was written against a different starting point than the server has.",
9374
+ ...savedSoFar()
9255
9375
  }
9256
9376
  };
9257
9377
  } else if (createPatchRes.error.errorType === "plan-refused") {
@@ -9416,6 +9536,25 @@ const ValServer = (valModules, options, callbacks, platform) => {
9416
9536
  }
9417
9537
  const ids = query.id;
9418
9538
  const deleteRes = await serverOps.deletePatches(ids);
9539
+ if ("error" in deleteRes && deleteRes.error !== undefined) {
9540
+ /*
9541
+ * The store failed -- the content service, or in fs mode the patch
9542
+ * store's lock or log -- so nothing is known to be deleted.
9543
+ * Answered as a failure, never as the 200 below: that names every
9544
+ * id as deleted, and the Studio forgets patches that still exist --
9545
+ * a reload brings the change back, and the next publish ships it.
9546
+ */
9547
+ Internal.log.error("Failed to delete patches", deleteRes.error);
9548
+ return {
9549
+ status: 502,
9550
+ json: {
9551
+ message: deleteRes.error.message,
9552
+ ...(typeof deleteRes.error.details === "string" ? {
9553
+ details: deleteRes.error.details
9554
+ } : {})
9555
+ }
9556
+ };
9557
+ }
9419
9558
  if (deleteRes.errors && Object.keys(deleteRes.errors).length > 0) {
9420
9559
  Internal.log.error("Failed to delete patches", deleteRes.errors);
9421
9560
  return {
@@ -11102,6 +11241,19 @@ const ValServer = (valModules, options, callbacks, platform) => {
11102
11241
  // nothing fetches it backend-to-backend. Neither half of the argument
11103
11242
  // above transfers. See architecture/media.md, "Why /files has no auth,
11104
11243
  // and /history/files does".
11244
+ // Media and nothing else. This route has no auth (above), so what it
11245
+ // serves is decided by the path: a file under /public, which the site
11246
+ // serves anyway, or a draft of one. Without this it answered any path
11247
+ // in the project -- `.env`, the source -- and in http mode asked the
11248
+ // content service for it with the project's api key.
11249
+ if (!isPublicFilePath(filePath)) {
11250
+ return {
11251
+ status: 404,
11252
+ json: {
11253
+ message: "File not found"
11254
+ }
11255
+ };
11256
+ }
11105
11257
  const remote = query.remote === "true";
11106
11258
  const patchId = query.patch_id;
11107
11259
  if (!patchId && isHttpOps(serverOps) && remote) {
@@ -12662,8 +12814,9 @@ class ValOpsMemory extends ValOps {
12662
12814
 
12663
12815
  /**
12664
12816
  * What `redirect_to` may be on Val's routes (`/enable`, `/disable`,
12665
- * `/authorize`, `/draft/enable`, ...): an absolute URL, or a path on the site
12666
- * that was asked, which is made absolute against the request's own origin.
12817
+ * `/authorize`, `/draft/enable`, ...): a path on the site that was asked,
12818
+ * which is made absolute against the request's own origin, or an absolute
12819
+ * URL on that same site.
12667
12820
  *
12668
12821
  * A path used to go through as it was, and two things downstream need an
12669
12822
  * absolute URL: `/authorize` reads the origin off it to build the callback,
@@ -12676,8 +12829,13 @@ class ValOpsMemory extends ValOps {
12676
12829
  * it always was (`/logout` reads it as absent).
12677
12830
  */
12678
12831
 
12679
- const REDIRECT_TO_ACCEPTS = "redirect_to must be an absolute URL (https://example.com/page) or a path on this site starting with / (/page).";
12680
- function resolveRedirectTo(value, requestOrigin) {
12832
+ 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).";
12833
+
12834
+ /**
12835
+ * `siteHosts` are the other names the request knows this site by (`Host`,
12836
+ * `X-Forwarded-Host`), for a server behind a proxy whose own URL is internal.
12837
+ */
12838
+ function resolveRedirectTo(value, requestOrigin, siteHosts = []) {
12681
12839
  if (value.startsWith("/") && !value.startsWith("//")) {
12682
12840
  // A path stays on this origin. `/\host/x` also starts with one slash,
12683
12841
  // and a URL parser reads the backslash as a second one: another host,
@@ -12691,13 +12849,22 @@ function resolveRedirectTo(value, requestOrigin) {
12691
12849
  message: REDIRECT_TO_ACCEPTS
12692
12850
  };
12693
12851
  }
12694
- if (parsed(value) !== null) {
12852
+ // An absolute URL, on this site only. Any URL used to pass, which made
12853
+ // `/logout` and `/enable` redirect wherever a link said, and `/authorize`
12854
+ // send the sign-in's code to that host: it reads the callback's origin off
12855
+ // this. http(s) only: `javascript:` parses as a URL too.
12856
+ const url = parsed(value);
12857
+ if (url === null || url.protocol !== "https:" && url.protocol !== "http:") {
12695
12858
  return {
12696
- ok: true,
12697
- href: value
12859
+ ok: false,
12860
+ message: REDIRECT_TO_ACCEPTS
12698
12861
  };
12699
12862
  }
12700
- return {
12863
+ const hosts = [new URL(requestOrigin).host, ...siteHosts].filter(host => typeof host === "string" && host !== "").map(host => host.toLowerCase());
12864
+ return hosts.includes(url.host.toLowerCase()) ? {
12865
+ ok: true,
12866
+ href: value
12867
+ } : {
12701
12868
  ok: false,
12702
12869
  message: REDIRECT_TO_ACCEPTS
12703
12870
  };
@@ -12715,6 +12882,130 @@ function parsed(value, base) {
12715
12882
  }
12716
12883
  }
12717
12884
 
12885
+ /**
12886
+ * Which requests Val's API answers in fs mode, where there is no session.
12887
+ *
12888
+ * fs mode reads and writes a working tree and asks nobody who they are: it is
12889
+ * a developer's own machine. That holds only while the request really comes
12890
+ * from that developer's Studio, and three kinds do not:
12891
+ *
12892
+ * - **A deployed site.** fs is the mode an app falls into when it has no
12893
+ * `VAL_API_KEY` and `VAL_SECRET`, so a site deployed without them served
12894
+ * this API, unauthenticated, to the internet.
12895
+ * - **Another site's page**, in the developer's browser. A `text/plain` POST
12896
+ * needs no preflight, and the router reads its body as JSON, so any page
12897
+ * open in another tab could write to the working tree.
12898
+ * - **A name that resolves to 127.0.0.1** (DNS rebinding), which makes such a
12899
+ * page same-origin with the dev server as far as the browser can tell.
12900
+ *
12901
+ * The MCP endpoint has refused all three since it was written
12902
+ * (`refuseUnsafeRequest` in `@valbuild/mcp`); this is the same rule for the
12903
+ * API the Studio uses. Nothing here needs Node: `ValRouterCore` runs in a
12904
+ * browser tab too, where no server is registered and nothing is refused.
12905
+ */
12906
+
12907
+ const guards = new WeakMap();
12908
+
12909
+ /** Say how `server`'s requests are to be checked. Without it, none are. */
12910
+ function setRequestGuard(server, guard) {
12911
+ guards.set(server, guard);
12912
+ }
12913
+
12914
+ /** `VAL_ALLOWED_HOSTS`: comma separated host names, without a port. */
12915
+ function parseAllowedHosts(value) {
12916
+ return (value ?? "").split(",").map(host => host.trim().toLowerCase()).filter(host => host !== "");
12917
+ }
12918
+
12919
+ /** The refusal, or `null` when the request may go on to its route. */
12920
+ function refuseUnsafeRequest(server, req, apiPath) {
12921
+ var _req$method;
12922
+ const guard = guards.get(server);
12923
+ if (guard === undefined || guard.mode !== "fs") {
12924
+ return null;
12925
+ }
12926
+ // Beacons are not refused: in fs mode one is checked and dropped, nothing
12927
+ // is written or forwarded, and a deployed site with analytics on would fill
12928
+ // every visitor's console with errors.
12929
+ if (apiPath === "/analytics") {
12930
+ return null;
12931
+ }
12932
+ if (guard.production) {
12933
+ 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.");
12934
+ }
12935
+ const host = hostOf(req);
12936
+ const forwardedHost = firstOf(req.headers.get("x-forwarded-host"));
12937
+ const origin = req.headers.get("origin");
12938
+ if (origin !== null) {
12939
+ // `null` is the opaque origin (a sandboxed frame, a `file:` page). It
12940
+ // cannot be compared with anything, so it is refused.
12941
+ const originHost = origin === "null" ? null : hostOfUrl(origin);
12942
+ if (originHost === null || originHost !== host && originHost !== forwardedHost) {
12943
+ return refusal(`Val refused a request from another site (${origin}). In local filesystem mode the API only answers the Studio on its own address.`);
12944
+ }
12945
+ }
12946
+ // A request with no `Origin` can still come from another site: an `<img>`,
12947
+ // a script. Following a link here is not refused: sign-in comes back as
12948
+ // one. A link is a GET; a form posted from another site navigates too.
12949
+ const followedLink = ((_req$method = req.method) === null || _req$method === void 0 ? void 0 : _req$method.toUpperCase()) === "GET" && req.headers.get("sec-fetch-mode") === "navigate";
12950
+ if (req.headers.get("sec-fetch-site") === "cross-site" && !followedLink) {
12951
+ return refusal("Val refused a request from another site. In local filesystem mode the API only answers the Studio on its own address.");
12952
+ }
12953
+ const hostname = host === null ? null : hostnameOf(host);
12954
+ if (hostname === null || !isLocalName(hostname, guard.allowedHosts)) {
12955
+ 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.`);
12956
+ }
12957
+ return null;
12958
+ }
12959
+ function refusal(message) {
12960
+ return {
12961
+ status: 403,
12962
+ json: {
12963
+ message
12964
+ }
12965
+ };
12966
+ }
12967
+ function firstOf(header) {
12968
+ var _header$split$;
12969
+ const first = header === null || header === void 0 || (_header$split$ = header.split(",")[0]) === null || _header$split$ === void 0 ? void 0 : _header$split$.trim().toLowerCase();
12970
+ return first ? first : null;
12971
+ }
12972
+ function hostOf(req) {
12973
+ const header = firstOf(req.headers.get("host"));
12974
+ if (header !== null) {
12975
+ return header;
12976
+ }
12977
+ // No Host header: the URL the framework built the request from.
12978
+ return hostOfUrl(req.url);
12979
+ }
12980
+ function hostOfUrl(url) {
12981
+ try {
12982
+ return new URL(url).host.toLowerCase();
12983
+ } catch {
12984
+ return null;
12985
+ }
12986
+ }
12987
+
12988
+ /** A host without its port. An IPv6 literal keeps its brackets. */
12989
+ function hostnameOf(host) {
12990
+ if (host.startsWith("[")) {
12991
+ const end = host.indexOf("]");
12992
+ return end === -1 ? host : host.slice(0, end + 1);
12993
+ }
12994
+ const colon = host.indexOf(":");
12995
+ return colon === -1 ? host : host.slice(0, colon);
12996
+ }
12997
+
12998
+ /**
12999
+ * localhost, an IP address, or a name the developer listed.
13000
+ *
13001
+ * An IP address is allowed because it cannot be rebound: a page that reaches
13002
+ * this server by address is on another origin, and the `Origin` check above
13003
+ * has already refused it. A phone on the same network uses one.
13004
+ */
13005
+ function isLocalName(hostname, allowedHosts) {
13006
+ return hostname === "localhost" || hostname.endsWith(".localhost") || /^\d{1,3}(\.\d{1,3}){3}$/.test(hostname) || hostname.startsWith("[") && hostname.endsWith("]") || allowedHosts.includes(hostname);
13007
+ }
13008
+
12718
13009
  /**
12719
13010
  * Val's API as a web-standard handler: a `Request` in, a converted result out.
12720
13011
  *
@@ -12798,6 +13089,10 @@ function createValRequestHandler(route, valServerPromise, convert, serveStatic)
12798
13089
  Api;
12799
13090
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
12800
13091
  const anyValServer = valServer;
13092
+ const refused = refuseUnsafeRequest(valServer, req, reqApiRoutePath);
13093
+ if (refused !== null) {
13094
+ return refused;
13095
+ }
12801
13096
  const method = (_req$method = req.method) === null || _req$method === void 0 ? void 0 : _req$method.toUpperCase();
12802
13097
  let route = null;
12803
13098
  let path = undefined;
@@ -12923,7 +13218,10 @@ function createValRequestHandler(route, valServerPromise, convert, serveStatic)
12923
13218
  }
12924
13219
  // `redirect_to` is a URL or a path on this site: see `resolveRedirectTo`.
12925
13220
  if ("redirect_to" in query && typeof query.redirect_to === "string" && query.redirect_to !== "") {
12926
- const resolved = resolveRedirectTo(query.redirect_to, url.origin);
13221
+ var _req$headers$get;
13222
+ // Behind a proxy `url` can be an internal address: the site's own
13223
+ // name is then in `Host` or `X-Forwarded-Host`.
13224
+ 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()]);
12927
13225
  if (!resolved.ok) {
12928
13226
  return {
12929
13227
  status: 400,
@@ -13116,4 +13414,4 @@ function getCookies(req, cookiesDef) {
13116
13414
  return z.object(cookiesDef).safeParse(input);
13117
13415
  }
13118
13416
 
13119
- export { largestHlsVariant as A, fallbackRefOf as B, mapHlsUris as C, DEFAULT_ANALYTICS_INGEST_URL as D, movedRemoteHost as E, needsHostCheck as F, rewriteRefHost as G, fallbackRemoteHost as H, InMemoryPatchStore as I, checkRemoteFiles as J, ValServer as K, createValRequestHandler as L, bytesToBase64 as M, ValHead as N, headWork as O, HEAD_BUDGET_BYTES as P, HEAD_VERSIONS_PER_MODULE as Q, bytesToUtf8 as R, posixPath as S, VAL_CLIENT_HEADERS as V, formatPatchSourceError as a, askOncePerHost as b, getSettings as c, getFileExt as d, ValOpsMemory as e, findNestedJsonValuesRecords as f, getNewJsonEntryPaths as g, byUpdatedAt as h, isSketchpadId as i, applySketchpadChange as j, ValOps as k, bufferFromDataUrl as l, matchesFilter as m, newSketchpad as n, getFieldsForType as o, guessMimeTypeFromPath as p, createMetadataFromBuffer as q, resolveExistingJsonPath as r, summaryOf as s, sessionAuth as t, uploadRemoteFile as u, validateJsonValuesEntries as v, isHttpOps as w, isHlsMasterPlaylist as x, sumHlsSegmentDurations as y, parseHlsMasterVariants as z };
13417
+ export { isHlsMasterPlaylist as A, sumHlsSegmentDurations as B, parseHlsMasterVariants as C, DEFAULT_ANALYTICS_INGEST_URL as D, largestHlsVariant as E, fallbackRefOf as F, mapHlsUris as G, movedRemoteHost as H, InMemoryPatchStore as I, needsHostCheck as J, rewriteRefHost as K, fallbackRemoteHost as L, MEDIA_FILE_PATH_ACCEPTS as M, checkRemoteFiles as N, ValServer as O, setRequestGuard as P, parseAllowedHosts as Q, createValRequestHandler as R, bytesToBase64 as S, ValHead as T, headWork as U, VAL_CLIENT_HEADERS as V, HEAD_BUDGET_BYTES as W, HEAD_VERSIONS_PER_MODULE as X, bytesToUtf8 as Y, posixPath as Z, formatPatchSourceError as a, askOncePerHost as b, getSettings as c, getFileExt as d, ValOpsMemory as e, findNestedJsonValuesRecords as f, getNewJsonEntryPaths as g, byUpdatedAt as h, isSketchpadId as i, applySketchpadChange as j, ValOps as k, isSafePatchId as l, matchesFilter as m, newSketchpad as n, isMediaFilePath as o, bufferFromDataUrl as p, getFieldsForType as q, resolveExistingJsonPath as r, summaryOf as s, isPublicFilePath as t, uploadRemoteFile as u, validateJsonValuesEntries as v, guessMimeTypeFromPath as w, createMetadataFromBuffer as x, sessionAuth as y, isHttpOps as z };
@@ -36,6 +36,28 @@ export declare function deepValidateExpression(value: ts.Expression): result.Res
36
36
  * Evaluates the expression as a JSON value
37
37
  */
38
38
  export declare function evaluateExpression(value: ts.Expression): result.Result<JSONValue, ValSyntaxErrorTree>;
39
+ /**
40
+ * Finds the property `key` is written as in an object literal, for an edit to
41
+ * write into.
42
+ *
43
+ * An object may spread another into itself (`{ ...noMedia, code: null }`): the
44
+ * module evaluates it, so the value reads fine, and an edit to a key written
45
+ * out AFTER every spread can go ahead - that property is the one that wins.
46
+ * What cannot is an edit to a key a spread might supply or override, since we
47
+ * would be writing a value the module does not end up with. Those are
48
+ * refused, naming the spread, so the author knows which line to write out.
49
+ */
39
50
  export declare function findObjectPropertyAssignment(value: ts.ObjectLiteralExpression, key: string): result.Result<LiteralPropertyAssignment | undefined, ValSyntaxErrorTree>;
51
+ /**
52
+ * Finds the property `key` is written as, for a REMOVE: stricter than
53
+ * {@link findObjectPropertyAssignment}, because removing a key from an object
54
+ * that spreads another into it is refused outright. The key's own property may
55
+ * be all that hides a value the spread supplies, and removing it would bring
56
+ * that value back - and for a `.jsonValues()` entry, delete its file as well.
57
+ *
58
+ * Every remove goes through this, so the two that exist (a value, and a
59
+ * `.jsonValues()` entry) cannot disagree about it.
60
+ */
61
+ export declare function findObjectPropertyAssignmentToRemove(value: ts.ObjectLiteralExpression, key: string): result.Result<LiteralPropertyAssignment | undefined, ValSyntaxErrorTree>;
40
62
  export declare function validateInitializers(nodes: ReadonlyArray<ts.Expression>): ValSyntaxErrorTree | undefined;
41
63
  export {};
@@ -1,5 +1,5 @@
1
1
  import { DEFAULT_CONTENT_HOST } from '@valbuild/core';
2
- import { e as ValOpsMemory, M as bytesToBase64, K as ValServer, L as createValRequestHandler } from './ValRouterCore-257f140c.esm.js';
2
+ import { e as ValOpsMemory, S as bytesToBase64, O as ValServer, R as createValRequestHandler } from './ValRouterCore-fe985e4c.esm.js';
3
3
 
4
4
  const NO_SESSIONS = "Val: sessions are not available here -- this server runs in the browser, " + "has no secret to sign them with, and serves without authenticating.";
5
5
 
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var core = require('@valbuild/core');
4
- var ValRouterCore = require('./ValRouterCore-4e3757ac.cjs.dev.js');
4
+ var ValRouterCore = require('./ValRouterCore-0c088c9e.cjs.dev.js');
5
5
 
6
6
  const NO_SESSIONS = "Val: sessions are not available here -- this server runs in the browser, " + "has no secret to sign them with, and serves without authenticating.";
7
7
 
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var core = require('@valbuild/core');
4
- var ValRouterCore = require('./ValRouterCore-d658dc75.cjs.prod.js');
4
+ var ValRouterCore = require('./ValRouterCore-4be8eaf1.cjs.prod.js');
5
5
 
6
6
  const NO_SESSIONS = "Val: sessions are not available here -- this server runs in the browser, " + "has no secret to sign them with, and serves without authenticating.";
7
7
 
@@ -1,8 +1,8 @@
1
1
  import ts from 'typescript';
2
2
  import { result, pipe } from '@valbuild/core/fp';
3
- import { a as analyzeValModule, c as analyzeJsonValuesEntries, T as TSOps } from './ValRouter-072c3dee.esm.js';
4
- export { c as analyzeJsonValuesEntries, a as analyzeValModule, a8 as evaluateModuleSource, i as insertValJsonEntry, a9 as jsonValuesRecordKeys, r as removeValJsonEntry } from './ValRouter-072c3dee.esm.js';
5
- import { R as bytesToUtf8, S as posixPath } from './ValRouterCore-257f140c.esm.js';
3
+ import { a as analyzeValModule, c as analyzeJsonValuesEntries, T as TSOps } from './ValRouter-558dc66d.esm.js';
4
+ export { c as analyzeJsonValuesEntries, a as analyzeValModule, a8 as evaluateModuleSource, i as insertValJsonEntry, a9 as jsonValuesRecordKeys, r as removeValJsonEntry } from './ValRouter-558dc66d.esm.js';
5
+ import { Y as bytesToUtf8, Z as posixPath } from './ValRouterCore-fe985e4c.esm.js';
6
6
  import '@valbuild/core';
7
7
  import '@valbuild/ui/server';
8
8
  import 'path';
@@ -2,8 +2,8 @@
2
2
 
3
3
  var ts = require('typescript');
4
4
  var fp = require('@valbuild/core/fp');
5
- var ValRouter = require('./ValRouter-2ff58de9.cjs.dev.js');
6
- var ValRouterCore = require('./ValRouterCore-4e3757ac.cjs.dev.js');
5
+ var ValRouter = require('./ValRouter-1f427c38.cjs.dev.js');
6
+ var ValRouterCore = require('./ValRouterCore-0c088c9e.cjs.dev.js');
7
7
  require('@valbuild/core');
8
8
  require('@valbuild/ui/server');
9
9
  require('path');
@@ -2,8 +2,8 @@
2
2
 
3
3
  var ts = require('typescript');
4
4
  var fp = require('@valbuild/core/fp');
5
- var ValRouter = require('./ValRouter-60ee2fa5.cjs.prod.js');
6
- var ValRouterCore = require('./ValRouterCore-d658dc75.cjs.prod.js');
5
+ var ValRouter = require('./ValRouter-cd6e854a.cjs.prod.js');
6
+ var ValRouterCore = require('./ValRouterCore-4be8eaf1.cjs.prod.js');
7
7
  require('@valbuild/core');
8
8
  require('@valbuild/ui/server');
9
9
  require('path');
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var ValRouter = require('./ValRouter-2ff58de9.cjs.dev.js');
5
+ var ValRouter = require('./ValRouter-1f427c38.cjs.dev.js');
6
6
  var patch = require('@valbuild/core/patch');
7
7
  var fp = require('@valbuild/core/fp');
8
8
  var core = require('@valbuild/core');
@@ -11,7 +11,7 @@ var path = require('path');
11
11
  var fs = require('fs');
12
12
  var vm = require('node:vm');
13
13
  var node_module = require('node:module');
14
- var ValRouterCore = require('./ValRouterCore-4e3757ac.cjs.dev.js');
14
+ var ValRouterCore = require('./ValRouterCore-0c088c9e.cjs.dev.js');
15
15
  var internal = require('@valbuild/shared/internal');
16
16
  var sucrase = require('sucrase');
17
17
  var fs$1 = require('fs/promises');
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var ValRouter = require('./ValRouter-60ee2fa5.cjs.prod.js');
5
+ var ValRouter = require('./ValRouter-cd6e854a.cjs.prod.js');
6
6
  var patch = require('@valbuild/core/patch');
7
7
  var fp = require('@valbuild/core/fp');
8
8
  var core = require('@valbuild/core');
@@ -11,7 +11,7 @@ var path = require('path');
11
11
  var fs = require('fs');
12
12
  var vm = require('node:vm');
13
13
  var node_module = require('node:module');
14
- var ValRouterCore = require('./ValRouterCore-d658dc75.cjs.prod.js');
14
+ var ValRouterCore = require('./ValRouterCore-4be8eaf1.cjs.prod.js');
15
15
  var internal = require('@valbuild/shared/internal');
16
16
  var sucrase = require('sucrase');
17
17
  var fs$1 = require('fs/promises');
@@ -1,5 +1,5 @@
1
- import { T as TSOps, a as analyzeValModule, f as flatMapErrors, b as formatSyntaxError, c as analyzeJsonValuesEntries, r as removeValJsonEntry, i as insertValJsonEntry, d as collectionReferencePatches, e as checkGalleryFiles, h as handleVideoUploadRemote, g as handleVideoDownloadRemote, j as handleVideosetMetadata, k as handleVideosetUploadRemote, l as handleVideosetCheckRemote, m as handleVideosetCheckAllFiles, n as canReadVideoMetadata, u as unreadableVideoMetadataMessage, o as localFilesWarning, p as openRemoteUploadSession, q as uploadBytesToRemote, s as getPersonalAccessTokenPath, V as ValOpsFS } from './ValRouter-072c3dee.esm.js';
2
- export { F as APP_MODE_REQUIRES_REMOTE_FILES, V as ValOpsFS, X as ValOpsHttp, a as analyzeValModule, R as checkRemoteRef, x as contentFromEnv, H as createFixPatch, t as createValApiRouter, D as createValOps, v as createValServer, a0 as decodeJwtWithoutVerifying, _ as describePatchStoreProblems, S as downloadFileFromRemote, a2 as encodeJwt, M as extractFileMetadata, L as extractImageMetadata, N as extractVideoMetadata, O as extractVideoMetadataFromFile, P as filesOfVideo, J as filesOfVideosetEntry, G as formatSyntaxErrorTree, U as getCachedRemoteFileDir, W as getCachedRemoteFilePath, a1 as getExpire, s as getPersonalAccessTokenPath, Q as getValidationErrorFileRef, m as handleVideosetCheckAllFiles, l as handleVideosetCheckRemote, j as handleVideosetMetadata, k as handleVideosetUploadRemote, C as initHandlerOptions, z as layeredSnapshot, Y as loadTypeScriptKit, K as parsePersonalAccessTokenFile, y as proposalFromEnv, A as proposalSnapshot, B as proposalSnapshotForReaders, Z as readPatchStore, E as resolveRemoteFileAuth, w as safeReadGit, $ as verifyJwt, I as videosetEntryVideoSchema } from './ValRouter-072c3dee.esm.js';
1
+ import { T as TSOps, a as analyzeValModule, f as flatMapErrors, b as formatSyntaxError, c as analyzeJsonValuesEntries, r as removeValJsonEntry, i as insertValJsonEntry, d as collectionReferencePatches, e as checkGalleryFiles, h as handleVideoUploadRemote, g as handleVideoDownloadRemote, j as handleVideosetMetadata, k as handleVideosetUploadRemote, l as handleVideosetCheckRemote, m as handleVideosetCheckAllFiles, n as canReadVideoMetadata, u as unreadableVideoMetadataMessage, o as localFilesWarning, p as openRemoteUploadSession, q as uploadBytesToRemote, s as getPersonalAccessTokenPath, V as ValOpsFS } from './ValRouter-558dc66d.esm.js';
2
+ export { F as APP_MODE_REQUIRES_REMOTE_FILES, V as ValOpsFS, X as ValOpsHttp, a as analyzeValModule, R as checkRemoteRef, x as contentFromEnv, H as createFixPatch, t as createValApiRouter, D as createValOps, v as createValServer, a0 as decodeJwtWithoutVerifying, _ as describePatchStoreProblems, S as downloadFileFromRemote, a2 as encodeJwt, M as extractFileMetadata, L as extractImageMetadata, N as extractVideoMetadata, O as extractVideoMetadataFromFile, P as filesOfVideo, J as filesOfVideosetEntry, G as formatSyntaxErrorTree, U as getCachedRemoteFileDir, W as getCachedRemoteFilePath, a1 as getExpire, s as getPersonalAccessTokenPath, Q as getValidationErrorFileRef, m as handleVideosetCheckAllFiles, l as handleVideosetCheckRemote, j as handleVideosetMetadata, k as handleVideosetUploadRemote, C as initHandlerOptions, z as layeredSnapshot, Y as loadTypeScriptKit, K as parsePersonalAccessTokenFile, y as proposalFromEnv, A as proposalSnapshot, B as proposalSnapshotForReaders, Z as readPatchStore, E as resolveRemoteFileAuth, w as safeReadGit, $ as verifyJwt, I as videosetEntryVideoSchema } from './ValRouter-558dc66d.esm.js';
3
3
  import { applyPatch, PatchError, JSONOps, deepClone } from '@valbuild/core/patch';
4
4
  import { pipe, result } from '@valbuild/core/fp';
5
5
  import { derefPatch, Internal, extractValModules, DEFAULT_CONTENT_HOST } from '@valbuild/core';
@@ -9,8 +9,8 @@ import path from 'path';
9
9
  import fs from 'fs';
10
10
  import vm from 'node:vm';
11
11
  import { Module } from 'node:module';
12
- import { r as resolveExistingJsonPath, f as findNestedJsonValuesRecords, v as validateJsonValuesEntries, g as getNewJsonEntryPaths, a as formatPatchSourceError, V as VAL_CLIENT_HEADERS } from './ValRouterCore-257f140c.esm.js';
13
- export { I as InMemoryPatchStore, e as ValOpsMemory, b as askOncePerHost, a as formatPatchSourceError, d as getFileExt, c as getSettings, u as uploadRemoteFile } from './ValRouterCore-257f140c.esm.js';
12
+ import { r as resolveExistingJsonPath, f as findNestedJsonValuesRecords, v as validateJsonValuesEntries, g as getNewJsonEntryPaths, a as formatPatchSourceError, V as VAL_CLIENT_HEADERS } from './ValRouterCore-fe985e4c.esm.js';
13
+ export { I as InMemoryPatchStore, e as ValOpsMemory, b as askOncePerHost, a as formatPatchSourceError, d as getFileExt, c as getSettings, u as uploadRemoteFile } from './ValRouterCore-fe985e4c.esm.js';
14
14
  import { isJsonValuesRootOp, rebaseContentOp, classifyJsonValuesOp, richTextImageSchema } from '@valbuild/shared/internal';
15
15
  export { classifyJsonValuesOp, rebaseContentOp } from '@valbuild/shared/internal';
16
16
  import { transform } from 'sucrase';
@@ -2,10 +2,10 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var inTabFetch = require('../../../dist/inTabFetch-09f7ae69.cjs.dev.js');
5
+ var inTabFetch = require('../../../dist/inTabFetch-c8966e73.cjs.dev.js');
6
6
  var draftReads = require('../../../dist/draftReads-df44e629.cjs.dev.js');
7
7
  require('@valbuild/core');
8
- require('../../../dist/ValRouterCore-4e3757ac.cjs.dev.js');
8
+ require('../../../dist/ValRouterCore-0c088c9e.cjs.dev.js');
9
9
  require('zod');
10
10
  require('@valbuild/shared/internal');
11
11
  require('zod-validation-error');