webveil 0.0.0 → 0.1.1

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 (78) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +326 -0
  3. package/dist/cli.d.ts +58 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +91 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/core/backends/custom.d.ts +15 -0
  8. package/dist/core/backends/custom.d.ts.map +1 -0
  9. package/dist/core/backends/custom.js +106 -0
  10. package/dist/core/backends/custom.js.map +1 -0
  11. package/dist/core/backends/registry.d.ts +13 -0
  12. package/dist/core/backends/registry.d.ts.map +1 -0
  13. package/dist/core/backends/registry.js +31 -0
  14. package/dist/core/backends/registry.js.map +1 -0
  15. package/dist/core/backends/searxng.d.ts +8 -0
  16. package/dist/core/backends/searxng.d.ts.map +1 -0
  17. package/dist/core/backends/searxng.js +43 -0
  18. package/dist/core/backends/searxng.js.map +1 -0
  19. package/dist/core/backends/tavily-compat.d.ts +10 -0
  20. package/dist/core/backends/tavily-compat.d.ts.map +1 -0
  21. package/dist/core/backends/tavily-compat.js +85 -0
  22. package/dist/core/backends/tavily-compat.js.map +1 -0
  23. package/dist/core/backends/types.d.ts +48 -0
  24. package/dist/core/backends/types.d.ts.map +1 -0
  25. package/dist/core/backends/types.js +5 -0
  26. package/dist/core/backends/types.js.map +1 -0
  27. package/dist/core/baseurl.d.ts +42 -0
  28. package/dist/core/baseurl.d.ts.map +1 -0
  29. package/dist/core/baseurl.js +79 -0
  30. package/dist/core/baseurl.js.map +1 -0
  31. package/dist/core/config.d.ts +39 -0
  32. package/dist/core/config.d.ts.map +1 -0
  33. package/dist/core/config.js +72 -0
  34. package/dist/core/config.js.map +1 -0
  35. package/dist/core/egress.d.ts +46 -0
  36. package/dist/core/egress.d.ts.map +1 -0
  37. package/dist/core/egress.js +113 -0
  38. package/dist/core/egress.js.map +1 -0
  39. package/dist/core/extract.d.ts +45 -0
  40. package/dist/core/extract.d.ts.map +1 -0
  41. package/dist/core/extract.js +36 -0
  42. package/dist/core/extract.js.map +1 -0
  43. package/dist/core/fetch.d.ts +42 -0
  44. package/dist/core/fetch.d.ts.map +1 -0
  45. package/dist/core/fetch.js +76 -0
  46. package/dist/core/fetch.js.map +1 -0
  47. package/dist/core/http.d.ts +8 -0
  48. package/dist/core/http.d.ts.map +1 -0
  49. package/dist/core/http.js +49 -0
  50. package/dist/core/http.js.map +1 -0
  51. package/dist/core/search.d.ts +34 -0
  52. package/dist/core/search.d.ts.map +1 -0
  53. package/dist/core/search.js +92 -0
  54. package/dist/core/search.js.map +1 -0
  55. package/dist/core/security.d.ts +35 -0
  56. package/dist/core/security.d.ts.map +1 -0
  57. package/dist/core/security.js +141 -0
  58. package/dist/core/security.js.map +1 -0
  59. package/dist/index.d.ts +22 -0
  60. package/dist/index.d.ts.map +1 -0
  61. package/dist/index.js +40 -0
  62. package/dist/index.js.map +1 -0
  63. package/package.json +62 -2
  64. package/src/cli.ts +106 -0
  65. package/src/core/backends/custom.ts +159 -0
  66. package/src/core/backends/registry.ts +41 -0
  67. package/src/core/backends/searxng.ts +70 -0
  68. package/src/core/backends/tavily-compat.ts +156 -0
  69. package/src/core/backends/types.ts +61 -0
  70. package/src/core/baseurl.ts +104 -0
  71. package/src/core/config.ts +106 -0
  72. package/src/core/egress.ts +134 -0
  73. package/src/core/extract.ts +82 -0
  74. package/src/core/fetch.ts +132 -0
  75. package/src/core/http.ts +62 -0
  76. package/src/core/search.ts +140 -0
  77. package/src/core/security.ts +141 -0
  78. package/src/index.ts +82 -0
