@valbuild/server 0.136.9 → 0.137.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.
@@ -8,16 +8,19 @@ import path__default from 'path';
8
8
  import fs from 'fs';
9
9
  import vm from 'node:vm';
10
10
  import { Module } from 'node:module';
11
- import { isSchemaSourceFixError, resolveSchemaSourceFixForError, Patch, getErrorMessageFromUnknownJson, JSONValue, PatchGroup, newestCommitSha, SerializedSchema, VAL_ENABLE_COOKIE_NAME, VAL_STATE_COOKIE, VAL_SESSION_COOKIE, Api } from '@valbuild/shared/internal';
11
+ import { isSchemaSourceFixError, resolveSchemaSourceFixForError, Patch, getErrorMessageFromUnknownJson, PatchId as PatchId$1, JSONValue, PatchGroup, newestCommitSha, SerializedSchema, VAL_ENABLE_COOKIE_NAME, VAL_STATE_COOKIE, VAL_SESSION_COOKIE, Api } from '@valbuild/shared/internal';
12
12
  import { createUIRequestHandler } from '@valbuild/ui/server';
13
13
  import crypto$1 from 'crypto';
14
14
  import z$1, { z } from 'zod';
15
+ import http from 'node:http';
16
+ import https from 'node:https';
17
+ import net from 'node:net';
15
18
  import sizeOf from 'image-size';
16
19
  import { fromError } from 'zod-validation-error';
17
20
  import os from 'os';
18
21
  import { transform } from 'sucrase';
19
- import http from 'http';
20
- import https from 'https';
22
+ import http$1 from 'http';
23
+ import https$1 from 'https';
21
24
  import fs$1 from 'fs/promises';
22
25
 
