Diffinery

homeflare/celldpublic

feat(node): node:url

Jason Schwarzenberger authored 1 parent 5189149commit 1a74a6bf5cfd1b8d09d3a103111999e7b7983e9cBrowse files
8 files changed+380−0
Files (8)
modifiedHOMEFLARE.md+1−0View file
@@ -21,6 +21,7 @@
2121 |---|---|
2222 | `node:net` `isIP` / `isIPv4` / `isIPv6`; `node:dns` and `node:dns/promises` `lookup()` | Fedify checks a URL's host with both before fetching it, so palm's remote lookups failed with `node:net.isIP is not implemented in celld`. `lookup()` uses the node's resolver through a new `__dns_lookup` op, with `connect()`'s egress rules. |
2323 | `Response.clone()` on a streaming body | celld threw `Cannot clone a streaming response before consumption`; workerd tees the body, as celld's `Request.clone()` already did. palm's media proxy returns a fetched image and caches `response.clone()`. |
24+| `node:url` (all but the legacy `parse` / `resolve`) | celld had no `node:url`; Fedify's WebFinger handler calls `domainToASCII` and `domainToUnicode`. Both run Node's own steps (the input set as a `ws://x` hostname) through new host ops on the `url` crate. |
2425
2526 ## Building
2627
modifiedcrates/celld/js.rs+3−0View file
@@ -6743,6 +6743,8 @@
67436743 "__tcp_close" => tcp::op_tcp_close,
67446744 "__tcp_starttls" => tcp::op_tcp_starttls,
67456745 "__dns_lookup" => dns::op_dns_lookup,
6746+ "__domain_to_ascii" => node_url::op_domain_to_ascii,
6747+ "__domain_to_unicode" => node_url::op_domain_to_unicode,
67466748 "__container_running" => container::op_container_running,
67476749 "__container_address" => container::op_container_address,
67486750 "__container_start" => container::op_container_start,
@@ -9958,6 +9960,7 @@
99589960 mod crypto;
99599961 mod dns;
99609962 mod html_rewriter;
9963+mod node_url;
99619964 mod tcp;
99629965 #[cfg(celld_internal_tests)]
99639966 pub use tcp::test_extra_tls_root;
modifiedcrates/celld/js/modules.rs+8−0View file
@@ -23,6 +23,7 @@
2323 static_source!(NODE_OS_SOURCE, "node_os.js");
2424 static_source!(NODE_NET_SOURCE, "node_net.js");
2525 static_source!(NODE_DNS_SOURCE, "node_dns.js");
26+static_source!(NODE_URL_SOURCE, "node_url.js");
2627 static_source!(NODE_PATH_SOURCE, "node_path.js");
2728 static_source!(NODE_BUFFER_SOURCE, "node_buffer.js");
2829 static_source!(NODE_CRYPTO_SOURCE, "node_crypto.js");
@@ -51,6 +52,7 @@
5152 ("node_os.js", &NODE_OS_SOURCE),
5253 ("node_net.js", &NODE_NET_SOURCE),
5354 ("node_dns.js", &NODE_DNS_SOURCE),
55+ ("node_url.js", &NODE_URL_SOURCE),
5456 ("node_path.js", &NODE_PATH_SOURCE),
5557 ("node_buffer.js", &NODE_BUFFER_SOURCE),
5658 ("node_crypto.js", &NODE_CRYPTO_SOURCE),
@@ -408,7 +410,13 @@
408410 global: "__dnsPromisesModule",
409411 source: &NODE_DNS_SOURCE,
410412 },
413+ // Homeflare patch: node:url without the legacy parser.
411414 LazyModule {
415+ specs: &["url", "node:url"],
416+ global: "__urlModule",
417+ source: &NODE_URL_SOURCE,
418+ },
419+ LazyModule {
412420 specs: &["path", "node:path", "path/posix", "node:path/posix"],
413421 global: "__pathModule",
414422 source: &NODE_PATH_SOURCE,
addedcrates/celld/js/node_url.js+231−0View file
@@ -1,0 +1,231 @@
1+// node:url for celld (Homeflare patch).
2+//
3+// The WHATWG side of Node's url module: URL and URLSearchParams (the
4+// globals), domainToASCII and domainToUnicode (through the __domain_to_ascii
5+// and __domain_to_unicode host ops, which follow Node's own steps),
6+// fileURLToPath and pathToFileURL (POSIX, as in workerd), urlToHttpOptions,
7+// and format() for a URL or a legacy URL object. Fedify uses domainToASCII
8+// and domainToUnicode for WebFinger handles.
9+//
10+// The legacy parser (parse, resolve, resolveObject, Url) isn't here; calling
11+// one throws with its name, as the generic stub did.
12+//
13+// Injected lazily, so an isolate that never imports node:url pays nothing.
14+(() => {
15+ "use strict";
16+
17+ const nodeError = (Type, code, message) => {
18+ const error = new Type(message);
19+ error.code = code;
20+ return error;
21+ };
22+ const invalidArgType = (name, expected, value) =>
23+ nodeError(
24+ TypeError,
25+ "ERR_INVALID_ARG_TYPE",
26+ `The "${name}" argument must be ${expected}. Received ${value === null ? "null" : typeof value}`,
27+ );
28+
29+ // Node throws only when the argument is missing; undefined is "undefined".
30+ const domainToASCII = (...args) => {
31+ if (args.length < 1) {
32+ throw nodeError(TypeError, "ERR_MISSING_ARGS", 'The "domain" argument must be specified');
33+ }
34+ return __domain_to_ascii(`${args[0]}`);
35+ };
36+ const domainToUnicode = (...args) => {
37+ if (args.length < 1) {
38+ throw nodeError(TypeError, "ERR_MISSING_ARGS", 'The "domain" argument must be specified');
39+ }
40+ return __domain_to_unicode(`${args[0]}`);
41+ };
42+
43+ const isURL = (value) =>
44+ value instanceof URL ||
45+ (value != null && typeof value.href === "string" && typeof value.protocol === "string" &&
46+ value.auth === undefined && value.path === undefined);
47+
48+ // POSIX, as workerd: no drive letters, and a file URL's host must be empty.
49+ const fileURLToPath = (path) => {
50+ if (typeof path === "string") path = new URL(path);
51+ else if (!isURL(path)) throw invalidArgType("path", "of type string or an instance of URL", path);
52+ if (path.protocol !== "file:") {
53+ throw nodeError(TypeError, "ERR_INVALID_URL_SCHEME", "The URL must be of scheme file");
54+ }
55+ if (path.hostname !== "") {
56+ throw nodeError(TypeError, "ERR_INVALID_FILE_URL_HOST", 'File URL host must be "localhost" or empty on linux');
57+ }
58+ const pathname = path.pathname;
59+ for (let n = 0; n < pathname.length; n++) {
60+ if (pathname[n] === "%") {
61+ const third = pathname.codePointAt(n + 2) | 0x20;
62+ if (pathname[n + 1] === "2" && third === 102) {
63+ throw nodeError(TypeError, "ERR_INVALID_FILE_URL_PATH", "File URL path must not include encoded / characters");
64+ }
65+ }
66+ }
67+ return decodeURIComponent(pathname);
68+ };
69+
70+ // path.posix.resolve against "/", the Workers working directory.
71+ const resolvePosix = (input) => {
72+ const parts = [];
73+ for (const segment of `/${input}`.split("/")) {
74+ if (segment === "" || segment === ".") continue;
75+ if (segment === "..") parts.pop();
76+ else parts.push(segment);
77+ }
78+ return `/${parts.join("/")}`;
79+ };
80+ const pathToFileURL = (filepath) => {
81+ if (typeof filepath !== "string") throw invalidArgType("path", "of type string", filepath);
82+ let resolved = resolvePosix(filepath);
83+ if (filepath.endsWith("/") && !resolved.endsWith("/")) resolved += "/";
84+ resolved = resolved
85+ .replace(/%/g, "%25")
86+ .replace(/\\/g, "%5C")
87+ .replace(/\n/g, "%0A")
88+ .replace(/\r/g, "%0D")
89+ .replace(/\t/g, "%09")
90+ .replace(/\?/g, "%3F")
91+ .replace(/#/g, "%23");
92+ return new URL(`file://${resolved}`);
93+ };
94+
95+ const urlToHttpOptions = (url) => {
96+ const { hostname, pathname, port, username, password, search } = url;
97+ const options = {
98+ __proto__: null,
99+ ...url,
100+ protocol: url.protocol,
101+ hostname: hostname && hostname[0] === "[" ? hostname.slice(1, -1) : hostname,
102+ hash: url.hash,
103+ search,
104+ pathname,
105+ path: `${pathname || ""}${search || ""}`,
106+ href: url.href,
107+ };
108+ if (port !== "") options.port = Number(port);
109+ if (username || password) {
110+ options.auth = `${decodeURIComponent(username)}:${decodeURIComponent(password)}`;
111+ }
112+ return options;
113+ };
114+
115+ // format(URL, { auth, fragment, search, unicode }).
116+ const formatURL = (url, options) => {
117+ const opts = options === undefined ? {} : options;
118+ if (opts === null || typeof opts !== "object") throw invalidArgType("options", "of type object", opts);
119+ const auth = opts.auth !== undefined ? Boolean(opts.auth) : true;
120+ const fragment = opts.fragment !== undefined ? Boolean(opts.fragment) : true;
121+ const search = opts.search !== undefined ? Boolean(opts.search) : true;
122+ const unicode = Boolean(opts.unicode);
123+ let out = url.protocol;
124+ if (url.href.startsWith(`${url.protocol}//`)) {
125+ out += "//";
126+ if (auth && (url.username || url.password)) {
127+ out += url.username;
128+ if (url.password) out += `:${url.password}`;
129+ out += "@";
130+ }
131+ out += unicode ? domainToUnicode(url.hostname) || url.hostname : url.hostname;
132+ if (url.port) out += `:${url.port}`;
133+ }
134+ out += url.pathname;
135+ if (search) out += url.search;
136+ if (fragment) out += url.hash;
137+ return out;
138+ };
139+
140+ const slashedProtocols = new Set([
141+ "http", "http:", "https", "https:", "ftp", "ftp:", "gopher", "gopher:",
142+ "file", "file:", "ws", "ws:", "wss", "wss:",
143+ ]);
144+ const queryValue = (value) => {
145+ if (typeof value === "string") return value;
146+ if (typeof value === "number" && Number.isFinite(value)) return `${value}`;
147+ if (typeof value === "bigint" || typeof value === "boolean") return `${value}`;
148+ return "";
149+ };
150+ const stringifyQuery = (query) =>
151+ Object.keys(query)
152+ .map((key) => {
153+ const name = encodeURIComponent(key);
154+ const value = query[key];
155+ if (Array.isArray(value)) {
156+ return value.map((v) => `${name}=${encodeURIComponent(queryValue(v))}`).join("&");
157+ }
158+ return `${name}=${encodeURIComponent(queryValue(value))}`;
159+ })
160+ .filter(Boolean)
161+ .join("&");
162+
163+ // Node's Url.prototype.format, for a legacy URL object.
164+ const formatObject = (object) => {
165+ let auth = object.auth || "";
166+ if (auth) auth = `${encodeURIComponent(auth).replace(/%3A/gi, ":")}@`;
167+ let protocol = object.protocol || "";
168+ let pathname = object.pathname || "";
169+ let hash = object.hash || "";
170+ let host = "";
171+ let query = "";
172+ if (object.host) {
173+ host = auth + object.host;
174+ } else if (object.hostname) {
175+ const hostname = object.hostname;
176+ host = auth + (hostname.includes(":") && hostname[0] !== "[" ? `[${hostname}]` : hostname);
177+ if (object.port) host += `:${object.port}`;
178+ }
179+ if (object.query !== null && typeof object.query === "object") query = stringifyQuery(object.query);
180+ let search = object.search || (query && `?${query}`) || "";
181+ if (protocol && !protocol.endsWith(":")) protocol += ":";
182+ pathname = pathname.replace(/[#?]/g, (c) => (c === "#" ? "%23" : "%3F"));
183+ if (object.slashes || slashedProtocols.has(protocol)) {
184+ if (object.slashes || host) {
185+ if (pathname && pathname[0] !== "/") pathname = `/${pathname}`;
186+ host = `//${host}`;
187+ } else if (protocol.startsWith("file")) {
188+ host = "//";
189+ }
190+ }
191+ search = search.replace(/#/g, "%23");
192+ if (hash && hash[0] !== "#") hash = `#${hash}`;
193+ if (search && search[0] !== "?") search = `?${search}`;
194+ return protocol + host + pathname + search + hash;
195+ };
196+
197+ const notImplemented = (name) => {
198+ const fn = function () {
199+ throw new Error(`node:url.${name} is not implemented in celld`);
200+ };
201+ Object.defineProperty(fn, "name", { value: name });
202+ return fn;
203+ };
204+
205+ const format = (urlObject, options) => {
206+ if (urlObject instanceof URL) return formatURL(urlObject, options);
207+ if (typeof urlObject === "string") {
208+ // Node runs a string through the legacy parser first.
209+ throw new Error("node:url.format(string) is not implemented in celld (it needs url.parse)");
210+ }
211+ if (urlObject === null || typeof urlObject !== "object") {
212+ throw invalidArgType("urlObject", "one of type object or string", urlObject);
213+ }
214+ return formatObject(urlObject);
215+ };
216+
217+ __celld.__urlModule = {
218+ URL,
219+ URLSearchParams,
220+ domainToASCII,
221+ domainToUnicode,
222+ fileURLToPath,
223+ pathToFileURL,
224+ urlToHttpOptions,
225+ format,
226+ parse: notImplemented("parse"),
227+ resolve: notImplemented("resolve"),
228+ resolveObject: notImplemented("resolveObject"),
229+ Url: notImplemented("Url"),
230+ };
231+})();
addedcrates/celld/js/node_url.rs+67−0View file
@@ -1,0 +1,67 @@
1+//! Host ops for `node:url` `domainToASCII()` and `domainToUnicode()`
2+//! (Homeflare patch).
3+//!
4+//! Node sets the input as the hostname of `ws://x` (a special scheme, so it
5+//! gets the WHATWG host parser with IDNA) and reads the hostname back, or
6+//! answers "" when the setter refuses it. The same steps run here through the
7+//! `url` crate's setter, so the answers match Node's: IPv4 addresses are
8+//! normalized and kept, and anything after a `/`, `?`, `#` or `:` is ignored.
9+
10+/// The ASCII hostname Node's `domainToASCII` returns, or "" when the input
11+/// isn't a valid host.
12+fn ascii_hostname(input: &str) -> String {
13+ if input.is_empty() {
14+ return String::new();
15+ }
16+ let mut url = url::Url::parse("ws://x").expect("a valid base URL");
17+ if url::quirks::set_hostname(&mut url, input).is_err() {
18+ return String::new();
19+ }
20+ url::quirks::hostname(&url).to_string()
21+}
22+
23+pub(super) fn op_domain_to_ascii(
24+ scope: &mut v8::PinScope,
25+ args: v8::FunctionCallbackArguments,
26+ mut rv: v8::ReturnValue<v8::Value>,
27+) {
28+ let input = args.get(0).to_rust_string_lossy(scope);
29+ let out = v8::String::new(scope, &ascii_hostname(&input)).unwrap();
30+ rv.set(out.into());
31+}
32+
33+pub(super) fn op_domain_to_unicode(
34+ scope: &mut v8::PinScope,
35+ args: v8::FunctionCallbackArguments,
36+ mut rv: v8::ReturnValue<v8::Value>,
37+) {
38+ let input = args.get(0).to_rust_string_lossy(scope);
39+ let ascii = ascii_hostname(&input);
40+ // An IP address has no Unicode form; Node returns it as it is.
41+ let unicode = if ascii.is_empty()
42+ || ascii.starts_with('[')
43+ || ascii.parse::<std::net::Ipv4Addr>().is_ok()
44+ {
45+ ascii
46+ } else {
47+ url::quirks::domain_to_unicode(&ascii)
48+ };
49+ let out = v8::String::new(scope, &unicode).unwrap();
50+ rv.set(out.into());
51+}
52+
53+#[cfg(test)]
54+mod tests {
55+ use super::ascii_hostname;
56+
57+ #[test]
58+ fn matches_node() {
59+ assert_eq!(ascii_hostname("español.com"), "xn--espaol-zwa.com");
60+ assert_eq!(ascii_hostname("EXAMPLE.com"), "example.com");
61+ assert_eq!(ascii_hostname("中文.com"), "xn--fiq228c.com");
62+ assert_eq!(ascii_hostname("xn--iñvalid.com"), "");
63+ assert_eq!(ascii_hostname(""), "");
64+ assert_eq!(ascii_hostname("127.0.0.1"), "127.0.0.1");
65+ assert_eq!(ascii_hostname("example.com/path"), "example.com");
66+ }
67+}
modifieddocs/cloudflare-compat.md+4−0View file
@@ -156,6 +156,10 @@
156156 - `node:dns` and `node:dns/promises` provide `lookup()`, which resolves
157157 through the node's own resolver. The `resolve*()` functions are not
158158 implemented (Homeflare patch).
159+- `node:url` provides `URL`, `URLSearchParams`, `domainToASCII`,
160+ `domainToUnicode`, `fileURLToPath`, `pathToFileURL`, `urlToHttpOptions` and
161+ `format`. The legacy `parse`, `resolve` and `resolveObject` are not
162+ implemented (Homeflare patch).
159163 - `node:fs` provides `access`, `mkdir`, `realpath`, `stat`, `lstat`, and
160164 `readFile`. It exposes an empty, request-local `/tmp` and a read-only
161165 `/bundle` that contains the Worker modules.
addedhomeflare/smoke/node-url/index.js+60−0View file
@@ -1,0 +1,60 @@
1+// Smoke test for the node:url patch. Expected values are Node's answers for
2+// the same calls. GET / answers a JSON report; every check is { name, ok, got }.
3+import { domainToASCII, domainToUnicode, fileURLToPath, pathToFileURL, urlToHttpOptions } from "node:url";
4+import url from "node:url";
5+
6+const expectEqual = (name, got, want) => ({ name, ok: JSON.stringify(got) === JSON.stringify(want), got });
7+const expectThrows = (name, fn, code) => {
8+ try {
9+ fn();
10+ return { name, ok: false, got: "no error" };
11+ } catch (error) {
12+ return { name, ok: code ? error.code === code : true, got: `${error.code ?? ""} ${error.message}` };
13+ }
14+};
15+
16+export default {
17+ async fetch() {
18+ const checks = [
19+ // Node's test-url-domain-ascii-unicode.js cases
20+ expectEqual("ascii español.com", domainToASCII("español.com"), "xn--espaol-zwa.com"),
21+ expectEqual("ascii 中文.com", domainToASCII("中文.com"), "xn--fiq228c.com"),
22+ expectEqual("ascii ïnhqgjv.com", domainToASCII("ïnhqgjv.com"), "xn--nhqgjv-cva.com"),
23+ expectEqual("ascii upper", domainToASCII("EXAMPLE.Com"), "example.com"),
24+ expectEqual("ascii invalid", domainToASCII("xn--iñvalid.com"), ""),
25+ expectEqual("ascii empty", domainToASCII(""), ""),
26+ expectEqual("ascii ipv4", domainToASCII("127.0.0.1"), "127.0.0.1"),
27+ expectEqual("ascii handle domain", domainToASCII("1j.nz"), "1j.nz"),
28+ expectEqual("unicode xn--espaol-zwa.com", domainToUnicode("xn--espaol-zwa.com"), "español.com"),
29+ expectEqual("unicode xn--fiq228c.com", domainToUnicode("xn--fiq228c.com"), "中文.com"),
30+ expectEqual("unicode ascii", domainToUnicode("example.com"), "example.com"),
31+ expectEqual("unicode invalid", domainToUnicode("xn--iñvalid.com"), ""),
32+ expectThrows("ascii missing arg", () => domainToASCII(), "ERR_MISSING_ARGS"),
33+
34+ expectEqual("fileURLToPath", fileURLToPath("file:///a/b%20c.txt"), "/a/b c.txt"),
35+ expectThrows("fileURLToPath http", () => fileURLToPath("http://x/"), "ERR_INVALID_URL_SCHEME"),
36+ expectThrows("fileURLToPath host", () => fileURLToPath("file://host/a"), "ERR_INVALID_FILE_URL_HOST"),
37+ expectThrows("fileURLToPath %2F", () => fileURLToPath("file:///a%2Fb"), "ERR_INVALID_FILE_URL_PATH"),
38+ expectEqual("pathToFileURL", pathToFileURL("/a/b c?#%").href, "file:///a/b%20c%3F%23%25"),
39+ expectEqual("pathToFileURL relative", pathToFileURL("x/../y/").href, "file:///y/"),
40+
41+ expectEqual("urlToHttpOptions", (() => {
42+ const o = urlToHttpOptions(new URL("https://u:p%40@[::1]:8443/p?q=1#h"));
43+ return [o.protocol, o.hostname, o.port, o.path, o.auth, o.hash];
44+ })(), ["https:", "::1", 8443, "/p?q=1", "u:p@", "#h"]),
45+
46+ expectEqual("format URL", url.format(new URL("https://u:[email protected]:8080/a?b#c")),
47+ "https://u:[email protected]:8080/a?b#c"),
48+ expectEqual("format URL options", url.format(new URL("https://u:[email protected]/a?b#c"),
49+ { auth: false, fragment: false, search: false, unicode: true }), "https://español.com/a"),
50+ expectEqual("format object", url.format({ protocol: "https", hostname: "example.com", pathname: "/a#b", query: { x: "1 2", y: ["a", "b"] } }),
51+ "https://example.com/a%23b?x=1%202&y=a&y=b"),
52+ expectEqual("format mailto", url.format({ protocol: "mailto", pathname: "[email protected]" }), "mailto:[email protected]"),
53+ expectThrows("parse not implemented", () => url.parse("http://x/")),
54+
55+ expectEqual("URL is the global", url.URL === URL && url.URLSearchParams === URLSearchParams, true),
56+ ];
57+ const failed = checks.filter((c) => !c.ok);
58+ return Response.json({ ok: failed.length === 0, failed, checks }, { status: failed.length ? 500 : 200 });
59+ },
60+};
addedhomeflare/smoke/node-url/wrangler.jsonc+6−0View file
@@ -1,0 +1,6 @@
1+{
2+ "name": "node-url",
3+ "main": "index.js",
4+ "compatibility_date": "2026-01-01",
5+ "compatibility_flags": ["nodejs_compat"]
6+}