@@ -0,0 +1,156 @@
1
+ // tavily-compat backend — a generic Tavily-shaped client (POST `/search` and an
2
+ // optional POST `/extract`) selected purely by `baseUrl`, so it covers
3
+ // orio-search / searcharvester / agent-search and any other Tavily-API-shaped
4
+ // instance. Both endpoints go THROUGH the handed `http` helper (never a direct
5
+ // fetch, so egress is not bypassable). `/search` normalizes to SearchResult[];
6
+ // `/extract` is exposed as the optional `Backend.fetch` a later task uses to
7
+ // override the distilly Extractor.
8
+ //
9
+ // Auth: a Bearer header is sent only when an apiKey is configured. The covered
10
+ // self-hosted instances are typically keyless, so a missing key is normal, not
11
+ // an error.
12
+
13
+ import type {Config} from '../config.js';
14
+ import type {
15
+ Backend,
16
+ FetchOptions,
17
+ FetchResult,
18
+ Http,
19
+ HttpRequestOptions,
20
+ SearchOptions,
21
+ SearchResult,
22
+ } from './types.js';
23
+
24
+ /** One entry in a Tavily `/search` `results` array (subset we use). */
25
+ interface TavilySearchHit {
26
+ title?: unknown;
27
+ url?: unknown;
28
+ content?: unknown;
29
+ }
30
+
31
+ /** The Tavily `/search` response (subset we use). */
32
+ interface TavilySearchResponse {
33
+ results?: TavilySearchHit[];
34
+ }
35
+
36
+ /** One entry in a Tavily `/extract` `results` array (subset we use). */
37
+ interface TavilyExtractHit {
38
+ url?: unknown;
39
+ raw_content?: unknown;
40
+ }
41
+
42
+ /** One entry in a Tavily `/extract` `failed_results` array (subset we use). */
43
+ interface TavilyExtractFailure {
44
+ url?: unknown;
45
+ error?: unknown;
46
+ }
47
+
48
+ /** The Tavily `/extract` response (subset we use). */
49
+ interface TavilyExtractResponse {
50
+ results?: TavilyExtractHit[];
51
+ failed_results?: TavilyExtractFailure[];
52
+ }
53
+
54
+ function str(value: unknown): string | undefined {
55
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
56
+ }
57
+
58
+ /** Normalize one Tavily search hit; drop entries without a usable url + title. */
59
+ function toResult(hit: TavilySearchHit): SearchResult | undefined {
60
+ const url = str(hit.url);
61
+ const title = str(hit.title);
62
+ if (!url || !title) return undefined;
63
+ const snippet = str(hit.content);
64
+ return snippet ? {title, url, snippet} : {title, url};
65
+ }
66
+
67
+ /** Resolve an endpoint path against the instance baseUrl. */
68
+ function endpoint(baseUrl: string, path: string): string {
69
+ return new URL(
70
+ path,
71
+ baseUrl.endsWith('/') ? baseUrl : baseUrl + '/',
72
+ ).toString();
73
+ }
74
+
75
+ /**
76
+ * Build a Tavily-compat backend bound to the configured instance. The returned
77
+ * backend only ever touches the network via the injected `http` helper. A Bearer
78
+ * header is added only when an apiKey is set (the covered instances are usually
79
+ * keyless).
80
+ */
81
+ export function createTavilyCompatBackend(config: Config): Backend {
82
+ const baseUrl = config.baseUrl;
83
+ const apiKey = config.apiKey;
84
+
85
+ function headers(): Record<string, string> {
86
+ const h: Record<string, string> = {
87
+ 'content-type': 'application/json',
88
+ accept: 'application/json',
89
+ };
90
+ if (apiKey) h.authorization = `Bearer ${apiKey}`;
91
+ return h;
92
+ }
93
+
94
+ function post(
95
+ path: string,
96
+ payload: unknown,
97
+ signal?: AbortSignal,
98
+ ): HttpRequestOptions {
99
+ return {
100
+ method: 'POST',
101
+ headers: headers(),
102
+ body: JSON.stringify(payload),
103
+ signal,
104
+ };
105
+ }
106
+
107
+ return {
108
+ async search(
109
+ query: string,
110
+ http: Http,
111
+ options: SearchOptions = {},
112
+ ): Promise<SearchResult[]> {
113
+ const payload: Record<string, unknown> = {query};
114
+ if (options.maxResults !== undefined)
115
+ payload.max_results = options.maxResults;
116
+ const body = await http.fetchJson<TavilySearchResponse>(
117
+ endpoint(baseUrl, 'search'),
118
+ post('search', payload, options.signal),
119
+ );
120
+ const results = Array.isArray(body.results) ? body.results : [];
121
+ const normalized = results
122
+ .map(toResult)
123
+ .filter((r): r is SearchResult => r !== undefined);
124
+ return options.maxResults !== undefined
125
+ ? normalized.slice(0, options.maxResults)
126
+ : normalized;
127
+ },
128
+
129
+ async fetch(
130
+ url: string,
131
+ http: Http,
132
+ options: FetchOptions = {},
133
+ ): Promise<FetchResult> {
134
+ // Tavily `/extract` has no `s/m/l/f` size knob (it has `format` /
135
+ // `extract_depth` instead); always request markdown. The default
136
+ // distilly Extractor owns webveil's size presets.
137
+ const body = await http.fetchJson<TavilyExtractResponse>(
138
+ endpoint(baseUrl, 'extract'),
139
+ post('extract', {urls: url, format: 'markdown'}, options.signal),
140
+ );
141
+ const failure = (body.failed_results ?? []).find(
142
+ (f) => str(f.url) === url,
143
+ );
144
+ if (failure)
145
+ throw new Error(
146
+ `tavily-compat: /extract failed for ${url}: ${str(failure.error) ?? 'unknown error'}`,
147
+ );
148
+ const hit = (body.results ?? [])[0];
149
+ const markdown = hit ? str(hit.raw_content) : undefined;
150
+ if (markdown === undefined)
151
+ throw new Error(`tavily-compat: no extract result for ${url}`);
152
+ // Tavily `/extract` returns no `truncated` flag and no page title.
153
+ return {url, markdown, truncated: false};
154
+ },
155
+ };
156
+ }
@@ -0,0 +1,61 @@
1
+ // backend seam — the contract every result source (searxng | tavily-compat |
2
+ // custom) implements. A Backend is HANDED a proxied `http` helper (bound to the
3
+ // configured egress dispatcher) so it physically cannot bypass the egress.
4
+
5
+ /** A single search hit. */
6
+ export interface SearchResult {
7
+ title: string;
8
+ url: string;
9
+ snippet?: string;
10
+ }
11
+
12
+ /** A fetched, extracted page as budget-bounded markdown. */
13
+ export interface FetchResult {
14
+ url: string;
15
+ title?: string;
16
+ markdown: string;
17
+ truncated: boolean;
18
+ }
19
+
20
+ export interface SearchOptions {
21
+ maxResults?: number;
22
+ signal?: AbortSignal;
23
+ }
24
+
25
+ export interface FetchOptions {
26
+ size?: 's' | 'm' | 'l' | 'f';
27
+ signal?: AbortSignal;
28
+ }
29
+
30
+ /** Options the http helper accepts for a single request. */
31
+ export interface HttpRequestOptions {
32
+ method?: string;
33
+ headers?: Record<string, string>;
34
+ body?: string;
35
+ /** Per-request timeout in ms (the helper aborts past this). */
36
+ timeoutMs?: number;
37
+ signal?: AbortSignal;
38
+ }
39
+
40
+ /**
41
+ * The proxied http helper handed to backends. Both methods route through the
42
+ * egress dispatcher; a backend never gets un-proxied transport of its own.
43
+ */
44
+ export interface Http {
45
+ fetchJson<T = unknown>(url: string, options?: HttpRequestOptions): Promise<T>;
46
+ fetchText(url: string, options?: HttpRequestOptions): Promise<string>;
47
+ }
48
+
49
+ /**
50
+ * A result/content source. `search` is required; `fetch` is optional (a backend
51
+ * may override the default distilly Extractor with its own `/extract`). Both are
52
+ * given the proxied `http` helper so they cannot escape the configured egress.
53
+ */
54
+ export interface Backend {
55
+ search(
56
+ query: string,
57
+ http: Http,
58
+ options?: SearchOptions,
59
+ ): Promise<SearchResult[]>;
60
+ fetch?(url: string, http: Http, options?: FetchOptions): Promise<FetchResult>;
61
+ }
@@ -0,0 +1,104 @@
1
+ // baseUrl transport parsing — the small, transport-AWARE helper that classifies
2
+ // a resolved `baseUrl` into either a normal TCP HTTP base or a Unix-domain-socket
3
+ // form, and (for the socket form) rewrites it into a synthetic `http://localhost`
4
+ // base that the transport-UNAWARE backends can build their request URL on top of.
5
+ //
6
+ // WHY THIS LIVES HERE (and not in egress.ts): the egress dispatcher
7
+ // (`buildDispatcher`) is built ONCE from config and SHARED by both the backend
8
+ // hop (search.ts) AND the arbitrary-public-URL fetch (fetch.ts). Binding a socket
9
+ // `Agent` into that shared dispatcher would route every `web_fetch` into the
10
+ // SearXNG socket. So the socket transport is scoped to the BACKEND `baseUrl` hop
11
+ // only: search.ts asks this helper to translate the baseUrl, gets back a real
12
+ // `http://localhost…` base (which the searxng backend's `new URL('search', base)`
13
+ // still works on, unchanged) plus the per-hop socket `Agent`, and leaves the
14
+ // fetch/SSRF egress path untouched.
15
+ //
16
+ // GRAMMAR (recorded decision, see the task's done record):
17
+ // unix:<socketPath>[:<httpPath>]
18
+ // - `<socketPath>`: the absolute path to the uWSGI Unix domain socket
19
+ // (e.g. /usr/local/searxng/run/socket). Must not contain a `:` (the parse
20
+ // splits on the FIRST `:` after the `unix:` scheme; conventional socket
21
+ // paths never contain a colon).
22
+ // - `<httpPath>`: OPTIONAL base path the SearXNG app is mounted under,
23
+ // defaulting to `/`. It is the SAME thing the TCP `baseUrl` encodes as its
24
+ // path: the backend appends `search` to it (`new URL('search', base + '/')`),
25
+ // so the install default is just `unix:/usr/local/searxng/run/socket` (the
26
+ // backend then requests `/search`). A non-root mount is `…/socket:/searxng`.
27
+ // A raw `unix:…` string is NOT a valid base for `new URL('search', …)`, so this
28
+ // translation MUST run BEFORE the backend builds its URL.
29
+
30
+ import {Agent, type Dispatcher} from 'undici';
31
+
32
+ /** The `unix:` scheme prefix this helper recognizes on a `baseUrl`. */
33
+ const UNIX_PREFIX = 'unix:';
34
+
35
+ /** A parsed Unix-socket baseUrl: the socket file path + the app's base path. */
36
+ export interface UnixBaseUrl {
37
+ socketPath: string;
38
+ /** The app's base path (mount point); the backend appends `search` to it. */
39
+ httpPath: string;
40
+ }
41
+
42
+ /** Is this resolved `baseUrl` a Unix-domain-socket form (`unix:…`)? */
43
+ export function isUnixBaseUrl(baseUrl: string): boolean {
44
+ return baseUrl.startsWith(UNIX_PREFIX);
45
+ }
46
+
47
+ /**
48
+ * Parse a `unix:<socketPath>[:<httpPath>]` baseUrl into `{socketPath, httpPath}`.
49
+ * Splits on the FIRST `:` after the `unix:` scheme (socket paths conventionally
50
+ * carry no colon); an absent/empty `<httpPath>` defaults to `/`.
51
+ *
52
+ * Throws if the socket path is empty (there is nothing to connect to).
53
+ */
54
+ export function parseUnixBaseUrl(baseUrl: string): UnixBaseUrl {
55
+ const rest = baseUrl.slice(UNIX_PREFIX.length);
56
+ const sep = rest.indexOf(':');
57
+ const socketPath = sep === -1 ? rest : rest.slice(0, sep);
58
+ const rawHttpPath = sep === -1 ? '' : rest.slice(sep + 1);
59
+ if (!socketPath)
60
+ throw new Error(
61
+ `webveil: malformed unix baseUrl ${JSON.stringify(baseUrl)} — ` +
62
+ `expected unix:<socketPath>[:<httpPath>] with a non-empty socket path`,
63
+ );
64
+ const httpPath = rawHttpPath
65
+ ? rawHttpPath.startsWith('/')
66
+ ? rawHttpPath
67
+ : '/' + rawHttpPath
68
+ : '/';
69
+ return {socketPath, httpPath};
70
+ }
71
+
72
+ /**
73
+ * The result of resolving a `baseUrl` for the BACKEND hop: the (possibly
74
+ * rewritten) HTTP base the backend builds its request URL on, plus an OPTIONAL
75
+ * undici `Dispatcher` to carry that hop. For a normal TCP baseUrl the dispatcher
76
+ * is `undefined` (the caller uses the config-wide egress dispatcher); for a
77
+ * `unix:` baseUrl it is a socket-bound `Agent` and the base is a synthetic
78
+ * `http://localhost<httpPath>`.
79
+ */
80
+ export interface BackendTransport {
81
+ baseUrl: string;
82
+ dispatcher?: Dispatcher;
83
+ }
84
+
85
+ /**
86
+ * Resolve a `baseUrl` into a backend-hop transport. For a `unix:` baseUrl this
87
+ * builds a socket-bound `Agent({connect:{socketPath}})` and a synthetic
88
+ * `http://localhost<httpPath>` base (the URL host is irrelevant to routing — the
89
+ * socket decides — and only becomes the `Host` header). For any other baseUrl it
90
+ * returns the baseUrl unchanged with NO dispatcher (the caller keeps using the
91
+ * shared config-wide egress dispatcher).
92
+ *
93
+ * NOTE: this is the BACKEND-hop transport only. It is never bound into the
94
+ * shared egress dispatcher, so `web_fetch`/SSRF egress is unaffected.
95
+ */
96
+ export function resolveBackendTransport(baseUrl: string): BackendTransport {
97
+ if (!isUnixBaseUrl(baseUrl)) return {baseUrl};
98
+ const {socketPath, httpPath} = parseUnixBaseUrl(baseUrl);
99
+ const dispatcher = new Agent({connect: {socketPath}});
100
+ return {
101
+ baseUrl: `http://localhost${httpPath === '/' ? '' : httpPath}`,
102
+ dispatcher,
103
+ };
104
+ }
@@ -0,0 +1,106 @@
1
+ // config seam — per-folder resolution. Precedence (highest wins):
2
+ // env > nearest .pi/webveil.json (walking up from cwd) > global
3
+ // ~/.pi/agent/webveil.json > defaults.
4
+ // "Per folder = per account/egress." Each layer is a partial; later (lower)
5
+ // layers fill gaps the higher layers leave.
6
+
7
+ import {readFileSync} from 'node:fs';
8
+ import {homedir} from 'node:os';
9
+ import {dirname, join, parse} from 'node:path';
10
+
11
+ /** How outbound HTTP leaves the machine. See egress.ts. */
12
+ export type Egress =
13
+ | {mode: 'direct'}
14
+ | {mode: 'http'; url: string}
15
+ | {mode: 'socks5'; url: string};
16
+
17
+ /** Page-size budget preset for fetch (passed through to distilly). */
18
+ export type FetchSize = 's' | 'm' | 'l' | 'f';
19
+
20
+ /** The fully-resolved config every webveil module consumes. */
21
+ export interface Config {
22
+ backend: string;
23
+ baseUrl: string;
24
+ apiKey?: string;
25
+ egress: Egress;
26
+ fetchSize: FetchSize;
27
+ }
28
+
29
+ /** A config file / env layer: any subset of the resolved shape. */
30
+ export type PartialConfig = Partial<Config>;
31
+
32
+ export interface ResolveOptions {
33
+ /** Directory the per-folder walk starts from. Defaults to process.cwd(). */
34
+ cwd?: string;
35
+ /** Environment to read overrides from. Defaults to process.env. */
36
+ env?: Record<string, string | undefined>;
37
+ /**
38
+ * Path to the global config file. Defaults to ~/.pi/agent/webveil.json.
39
+ * Tests point this at a temp dir to isolate the real home directory.
40
+ */
41
+ globalPath?: string;
42
+ }
43
+
44
+ const DEFAULTS: Config = {
45
+ backend: 'searxng',
46
+ baseUrl: 'http://127.0.0.1:8080',
47
+ egress: {mode: 'direct'},
48
+ fetchSize: 'm',
49
+ };
50
+
51
+ const PROJECT_FILE = join('.pi', 'webveil.json');
52
+
53
+ function readJson(path: string): PartialConfig | undefined {
54
+ let text: string;
55
+ try {
56
+ text = readFileSync(path, 'utf8');
57
+ } catch {
58
+ return undefined; // absent file is fine; missing layers are expected
59
+ }
60
+ return JSON.parse(text) as PartialConfig;
61
+ }
62
+
63
+ /** The nearest `.pi/webveil.json` walking up from `cwd` (first found wins). */
64
+ function readProjectChain(cwd: string): PartialConfig | undefined {
65
+ let dir = cwd;
66
+ const {root} = parse(dir);
67
+ for (;;) {
68
+ const found = readJson(join(dir, PROJECT_FILE));
69
+ if (found) return found;
70
+ if (dir === root) return undefined;
71
+ dir = dirname(dir);
72
+ }
73
+ }
74
+
75
+ function readEnv(env: Record<string, string | undefined>): PartialConfig {
76
+ const layer: PartialConfig = {};
77
+ if (env.WEBVEIL_BACKEND) layer.backend = env.WEBVEIL_BACKEND;
78
+ if (env.WEBVEIL_BASE_URL) layer.baseUrl = env.WEBVEIL_BASE_URL;
79
+ if (env.WEBVEIL_API_KEY) layer.apiKey = env.WEBVEIL_API_KEY;
80
+ if (env.WEBVEIL_FETCH_SIZE)
81
+ layer.fetchSize = env.WEBVEIL_FETCH_SIZE as FetchSize;
82
+ const mode = env.WEBVEIL_EGRESS;
83
+ if (mode === 'direct') layer.egress = {mode: 'direct'};
84
+ else if (mode === 'http' || mode === 'socks5')
85
+ layer.egress = {mode, url: env.WEBVEIL_EGRESS_URL ?? ''};
86
+ return layer;
87
+ }
88
+
89
+ /**
90
+ * Resolve the effective config. Higher-precedence layers override lower ones,
91
+ * key by key: env > project chain > global file > defaults.
92
+ */
93
+ export function resolveConfig(options: ResolveOptions = {}): Config {
94
+ const cwd = options.cwd ?? process.cwd();
95
+ const env = options.env ?? process.env;
96
+ const globalPath =
97
+ options.globalPath ?? join(homedir(), '.pi', 'agent', 'webveil.json');
98
+
99
+ const layers: PartialConfig[] = [
100
+ DEFAULTS,
101
+ readJson(globalPath) ?? {},
102
+ readProjectChain(cwd) ?? {},
103
+ readEnv(env),
104
+ ];
105
+ return Object.assign({}, ...layers) as Config;
106
+ }
@@ -0,0 +1,134 @@
1
+ // egress seam — how outbound HTTP leaves the machine. Yields TWO artifacts off
2
+ // the SAME undici dispatcher: the proxied `http` helper (see http.ts, handed to
3
+ // backends) and an egress-bound WHATWG `fetch` (injected into distilly/fetch).
4
+ //
5
+ // CRITICAL anonymity invariant (docs/adr/0001): egress is fail-loud. A
6
+ // configured proxy that cannot be built MUST throw — it must NEVER silently
7
+ // fall back to un-proxied (direct) transport.
8
+
9
+ import {Agent, type Dispatcher, ProxyAgent, fetch as undiciFetch} from 'undici';
10
+ import {socksDispatcher} from 'fetch-socks';
11
+ import type {Config, Egress} from './config.js';
12
+ import {isUnixBaseUrl} from './baseurl.js';
13
+
14
+ /** Thrown when a configured egress proxy cannot be built. Never swallowed. */
15
+ export class EgressError extends Error {
16
+ constructor(message: string, options?: {cause?: unknown}) {
17
+ super(message, options);
18
+ this.name = 'EgressError';
19
+ }
20
+ }
21
+
22
+ /**
23
+ * Fail-loud guard for the false-confidence combo: a `unix:` (local-socket)
24
+ * backend `baseUrl` configured with a NON-direct egress (`http`/`socks5`). A
25
+ * Unix socket is inherently local, so proxying that hop is the same fake-
26
+ * anonymity footgun as proxying a loopback TCP baseUrl: webveil would route a
27
+ * pointless local call through the proxy while the backend (SearXNG) crawls the
28
+ * public web from the real IP, OUTSIDE webveil's egress. Refuse it and point at
29
+ * the real fix.
30
+ *
31
+ * OVERLAP SEAM (recorded): this is the loopback false-confidence family. The
32
+ * sibling task `fail-loud-on-proxied-loopback-backend` adds the broader guard
33
+ * for loopback TCP baseUrls (127.0.0.0/8, ::1, localhost). When it lands, fold
34
+ * THIS `unix:`-is-loopback-equivalent case into that single guard instead of
35
+ * keeping a parallel check here.
36
+ */
37
+ export function assertEgressAllowsBaseUrl(cfg: Config): void {
38
+ if (cfg.egress.mode === 'direct') return;
39
+ if (isUnixBaseUrl(cfg.baseUrl))
40
+ throw new EgressError(
41
+ `egress ${cfg.egress.mode}: a unix: (local socket) baseUrl cannot be ` +
42
+ `proxied — it is inherently local, so proxying it gives fake ` +
43
+ `anonymity (SearXNG still crawls the web from your real IP). Set ` +
44
+ `egress=direct and proxy the backend itself (SearXNG's ` +
45
+ `outgoing.proxies), or use a remote backend.`,
46
+ );
47
+ }
48
+
49
+ function socksFromUrl(raw: string): Dispatcher {
50
+ const url = new URL(raw); // throws on a malformed proxy URL → fail loud
51
+ const protocol = url.protocol.replace(':', '');
52
+ if (protocol !== 'socks5' && protocol !== 'socks' && protocol !== 'socks5h')
53
+ throw new EgressError(
54
+ `egress socks5: expected a socks5:// proxy url, got ${raw}`,
55
+ );
56
+ const port = Number(url.port);
57
+ if (!url.hostname || !Number.isInteger(port) || port <= 0)
58
+ throw new EgressError(`egress socks5: invalid host/port in ${raw}`);
59
+ return socksDispatcher({
60
+ type: 5,
61
+ host: url.hostname,
62
+ port,
63
+ userId: url.username || undefined,
64
+ password: url.password || undefined,
65
+ });
66
+ }
67
+
68
+ /**
69
+ * Build the undici Dispatcher for the config's egress mode:
70
+ * - direct → undefined (undici uses its default, un-proxied transport)
71
+ * - http → ProxyAgent
72
+ * - socks5 → socks dispatcher (undici Agent over a socks connector)
73
+ *
74
+ * Throws (fail loud) if a configured http/socks5 proxy cannot be built. It
75
+ * NEVER returns `undefined` (direct) as a fallback for a broken proxy.
76
+ */
77
+ export function buildDispatcher(cfg: Config): Dispatcher | undefined {
78
+ const egress: Egress = cfg.egress;
79
+ switch (egress.mode) {
80
+ case 'direct':
81
+ return undefined;
82
+ case 'http':
83
+ try {
84
+ if (!egress.url) throw new Error('missing proxy url');
85
+ return new ProxyAgent(egress.url);
86
+ } catch (cause) {
87
+ throw new EgressError(
88
+ `egress http: could not build proxy for ${egress.url}`,
89
+ {cause},
90
+ );
91
+ }
92
+ case 'socks5':
93
+ try {
94
+ if (!egress.url) throw new Error('missing proxy url');
95
+ return socksFromUrl(egress.url);
96
+ } catch (cause) {
97
+ if (cause instanceof EgressError) throw cause;
98
+ throw new EgressError(
99
+ `egress socks5: could not build proxy for ${egress.url}`,
100
+ {cause},
101
+ );
102
+ }
103
+ default: {
104
+ const exhaustive: never = egress;
105
+ throw new EgressError(
106
+ `egress: unknown mode ${JSON.stringify(exhaustive)}`,
107
+ );
108
+ }
109
+ }
110
+ }
111
+
112
+ /** A WHATWG-compatible fetch bound to a specific egress dispatcher. */
113
+ export type EgressFetch = typeof globalThis.fetch;
114
+
115
+ /**
116
+ * Build an egress-bound WHATWG `fetch`: undici's `fetch` closed over the
117
+ * dispatcher from buildDispatcher(cfg). This is the `fetch` injected into
118
+ * distilly/fetch so distilly never has egress of its own. Same fail-loud
119
+ * guarantee: a broken proxy throws HERE (before any I/O), never goes un-proxied.
120
+ */
121
+ export function createEgressFetch(cfg: Config): EgressFetch {
122
+ const dispatcher = buildDispatcher(cfg);
123
+ return ((input: RequestInfo | URL, init?: RequestInit) =>
124
+ undiciFetch(
125
+ input as never,
126
+ {
127
+ ...((init ?? {}) as Record<string, unknown>),
128
+ dispatcher,
129
+ } as never,
130
+ )) as EgressFetch;
131
+ }
132
+
133
+ export type {Dispatcher};
134
+ export {Agent, ProxyAgent};
@@ -0,0 +1,82 @@
1
+ // Extractor seam — turn a URL into clean, size-bounded markdown by calling
2
+ // distilly's NETWORKED `urlToMarkdown` (the `distilly/fetch` entrypoint),
3
+ // INJECTING webveil's egress-bound `fetch` as the only transport. distilly's
4
+ // network Rules (github/mdn/react.dev/vuejs.org) rewrite a matching URL to its
5
+ // raw `.md`/API source and fetch THAT over our egress — shorter, cleaner output;
6
+ // non-matching URLs run through distilly's pure core. See docs/adr/0001.
7
+ //
8
+ // THE HARD INVARIANT (load-bearing for anonymity): webveil ALWAYS injects its
9
+ // egress-bound `fetch` here and NEVER lets distilly use a global/default fetch.
10
+ // distilly throws if none is injected — the desired fail-loud. And the egress
11
+ // fetch itself throws (before any I/O) when a configured proxy is unbuildable
12
+ // (egress.ts), so a broken proxy can never become an un-proxied request.
13
+ //
14
+ // This is the DEFAULT extractor; a backend's own `/extract` (tavily-compat) may
15
+ // override it (wired in the core-fetch task).
16
+
17
+ import {urlToMarkdown as distillyUrlToMarkdown} from 'distilly/fetch';
18
+ import type {Config, FetchSize} from './config.js';
19
+ import {createEgressFetch, type EgressFetch} from './egress.js';
20
+ import type {FetchResult} from './backends/types.js';
21
+
22
+ /** The shape distilly's `urlToMarkdown` returns (the bits we surface). */
23
+ interface UrlToMarkdownResult {
24
+ markdown: string;
25
+ truncated: boolean;
26
+ }
27
+
28
+ /** distilly's networked entrypoint, narrowed to what the seam injects/uses. */
29
+ type UrlToMarkdown = (
30
+ url: string | URL,
31
+ options: {fetch: EgressFetch; size?: FetchSize},
32
+ ) => Promise<UrlToMarkdownResult>;
33
+
34
+ /** Per-call extractor options. */
35
+ export interface ExtractOptions {
36
+ /**
37
+ * Page-size budget for THIS call. Overrides the config's `fetchSize` when
38
+ * given. webveil's `s`/`m`/`l`/`f` preset maps STRAIGHT to distilly's `size`
39
+ * (the two enums are identical), so this is passed through verbatim.
40
+ */
41
+ size?: FetchSize;
42
+ }
43
+
44
+ /**
45
+ * Seams the extractor's collaborators so it is testable WITHOUT real network or
46
+ * undici: tests inject a spy `urlToMarkdown` and/or a spy egress fetch to assert
47
+ * distilly is called with the egress fetch (never a global). Defaults wire the
48
+ * real `distilly/fetch` + `createEgressFetch`.
49
+ */
50
+ export interface ExtractDeps {
51
+ /** distilly's networked `urlToMarkdown` (default: the real `distilly/fetch`). */
52
+ urlToMarkdown?: UrlToMarkdown;
53
+ /** Builds the egress-bound fetch from config (default: createEgressFetch). */
54
+ createEgressFetch?: (config: Config) => EgressFetch;
55
+ }
56
+
57
+ /**
58
+ * Extract a URL to clean, budget-bounded markdown via distilly over webveil's
59
+ * egress. Builds the egress-bound `fetch` (fail-loud on an unbuildable proxy),
60
+ * injects it into distilly's `urlToMarkdown`, maps the `s`/`m`/`l`/`f` preset to
61
+ * distilly's `size`, and surfaces distilly's `truncated`.
62
+ *
63
+ * @returns `{ url, markdown, truncated }` (a `FetchResult` without a `title`).
64
+ */
65
+ export async function extract(
66
+ url: string,
67
+ config: Config,
68
+ options: ExtractOptions = {},
69
+ deps: ExtractDeps = {},
70
+ ): Promise<FetchResult> {
71
+ const urlToMarkdown = deps.urlToMarkdown ?? distillyUrlToMarkdown;
72
+ const buildFetch = deps.createEgressFetch ?? createEgressFetch;
73
+
74
+ // Build the egress-bound fetch FIRST: a configured-but-unbuildable proxy
75
+ // throws here, before any network access (never an un-proxied request).
76
+ const fetch = buildFetch(config);
77
+
78
+ const size = options.size ?? config.fetchSize;
79
+
80
+ const {markdown, truncated} = await urlToMarkdown(url, {fetch, size});
81
+ return {url, markdown, truncated};
82
+ }