23
26
  class ValSyntaxError {
@@ -2565,6 +2568,572 @@ function encodeJwt(payload, sessionKey) {
2565
2568
  return `${jwtHeaderBase64}.${payloadBase64}.${crypto$1.createHmac("sha256", sessionKey).update(`${jwtHeaderBase64}.${payloadBase64}`).digest("base64")}`;
2566
2569
  }
2567
2570
 
2571
+ /**
2572
+ * Just the part of `ValServerConfig` this decision needs.
2573
+ *
2574
+ * Narrower than the whole thing on purpose: a `ValServerConfig` carries the api
2575
+ * key, the secret and the content URLs, and a function that took one would look
2576
+ * like it might consult them. It also makes this testable with an object
2577
+ * literal rather than a cast.
2578
+ */
2579
+
2580
+ /**
2581
+ * The `val.config` the Studio is told about, which is not quite the one on disk.
2582
+ *
2583
+ * `gitBranch` is optional in `val.config`, and a proxy-mode server that mirrors
2584
+ * into a repository usually knows the branch when the file does not: setting it
2585
+ * in the environment is how a Vercel deployment does it
2586
+ * (`VERCEL_GIT_COMMIT_REF`), and the example app does not set it at all.
2587
+ *
2588
+ * Git is OPTIONAL in http mode — a project can run on credentials alone, with
2589
+ * no repository to mirror into — so "http" no longer implies a branch exists.
2590
+ * That changed under this function rather than being designed into it: the
2591
+ * original said proxy mode "refuses to start without `VAL_GIT_BRANCH`", which
2592
+ * was true when it was written and is not any more. With no mirror there is
2593
+ * nothing to fill in and nothing to say, which is the same answer fs mode gets.
2594
+ *
2595
+ * The Studio reads `config.gitBranch` and nothing else, so without this a
2596
+ * correctly configured project gets a History pane reading "this project has no
2597
+ * gitBranch configured" while the server behind it is busy committing to one,
2598
+ * and a status bar with no branch on it.
2599
+ *
2600
+ * Narrow on purpose:
2601
+ *
2602
+ * - **`val.config` wins.** A branch named in the file is the author's answer,
2603
+ * and the environment's is the fallback.
2604
+ * - **Every other mode is left alone.** Neither `fs` nor `memory` has a branch:
2605
+ * `ValOpsFS` has no commits of its own, and a memory host holds its own
2606
+ * source and never had any. Nor does an http project with no git mirror. The
2607
+ * shell hides what needs a branch rather than being handed a name that means
2608
+ * nothing.
2609
+ *
2610
+ * The modes are enumerated rather than written as "http, or anything else", and
2611
+ * that is worth keeping: `memory` arrived after this function did, and spelling
2612
+ * every mode out is what turned "does this one have a branch?" into a compile
2613
+ * error somebody had to answer instead of a default that silently applied.
2614
+ */
2615
+ function clientConfig(options) {
2616
+ if (options.mode !== "http" || options.git === undefined) {
2617
+ return options.config;
2618
+ }
2619
+ if (options.config.gitBranch !== undefined) {
2620
+ return options.config;
2621
+ }
2622
+ return {
2623
+ ...options.config,
2624
+ gitBranch: options.git.branch
2625
+ };
2626
+ }
2627
+
2628
+ /**
2629
+ * Which IP addresses this server may open a connection to.
2630
+ *
2631
+ * The link check makes outbound requests to addresses an editor supplies,
2632
+ * which is the definition of SSRF: without this, "check my external links"
2633
+ * is a button that turns the app's server into a probe for whatever is
2634
+ * reachable from inside the network it runs in - a database on a private
2635
+ * subnet, an admin panel on localhost, and on every major cloud the instance
2636
+ * metadata service on 169.254.169.254, which hands out credentials.
2637
+ *
2638
+ * So the rule is a DENY LIST of address ranges rather than an allow list of
2639
+ * hostnames: an editor is allowed to check any real site on the internet, and
2640
+ * nothing else. It is applied to the RESOLVED address, in the lookup the
2641
+ * socket then connects to - a public name is free to resolve to 127.0.0.1,
2642
+ * and checking the name would catch none of it.
2643
+ */
2644
+
2645
+ /** Why an address may not be connected to. Reported, not just counted. */
2646
+
2647
+ const REASON_TEXT = {
2648
+ unspecified: "an unspecified address",
2649
+ loopback: "a loopback address",
2650
+ private: "a private address",
2651
+ "link-local": "a link-local address",
2652
+ "unique-local": "a unique local address",
2653
+ multicast: "a multicast address",
2654
+ reserved: "a reserved address",
2655
+ unparseable: "an address that could not be read"
2656
+ };
2657
+ function describeBlocked(reason) {
2658
+ return REASON_TEXT[reason];
2659
+ }
2660
+
2661
+ /** `null` when the address is a public one this server may talk to. */
2662
+ function blockedAddressReason(address) {
2663
+ // A scope/zone id (`fe80::1%eth0`) is not part of the address, and leaving
2664
+ // it on would make the address unparseable — which fails closed, but for the
2665
+ // wrong reason and with the wrong message.
2666
+ const bare = address.split("%")[0];
2667
+ const v4 = parseIPv4(bare);
2668
+ if (v4 !== null) {
2669
+ return blockedIPv4(v4);
2670
+ }
2671
+ const v6 = parseIPv6(bare);
2672
+ if (v6 !== null) {
2673
+ return blockedIPv6(v6);
2674
+ }
2675
+ // Fail closed. Anything that reaches here is not something `dns.lookup`
2676
+ // produced, and connecting to an address this cannot read is exactly the
2677
+ // case a deny list must not wave through.
2678
+ return "unparseable";
2679
+ }
2680
+ function parseIPv4(text) {
2681
+ const parts = text.split(".");
2682
+ if (parts.length !== 4) {
2683
+ return null;
2684
+ }
2685
+ const octets = [];
2686
+ for (const part of parts) {
2687
+ // Deliberately strict: `010` is octal to `inet_aton` and decimal to
2688
+ // `Number`, and `1e2` parses as 100. A resolver never produces either, so
2689
+ // anything that is not plain digits is not an address - and a leading
2690
+ // zero is refused outright rather than read as decimal, because that is
2691
+ // the one form where this and `inet_aton` would read the SAME string as
2692
+ // two different addresses. `0` itself is an octet; `01` is not.
2693
+ if (!/^(0|[1-9]\d{0,2})$/.test(part)) {
2694
+ return null;
2695
+ }
2696
+ const value = Number(part);
2697
+ if (value > 255) {
2698
+ return null;
2699
+ }
2700
+ octets.push(value);
2701
+ }
2702
+ return [octets[0], octets[1], octets[2], octets[3]];
2703
+ }
2704
+
2705
+ /** Eight hextets, with `::` expanded and a trailing IPv4 form accepted. */
2706
+ function parseIPv6(text) {
2707
+ if (!text.includes(":")) {
2708
+ return null;
2709
+ }
2710
+ // A trailing dotted quad is rewritten into the two hextets it IS, before
2711
+ // anything else looks at the string. Splitting the address around it
2712
+ // instead means handling a `::` that the split lands inside - which is
2713
+ // exactly where `::127.0.0.1` went wrong.
2714
+ let normalized = text;
2715
+ const lastColon = text.lastIndexOf(":");
2716
+ const tail = text.slice(lastColon + 1);
2717
+ if (tail.includes(".")) {
2718
+ const v4 = parseIPv4(tail);
2719
+ if (v4 === null) {
2720
+ return null;
2721
+ }
2722
+ const high = (v4[0] << 8 | v4[1]).toString(16);
2723
+ const low = (v4[2] << 8 | v4[3]).toString(16);
2724
+ normalized = `${text.slice(0, lastColon + 1)}${high}:${low}`;
2725
+ }
2726
+ const doubleColon = normalized.indexOf("::");
2727
+ if (doubleColon !== normalized.lastIndexOf("::")) {
2728
+ return null;
2729
+ }
2730
+ let groups;
2731
+ if (doubleColon === -1) {
2732
+ groups = normalized.split(":");
2733
+ if (groups.length !== 8) {
2734
+ return null;
2735
+ }
2736
+ } else {
2737
+ const left = normalized.slice(0, doubleColon);
2738
+ const right = normalized.slice(doubleColon + 2);
2739
+ const before = left === "" ? [] : left.split(":");
2740
+ const after = right === "" ? [] : right.split(":");
2741
+ if (before.length + after.length > 7) {
2742
+ // `::` stands for AT LEAST one group of zeros, so eight written groups
2743
+ // beside it is one too many.
2744
+ return null;
2745
+ }
2746
+ groups = [...before, ...new Array(8 - before.length - after.length).fill("0"), ...after];
2747
+ }
2748
+ const hextets = [];
2749
+ for (const group of groups) {
2750
+ if (!/^[0-9a-fA-F]{1,4}$/.test(group)) {
2751
+ return null;
2752
+ }
2753
+ hextets.push(parseInt(group, 16));
2754
+ }
2755
+ return hextets.length === 8 ? hextets : null;
2756
+ }
2757
+ function blockedIPv4(octets) {
2758
+ const [a, b, c] = octets;
2759
+ if (a === 0) return "unspecified"; // 0.0.0.0/8
2760
+ if (a === 10) return "private"; // 10.0.0.0/8
2761
+ if (a === 127) return "loopback"; // 127.0.0.0/8
2762
+ if (a === 100 && b >= 64 && b <= 127) return "private"; // 100.64.0.0/10 CGNAT
2763
+ if (a === 169 && b === 254) return "link-local"; // 169.254.0.0/16 — cloud metadata
2764
+ if (a === 172 && b >= 16 && b <= 31) return "private"; // 172.16.0.0/12
2765
+ if (a === 192 && b === 168) return "private"; // 192.168.0.0/16
2766
+ if (a === 192 && b === 0 && (c === 0 || c === 2)) return "reserved"; // 192.0.0.0/24, TEST-NET-1
2767
+ if (a === 192 && b === 88 && c === 99) return "reserved"; // 6to4 relay anycast
2768
+ if (a === 198 && (b === 18 || b === 19)) return "reserved"; // benchmarking
2769
+ if (a === 198 && b === 51 && c === 100) return "reserved"; // TEST-NET-2
2770
+ if (a === 203 && b === 0 && c === 113) return "reserved"; // TEST-NET-3
2771
+ if (a >= 240) return "reserved"; // 240.0.0.0/4, incl. 255.255.255.255
2772
+ if (a >= 224) return "multicast"; // 224.0.0.0/4
2773
+ return null;
2774
+ }
2775
+ function blockedIPv6(h) {
2776
+ const leadingZeros = h[0] === 0 && h[1] === 0 && h[2] === 0 && h[3] === 0 && h[4] === 0;
2777
+ if (leadingZeros && h[5] === 0xffff) {
2778
+ // ::ffff:0:0/96 — an IPv4 address wearing an IPv6 hat, and the form a
2779
+ // dual-stack resolver hands back. Judged as the IPv4 address it is, or
2780
+ // this whole list would be one `::ffff:` away from being bypassed.
2781
+ return blockedIPv4(v4Of(h[6], h[7]));
2782
+ }
2783
+ if (leadingZeros && h[5] === 0) {
2784
+ // ::/128 unspecified, ::1/128 loopback, and the deprecated
2785
+ // IPv4-compatible ::a.b.c.d — all of which are local or nothing.
2786
+ if (h[6] === 0 && h[7] === 0) return "unspecified";
2787
+ if (h[6] === 0 && h[7] === 1) return "loopback";
2788
+ return blockedIPv4(v4Of(h[6], h[7])) ?? "reserved";
2789
+ }
2790
+ if (h[0] === 0x64 && h[1] === 0xff9b) return "reserved"; // NAT64
2791
+ if (h[0] === 0x100 && h[1] === 0 && h[2] === 0 && h[3] === 0) {
2792
+ return "reserved"; // 100::/64 discard-only
2793
+ }
2794
+ if (h[0] === 0x2001 && h[1] === 0x0db8) return "reserved"; // documentation
2795
+ if ((h[0] & 0xfe00) === 0xfc00) return "unique-local"; // fc00::/7
2796
+ if ((h[0] & 0xffc0) === 0xfe80) return "link-local"; // fe80::/10
2797
+ if ((h[0] & 0xff00) === 0xff00) return "multicast"; // ff00::/8
2798
+ return null;
2799
+ }
2800
+ function v4Of(high, low) {
2801
+ return [high >> 8, high & 0xff, low >> 8, low & 0xff];
2802
+ }
2803
+
2804
+ /**
2805
+ * Opening one external URL and reporting what answered.
2806
+ *
2807
+ * Mirrors `ExternalUrlProbeResult` in the Studio - the two are checked against
2808
+ * each other by the API route's zod schema, which is the only place they meet.
2809
+ */
2810
+
2811
+ const DEFAULT_TIMEOUT_MS$1 = 5000;
2812
+ const DEFAULT_MAX_REDIRECTS = 5;
2813
+
2814
+ /**
2815
+ * A browser-ish identity.
2816
+ *
2817
+ * Not a disguise: plenty of sites answer 403 to a request with no `User-Agent`
2818
+ * at all, and reporting those as broken would be a check that cries wolf. It
2819
+ * says what it is and where to complain.
2820
+ */
2821
+ const USER_AGENT = "Val-Studio-LinkCheck/1.0 (+https://val.build; link checker)";
2822
+
2823
+ /**
2824
+ * A `lookup` that refuses to hand back an address this server may not reach.
2825
+ *
2826
+ * This, rather than a check on the hostname or a check after the fact, is what
2827
+ * closes the hole. The socket connects to the address the lookup RETURNS, so
2828
+ * validating inside it leaves no window between the check and the connection —
2829
+ * a name that resolves to 93.184.216.34 once and 127.0.0.1 the next time gets
2830
+ * no second chance, because there is only ever one resolution and it is this
2831
+ * one.
2832
+ */
2833
+ /**
2834
+ * What a refused lookup tells the CALLER.
2835
+ *
2836
+ * Deliberately the same words `ENETUNREACH` gets, and deliberately without the
2837
+ * address. The guard stops the connection, but the first version of it handed
2838
+ * back the DNS answer it had just refused to use - "vault.prod.svc resolves to
2839
+ * a private address (10.42.7.19)" - which travels through `readableError` into
2840
+ * the response and onto the screen. That turns an endpoint that cannot reach
2841
+ * the internal network into one that MAPS it: twenty names a request, existence
2842
+ * confirmed and address included, without a single connection being made.
2843
+ *
2844
+ * True rather than evasive: this server genuinely did not reach the host. And
2845
+ * because a real external host that is down produces the same sentence, the
2846
+ * answer no longer says which of the two happened. The operator still gets the
2847
+ * detail, in the log, where it belongs.
2848
+ *
2849
+ * A hostname the caller wrote as a literal address is different and keeps its
2850
+ * specific message (see the literal check in `probeUrl`): repeating
2851
+ * `127.0.0.1` to someone who just typed `127.0.0.1` reveals nothing.
2852
+ */
2853
+ const REFUSED_MESSAGE = "the host could not be reached";
2854
+ function guardedLookup(lookup) {
2855
+ const guarded = (hostname, options, callback) => {
2856
+ // The overloads differ only in whether `options` was passed; `net` always
2857
+ // calls through with both, and this forwards whatever it was given.
2858
+ return lookup(hostname, options, (err, address, family) => {
2859
+ if (err) {
2860
+ callback(err, "", 0);
2861
+ return;
2862
+ }
2863
+ const addresses = Array.isArray(address) ? address : [{
2864
+ address,
2865
+ family: family ?? 0
2866
+ }];
2867
+ for (const entry of addresses) {
2868
+ const reason = blockedAddressReason(entry.address);
2869
+ if (reason !== null) {
2870
+ // Server-side only. This is the half an operator needs to work out
2871
+ // why a link check refused a URL, and the half a caller must not
2872
+ // be given.
2873
+ console.warn(`[val] link check refused ${hostname}: resolves to ${describeBlocked(reason)} (${entry.address})`);
2874
+ callback(new Error(REFUSED_MESSAGE), "", 0);
2875
+ return;
2876
+ }
2877
+ }
2878
+ // Forwarded in the shape it arrived in: `net` reads it back according
2879
+ // to whether it asked for `all`.
2880
+ if (Array.isArray(address)) {
2881
+ callback(null, address, family);
2882
+ } else {
2883
+ callback(null, address, family ?? 0);
2884
+ }
2885
+ }
2886
+ // The callback shape above is the union of both overloads, which the
2887
+ // published types split apart.
2888
+ );
2889
+ };
2890
+ return guarded;
2891
+ }
2892
+
2893
+ /** The statuses that mean "ask again with GET" rather than "no". */
2894
+ function needsGetFallback(code) {
2895
+ /*
2896
+ * Only where the server said the METHOD was the problem.
2897
+ *
2898
+ * A 403 is the tempting third case - some WAFs and proxies do refuse HEAD
2899
+ * with one, and this repo's own sandbox is an example - but retrying every
2900
+ * 403 with a GET means downloading a page for each of them, on a check whose
2901
+ * whole point is to be cheap enough to run over a few hundred URLs. And it
2902
+ * would buy little: 403 is already reported as "may be fine for a visitor,
2903
+ * cannot be checked from here" rather than as a broken link, which is the
2904
+ * right answer either way.
2905
+ */
2906
+ return code === 405 || code === 501;
2907
+ }
2908
+ async function probeUrl(rawUrl, options = {}) {
2909
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS$1;
2910
+ const maxRedirects = options.maxRedirects ?? DEFAULT_MAX_REDIRECTS;
2911
+ const now = options.now ?? (() => Date.now());
2912
+ const started = now();
2913
+ const deadline = started + timeoutMs;
2914
+ let url;
2915
+ try {
2916
+ url = new URL(rawUrl.trim());
2917
+ } catch {
2918
+ return {
2919
+ kind: "skipped",
2920
+ message: "Not opened: this is not a URL."
2921
+ };
2922
+ }
2923
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
2924
+ return {
2925
+ kind: "skipped",
2926
+ message: "Not opened: only http:// and https:// can be checked."
2927
+ };
2928
+ }
2929
+ let method = "HEAD";
2930
+ let redirects = 0;
2931
+ for (;;) {
2932
+ const remaining = deadline - now();
2933
+ if (remaining <= 0) {
2934
+ return {
2935
+ kind: "timeout",
2936
+ ms: timeoutMs
2937
+ };
2938
+ }
2939
+ /*
2940
+ * A hostname that is ALREADY an address never reaches the lookup.
2941
+ *
2942
+ * `net.connect` checks for an IP literal first and connects straight to
2943
+ * it, so `guardedLookup` is simply not called for
2944
+ * `http://169.254.169.254/` — which is the single most valuable URL an
2945
+ * attacker could ask this server to open. Checked here, per hop, because a
2946
+ * redirect can introduce one at any point in the chain.
2947
+ *
2948
+ * This was a real hole, found by a test that asserted the local server
2949
+ * received nothing and watched it receive something.
2950
+ */
2951
+ const literal = bareHost(url.hostname);
2952
+ if (net.isIP(literal) !== 0) {
2953
+ const reason = blockedAddressReason(literal);
2954
+ if (reason !== null) {
2955
+ return {
2956
+ kind: "unreachable",
2957
+ message: `${literal} is ${describeBlocked(reason)}`
2958
+ };
2959
+ }
2960
+ }
2961
+ let response;
2962
+ try {
2963
+ response = await requestOnce(url, method, remaining, options.request);
2964
+ } catch (error) {
2965
+ const message = error instanceof Error ? error.message : String(error);
2966
+ if (message === TIMED_OUT) {
2967
+ return {
2968
+ kind: "timeout",
2969
+ ms: timeoutMs
2970
+ };
2971
+ }
2972
+ return {
2973
+ kind: "unreachable",
2974
+ message
2975
+ };
2976
+ }
2977
+ if (method === "HEAD" && needsGetFallback(response.code)) {
2978
+ method = "GET";
2979
+ continue;
2980
+ }
2981
+ const location = response.location;
2982
+ if (location !== undefined && response.code >= 300 && response.code < 400) {
2983
+ if (redirects >= maxRedirects) {
2984
+ return {
2985
+ kind: "unreachable",
2986
+ message: `too many redirects (${maxRedirects})`
2987
+ };
2988
+ }
2989
+ let next;
2990
+ try {
2991
+ next = new URL(location, url);
2992
+ } catch {
2993
+ return {
2994
+ kind: "unreachable",
2995
+ message: `redirected to something that is not a URL (${location})`
2996
+ };
2997
+ }
2998
+ if (next.protocol !== "http:" && next.protocol !== "https:") {
2999
+ // A redirect to `file:` or `gopher:` is a redirect out of what this
3000
+ // is allowed to open, and the address guard would never see it.
3001
+ return {
3002
+ kind: "unreachable",
3003
+ message: `redirected to ${next.protocol}//, which cannot be checked`
3004
+ };
3005
+ }
3006
+ url = next;
3007
+ redirects++;
3008
+ // A redirect answers the method question too: a server that refused
3009
+ // HEAD at the old URL says nothing about the new one.
3010
+ method = "HEAD";
3011
+ continue;
3012
+ }
3013
+ return {
3014
+ kind: "answered",
3015
+ code: response.code,
3016
+ finalUrl: url.toString(),
3017
+ ms: Math.max(0, Math.round(now() - started))
3018
+ };
3019
+ }
3020
+ }
3021
+
3022
+ /**
3023
+ * A hostname with the IPv6 brackets off.
3024
+ *
3025
+ * `new URL("http://[::1]/").hostname` is `"[::1]"`, brackets and all, and
3026
+ * `net.isIP` says 0 to that — so the bracketed form sailed past the literal
3027
+ * check and failed later with "host could not be found". Which looks like a
3028
+ * refusal, and is not one.
3029
+ */
3030
+ function bareHost(hostname) {
3031
+ return hostname.startsWith("[") && hostname.endsWith("]") ? hostname.slice(1, -1) : hostname;
3032
+ }
3033
+ const TIMED_OUT = "val:link-check-timeout";
3034
+ function requestOnce(url, method, timeoutMs, requestImpl) {
3035
+ const impl = requestImpl ?? (url.protocol === "http:" ? http.request : https.request);
3036
+ return new Promise((resolve, reject) => {
3037
+ let settled = false;
3038
+ const finish = fn => {
3039
+ if (settled) return;
3040
+ settled = true;
3041
+ fn();
3042
+ };
3043
+ const req = impl({
3044
+ protocol: url.protocol,
3045
+ hostname: url.hostname,
3046
+ port: url.port === "" ? undefined : url.port,
3047
+ path: `${url.pathname}${url.search}`,
3048
+ method,
3049
+ headers: {
3050
+ // No cookies, no authorization, no forwarded headers: this request
3051
+ // is the server's own and carries none of its identity.
3052
+ "user-agent": USER_AGENT,
3053
+ accept: "*/*",
3054
+ // A redirect chain is followed by hand, one guarded hop at a time.
3055
+ "accept-encoding": "identity"
3056
+ },
3057
+ // Every DNS answer is checked before a socket is opened. See
3058
+ // `guardedLookup` — this is the line that makes the whole feature safe.
3059
+ lookup: guardedLookup(defaultLookup()),
3060
+ // Node's default agent keeps sockets alive between requests, and a
3061
+ // pooled socket was resolved by a PREVIOUS lookup. A fresh connection
3062
+ // per probe is what keeps the guard in front of every one of them.
3063
+ agent: false,
3064
+ timeout: timeoutMs
3065
+ }, res => {
3066
+ const location = res.headers.location;
3067
+ // The body is never read: a status and a `Location` is the whole
3068
+ // answer, and downloading a page to throw it away is bandwidth spent
3069
+ // on somebody else's server.
3070
+ res.destroy();
3071
+ finish(() => resolve({
3072
+ code: res.statusCode ?? 0,
3073
+ location: typeof location === "string" ? location : undefined
3074
+ }));
3075
+ });
3076
+ req.on("timeout", () => {
3077
+ req.destroy();
3078
+ finish(() => reject(new Error(TIMED_OUT)));
3079
+ });
3080
+ req.on("error", error => {
3081
+ finish(() => reject(new Error(readableError(error))));
3082
+ });
3083
+ req.end();
3084
+ });
3085
+ }
3086
+
3087
+ /** `dns.lookup`, read lazily so a test can swap `node:dns` wholesale. */
3088
+ function defaultLookup() {
3089
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
3090
+ const dns = require("node:dns");
3091
+ return dns.lookup;
3092
+ }
3093
+
3094
+ /** What went wrong, in words rather than in errno. */
3095
+ function readableError(error) {
3096
+ /*
3097
+ * The guard's own refusal, recognised by its message rather than by a code.
3098
+ * `net` destroys the socket with the Error the lookup gave it, and the
3099
+ * message survives that trip verbatim; whether a custom `code` does is an
3100
+ * implementation detail this does not need to bet on.
3101
+ */
3102
+ if (error.message === REFUSED_MESSAGE) {
3103
+ return REFUSED_MESSAGE;
3104
+ }
3105
+ switch (error.code) {
3106
+ case "ENOTFOUND":
3107
+ case "EAI_AGAIN":
3108
+ return "the host could not be found";
3109
+ case "ECONNREFUSED":
3110
+ return "the connection was refused";
3111
+ case "ECONNRESET":
3112
+ return "the connection was reset";
3113
+ case "EHOSTUNREACH":
3114
+ case "ENETUNREACH":
3115
+ return "the host could not be reached";
3116
+ case "CERT_HAS_EXPIRED":
3117
+ return "its certificate has expired";
3118
+ case "ERR_TLS_CERT_ALTNAME_INVALID":
3119
+ return "its certificate is for a different host";
3120
+ case "DEPTH_ZERO_SELF_SIGNED_CERT":
3121
+ case "SELF_SIGNED_CERT_IN_CHAIN":
3122
+ return "its certificate is self-signed";
3123
+ default:
3124
+ /*
3125
+ * A fixed string, not `error.message`.
3126
+ *
3127
+ * Whatever Node or OpenSSL put in there is written for a server log, and
3128
+ * some of it names things the caller should not learn - a resolved
3129
+ * address, a certificate's subject, a path. The cases above cover what is
3130
+ * worth telling an editor; anything else is noise to them and a leak
3131
+ * waiting to happen.
3132
+ */
3133
+ return "the request failed";
3134
+ }
3135
+ }
3136
+
2568
3137
  /* eslint-disable @typescript-eslint/no-unused-vars */
2569
3138
  const jsonOps = new JSONOps();
2570
3139
  /**
@@ -4520,6 +5089,9 @@ class ValOps {
4520
5089
  // group whose id is undefined, all the way to the client.
4521
5090
  ...(saveRes.value.patchGroupId !== undefined ? {
4522
5091
  patchGroupId: saveRes.value.patchGroupId
5092
+ } : {}),
5093
+ ...(saveRes.value.headVersion !== undefined ? {
5094
+ headVersion: saveRes.value.headVersion
4523
5095
  } : {})
4524
5096
  });
4525
5097
  }
@@ -7672,6 +8244,16 @@ const GetApplicablePatches = z.object({
7672
8244
  commitSha: z.string()
7673
8245
  }).nullable()
7674
8246
  })),
8247
+ /**
8248
+ * The head of the chain. See `OrderedPatches.headPatchId`. Optional because
8249
+ * a content service that predates it sends nothing.
8250
+ */
8251
+ headPatchId: PatchId$1.nullable().optional(),
8252
+ /**
8253
+ * The chain version of that head. See `OrderedPatches.headVersion`.
8254
+ * Optional for the same reason.
8255
+ */
8256
+ headVersion: z.number().optional(),
7675
8257
  commits: z.array(z.object({
7676
8258
  commitSha: z.string(),
7677
8259
  /*
@@ -7747,15 +8329,39 @@ const SavePatchResponse = z.object({
7747
8329
  * Optional: a content API that predates patch groups does not send one, and
7748
8330
  * absence has to keep meaning "no groups here" rather than failing the save.
7749
8331
  */
7750
- patchGroupId: z.string().optional()
8332
+ patchGroupId: z.string().optional(),
8333
+ /**
8334
+ * The chain version this write made, comparable with `headVersion` on the
8335
+ * listing. Optional: a content service that predates it sends nothing.
8336
+ */
8337
+ headVersion: z.number().optional()
7751
8338
  });
7752
8339
  const DeletePatchesResponse = z.object({
7753
8340
  deleted: z.array(PatchId),
7754
8341
  errors: z.array(z.object({
7755
8342
  message: z.string(),
7756
8343
  patchId: PatchId
7757
- })).optional()
8344
+ })).optional(),
8345
+ /**
8346
+ * The chain version each branch the delete changed is now at, keyed by
8347
+ * branch. Optional: a content service that predates it sends none.
8348
+ */
8349
+ headVersions: z.record(z.string(), z.number()).optional()
7758
8350
  });
8351
+ /**
8352
+ * This client's own branch's entry in a per-branch version map.
8353
+ *
8354
+ * A delete can span branches, so the content service answers per branch. With
8355
+ * no branch of its own (a build with no repository, where the service resolves
8356
+ * it), the only entry is ours when there is exactly one; with several, none can
8357
+ * be picked, and a wrong one would floor this client at another chain's count.
8358
+ */
8359
+ function ownBranchVersion(headVersions, branch) {
8360
+ if (headVersions === undefined) return undefined;
8361
+ if (branch !== undefined) return headVersions[branch];
8362
+ const versions = Object.values(headVersions);
8363
+ return versions.length === 1 ? versions[0] : undefined;
8364
+ }
7759
8365
  const SavePatchFileResponse = z.object({
7760
8366
  patchId: PatchId,
7761
8367
  filePath: ModuleFilePath
@@ -7775,7 +8381,9 @@ const CommitResponse = z.object({
7775
8381
  */
7776
8382
  parent: z.string().optional(),
7777
8383
  tree: z.string().optional(),
7778
- branch: z.string()
8384
+ branch: z.string(),
8385
+ /** The chain version the publish moved the branch to; absent if it applied nothing. */
8386
+ headVersion: z.number().optional()
7779
8387
  });
7780
8388
  // #region history wire schemas
7781
8389
  //
@@ -8139,7 +8747,9 @@ class ValOpsHttp extends ValOps {
8139
8747
  * An allow list rather than a prefix check, because this method holds a
8140
8748
  * credential and the browser chooses the path. `/publish/{id}` and its three
8141
8749
  * steps are the publish conversation; `/build-target` is what a build needs
8142
- * to know before it starts; `/project-source` is what it builds.
8750
+ * to know before it starts; `/project-source` is what it builds;
8751
+ * `/update-target` is the same question as `/build-target` for a managed
8752
+ * project moving onto its template's current dependencies.
8143
8753
  *
8144
8754
  * `/project-source` is here rather than on a route of its own because it is
8145
8755
  * one of the three things a publish asks for and none of them are useful
@@ -8153,7 +8763,7 @@ class ValOpsHttp extends ValOps {
8153
8763
  * segment gets through.
8154
8764
  */
8155
8765
  static publishApiPathAllowed(path) {
8156
- if (path === "/build-target" || path === "/project-source" || path === "/publish") {
8766
+ if (path === "/build-target" || path === "/project-source" || path === "/update-target" || path === "/publish") {
8157
8767
  return true;
8158
8768
  }
8159
8769
  return /^\/publish\/[A-Za-z0-9_-]+(\/(artifacts|verify|promote))?$/.test(path);
@@ -8397,6 +9007,16 @@ class ValOpsHttp extends ValOps {
8397
9007
  deployments: allPatchData.deployments || [],
8398
9008
  patches,
8399
9009
  appliedPatches,
9010
+ /*
9011
+ * The CHAIN head, not the publish head below. Spread: absent is a content
9012
+ * service that does not report it, which is not the same as `null`.
9013
+ */
9014
+ ...(allPatchData.headPatchId !== undefined ? {
9015
+ headPatchId: allPatchData.headPatchId
9016
+ } : {}),
9017
+ ...(allPatchData.headVersion !== undefined ? {
9018
+ headVersion: allPatchData.headVersion
9019
+ } : {}),
8400
9020
  /*
8401
9021
  * The PUBLISH head, which is not `commitSha`.
8402
9022
  *
@@ -8521,6 +9141,10 @@ class ValOpsHttp extends ValOps {
8521
9141
  * the same treatment and a home on `OrderedPatches` first.
8522
9142
  */
8523
9143
  let commits;
9144
+ // A fact about the branch too, so taken from the first chunk that has it
9145
+ // for the same reason `commits` is.
9146
+ let headPatchId;
9147
+ let headVersion;
8524
9148
  if (patchIds === undefined || patchIds.length === 0) {
8525
9149
  return this.fetchPatchesInternal({
8526
9150
  patchIds: patchIds,
@@ -8541,6 +9165,16 @@ class ValOpsHttp extends ValOps {
8541
9165
  if (commits === undefined && res.commits !== undefined) {
8542
9166
  commits = res.commits;
8543
9167
  }
9168
+ /*
9169
+ * The NEWEST head among the chunks: each is its own request, so a later
9170
+ * one can have seen a write an earlier one did not. Taken with its own
9171
+ * version, so the two always describe one read. Without versions (an
9172
+ * older content service) the first head stands, as before.
9173
+ */
9174
+ if (res.headPatchId !== undefined && (headPatchId === undefined || res.headVersion !== undefined && (headVersion === undefined || res.headVersion > headVersion))) {
9175
+ headPatchId = res.headPatchId;
9176
+ headVersion = res.headVersion;
9177
+ }
8544
9178
  }
8545
9179
  // Chunking is a query-string-length workaround, NOT a filter: the content
8546
9180
  // api returns every applicable patch per request regardless of which
@@ -8573,6 +9207,12 @@ class ValOpsHttp extends ValOps {
8573
9207
  // readers do — sees the same shape the unchunked path gives it.
8574
9208
  ...(commits !== undefined ? {
8575
9209
  commits
9210
+ } : {}),
9211
+ ...(headPatchId !== undefined ? {
9212
+ headPatchId
9213
+ } : {}),
9214
+ ...(headVersion !== undefined ? {
9215
+ headVersion
8576
9216
  } : {})
8577
9217
  };
8578
9218
  }
@@ -8668,7 +9308,13 @@ class ValOpsHttp extends ValOps {
8668
9308
  commits,
8669
9309
  deployments,
8670
9310
  patches,
8671
- errors
9311
+ errors,
9312
+ ...(data.headPatchId !== undefined ? {
9313
+ headPatchId: data.headPatchId
9314
+ } : {}),
9315
+ ...(data.headVersion !== undefined ? {
9316
+ headVersion: data.headVersion
9317
+ } : {})
8672
9318
  };
8673
9319
  }
8674
9320
  console.error("Could not parse patches response. Error: " + fromError(parsed.error));
@@ -9038,6 +9684,9 @@ class ValOpsHttp extends ValOps {
9038
9684
  */
9039
9685
  ...(parsed.data.patchGroupId !== undefined ? {
9040
9686
  patchGroupId: parsed.data.patchGroupId
9687
+ } : {}),
9688
+ ...(parsed.data.headVersion !== undefined ? {
9689
+ headVersion: parsed.data.headVersion
9041
9690
  } : {})
9042
9691
  });
9043
9692
  }
@@ -9361,18 +10010,25 @@ class ValOpsHttp extends ValOps {
9361
10010
  if (res.ok) {
9362
10011
  const parsed = DeletePatchesResponse.safeParse(await res.json());
9363
10012
  if (parsed.success) {
10013
+ var _this$git;
9364
10014
  const errors = {};
9365
10015
  for (const err of parsed.data.errors || []) {
9366
10016
  errors[err.patchId] = err;
9367
10017
  }
10018
+ const headVersion = ownBranchVersion(parsed.data.headVersions, (_this$git = this.git) === null || _this$git === void 0 ? void 0 : _this$git.branch);
10019
+ const version = headVersion !== undefined ? {
10020
+ headVersion
10021
+ } : {};
9368
10022
  if (Object.keys(errors).length === 0) {
9369
10023
  return {
9370
- deleted: parsed.data.deleted
10024
+ deleted: parsed.data.deleted,
10025
+ ...version
9371
10026
  };
9372
10027
  }
9373
10028
  return {
9374
10029
  deleted: parsed.data.deleted,
9375
- errors
10030
+ errors,
10031
+ ...version
9376
10032
  };
9377
10033
  }
9378
10034
  return {
@@ -9502,6 +10158,9 @@ class ValOpsHttp extends ValOps {
9502
10158
  } : {}),
9503
10159
  ...(parsed.data.tree !== undefined ? {
9504
10160
  tree: parsed.data.tree
10161
+ } : {}),
10162
+ ...(parsed.data.headVersion !== undefined ? {
10163
+ headVersion: parsed.data.headVersion
9505
10164
  } : {})
9506
10165
  };
9507
10166
  }
@@ -12271,7 +12930,10 @@ const ValServer = (valModules, options, callbacks) => {
12271
12930
  ...(sourceMode ? {
12272
12931
  sourceMode
12273
12932
  } : {}),
12274
- config: options.config
12933
+ // Not `options.config` verbatim: in proxy mode the branch the
12934
+ // server resolved is filled in where the file did not name one.
12935
+ // See `clientConfig`.
12936
+ config: clientConfig(options)
12275
12937
  }
12276
12938
  };
12277
12939
  }
@@ -12364,6 +13026,46 @@ const ValServer = (valModules, options, callbacks) => {
12364
13026
  };
12365
13027
  }
12366
13028
  },
13029
+ "/external-urls/check": {
13030
+ POST: async req => {
13031
+ /*
13032
+ * The same door as every other route, which in fs mode is an open one.
13033
+ *
13034
+ * `getAuth` returns anonymous success when there is no `valSecret` and
13035
+ * nothing requires auth — a developer's own machine, where there is no
13036
+ * credential to require and 29 other routes already behave this way.
13037
+ * So this is not a session gate in fs mode, and it is not meant to be
13038
+ * the thing that makes the endpoint safe: what does that is
13039
+ * `addressGuard`, which refuses every address that is not on the
13040
+ * public internet, on the RESOLVED address, at every redirect hop.
13041
+ */
13042
+ const auth = getAuth(req.cookies);
13043
+ if (auth.error) {
13044
+ return {
13045
+ status: 401,
13046
+ json: {
13047
+ message: auth.error
13048
+ }
13049
+ };
13050
+ }
13051
+ /*
13052
+ * Every URL in the batch at once, and nothing beyond it.
13053
+ *
13054
+ * The concurrency here is the batch size the route caps at, which is
13055
+ * what keeps "check a thousand links" from becoming a thousand
13056
+ * simultaneous outbound sockets: the client sends ten, waits, sends
13057
+ * the next ten. Doing them in parallel WITHIN a batch is what makes a
13058
+ * batch worth having — ten five-second timeouts in series is a minute.
13059
+ */
13060
+ const results = await Promise.all(req.body.urls.map(async url => [url, await probeUrl(url)]));
13061
+ return {
13062
+ status: 200,
13063
+ json: {
13064
+ results: Object.fromEntries(results)
13065
+ }
13066
+ };
13067
+ }
13068
+ },
12367
13069
  "/direct-file-upload-settings": {
12368
13070
  POST: async req => {
12369
13071
  const cookies = req.cookies;
@@ -12671,6 +13373,13 @@ const ValServer = (valModules, options, callbacks) => {
12671
13373
  * re-read when a fetch has missing ids to ask for.
12672
13374
  */
12673
13375
  let patchGroupIdFromStore;
13376
+ /*
13377
+ * The chain version the LAST patch made — the head this batch leaves.
13378
+ * The client keeps the highest version it has seen, so a `/stat` read
13379
+ * before this write cannot put its parent back behind it. Absent in
13380
+ * `fs` mode and from an older content API.
13381
+ */
13382
+ let headVersion;
12674
13383
  for (const patch of patches) {
12675
13384
  const createPatchRes = await serverOps.createPatch(patch.path, patch.patch, patch.patchId, parentRef, sessionId, authorId, patchGroup);
12676
13385
  if (result.isErr(createPatchRes)) {
@@ -12707,6 +13416,7 @@ const ValServer = (valModules, options, callbacks) => {
12707
13416
  if (createPatchRes.value.patchGroupId !== undefined) {
12708
13417
  patchGroupIdFromStore = createPatchRes.value.patchGroupId;
12709
13418
  }
13419
+ headVersion = createPatchRes.value.headVersion;
12710
13420
  }
12711
13421
  }
12712
13422
  return {
@@ -12719,6 +13429,9 @@ const ValServer = (valModules, options, callbacks) => {
12719
13429
  // client reads absence as "staging is not available here".
12720
13430
  ...(patchGroupIdFromStore !== undefined ? {
12721
13431
  patchGroupId: patchGroupIdFromStore
13432
+ } : {}),
13433
+ ...(headVersion !== undefined ? {
13434
+ headVersion
12722
13435
  } : {})
12723
13436
  }
12724
13437
  };
@@ -12858,7 +13571,7 @@ const ValServer = (valModules, options, callbacks) => {
12858
13571
  };
12859
13572
  },
12860
13573
  DELETE: async req => {
12861
- var _req$body;
13574
+ var _req$body, _req$body2;
12862
13575
  const query = req.query;
12863
13576
  const cookies = req.cookies;
12864
13577
  const auth = getAuth(cookies);
@@ -12911,6 +13624,17 @@ const ValServer = (valModules, options, callbacks) => {
12911
13624
  }
12912
13625
  };
12913
13626
  }
13627
+ if (((_req$body2 = req.body) === null || _req$body2 === void 0 ? void 0 : _req$body2.reportHeadVersion) === true) {
13628
+ return {
13629
+ status: 200,
13630
+ json: {
13631
+ deleted: ids,
13632
+ ...("headVersion" in deleteRes && deleteRes.headVersion !== undefined ? {
13633
+ headVersion: deleteRes.headVersion
13634
+ } : {})
13635
+ }
13636
+ };
13637
+ }
12914
13638
  return {
12915
13639
  status: 200,
12916
13640
  json: ids
@@ -13957,6 +14681,9 @@ const ValServer = (valModules, options, callbacks) => {
13957
14681
  ...(managedBranch !== null ? {
13958
14682
  branch: managedBranch
13959
14683
  } : {}),
14684
+ ...(commitRes.headVersion !== undefined ? {
14685
+ headVersion: commitRes.headVersion
14686
+ } : {}),
13960
14687
  ...(committedBinaries !== null ? {
13961
14688
  binaryFiles: committedBinaries.files,
13962
14689
  ...(committedBinaries.unread.length > 0 ? {
@@ -16395,7 +17122,7 @@ async function getFileBufferFromRemote(ref, fileExt, currentFileHash, projectRoo
16395
17122
  async function downloadFileFromRemote(ref, filePath) {
16396
17123
  return new Promise((resolve, reject) => {
16397
17124
  const url = new URL(ref);
16398
- const client = url.protocol === "https:" ? https : http;
17125
+ const client = url.protocol === "https:" ? https$1 : http$1;
16399
17126
  const request = client.get(url, response => {
16400
17127
  if (response.statusCode && response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) {
16401
17128
  // Handle redirects