@osd-project/osd-cli 0.0.0-stage → 0.8.3

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 (52) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +585 -2
  3. package/THIRD_PARTY_NOTICES.md +96 -0
  4. package/dist/auth-store.d.ts +38 -0
  5. package/dist/auth-store.js +239 -0
  6. package/dist/brand-catalog.d.ts +65 -0
  7. package/dist/brand-catalog.js +175 -0
  8. package/dist/connect-gate.d.ts +31 -0
  9. package/dist/connect-gate.js +82 -0
  10. package/dist/contracts.d.ts +61 -0
  11. package/dist/contracts.js +145 -0
  12. package/dist/exit-codes.d.ts +32 -0
  13. package/dist/exit-codes.js +40 -0
  14. package/dist/format.d.ts +71 -0
  15. package/dist/format.js +99 -0
  16. package/dist/generated/schemas.d.ts +2 -0
  17. package/dist/generated/schemas.js +1781 -0
  18. package/dist/guarded-fetch.d.ts +28 -0
  19. package/dist/guarded-fetch.js +252 -0
  20. package/dist/help.d.ts +27 -0
  21. package/dist/help.js +32 -0
  22. package/dist/http-fetch.d.ts +1 -0
  23. package/dist/http-fetch.js +17 -0
  24. package/dist/index.d.ts +2 -0
  25. package/dist/index.js +821 -0
  26. package/dist/logout.d.ts +16 -0
  27. package/dist/logout.js +82 -0
  28. package/dist/mcp-auth.d.ts +70 -0
  29. package/dist/mcp-auth.js +603 -0
  30. package/dist/mcp-card.d.ts +23 -0
  31. package/dist/mcp-card.js +18 -0
  32. package/dist/mcp-client.d.ts +77 -0
  33. package/dist/mcp-client.js +193 -0
  34. package/dist/net-guard.d.ts +66 -0
  35. package/dist/net-guard.js +152 -0
  36. package/dist/proxy-config.d.ts +51 -0
  37. package/dist/proxy-config.js +147 -0
  38. package/dist/request.d.ts +32 -0
  39. package/dist/request.js +62 -0
  40. package/dist/resolve-endpoint.d.ts +62 -0
  41. package/dist/resolve-endpoint.js +172 -0
  42. package/dist/search.d.ts +39 -0
  43. package/dist/search.js +69 -0
  44. package/dist/skill.d.ts +155 -0
  45. package/dist/skill.js +320 -0
  46. package/dist/updates.d.ts +101 -0
  47. package/dist/updates.js +541 -0
  48. package/dist/verify.d.ts +92 -0
  49. package/dist/verify.js +379 -0
  50. package/package.json +55 -3
  51. package/skill/osd/SKILL.md +400 -0
  52. package/skill/osd/references/connect-mcp.md +48 -0
@@ -0,0 +1,77 @@
1
+ import type { OAuthClientProvider } from "@modelcontextprotocol/client";
2
+ import type { AddressLookup } from "./net-guard.js";
3
+ export declare const CONNECT_TIMEOUT_MS = 120000;
4
+ export declare const REQUEST_TIMEOUT_MS = 120000;
5
+ /** Thrown when a session phase times out or is cancelled; classified as unreachable. */
6
+ export declare class McpSessionError extends Error {
7
+ }
8
+ export interface McpToolSummary {
9
+ name: string;
10
+ description?: string;
11
+ }
12
+ export type McpProbeOutcome = {
13
+ kind: "connected";
14
+ serverInfo?: {
15
+ name?: string;
16
+ version?: string;
17
+ };
18
+ tools: McpToolSummary[];
19
+ } | {
20
+ kind: "authRequired";
21
+ message: string;
22
+ } | {
23
+ kind: "unreachable";
24
+ message: string;
25
+ } | {
26
+ kind: "protocolError";
27
+ message: string;
28
+ };
29
+ export type McpCallOutcome = {
30
+ kind: "called";
31
+ result: unknown;
32
+ } | {
33
+ kind: "authRequired";
34
+ message: string;
35
+ } | {
36
+ kind: "unreachable";
37
+ message: string;
38
+ } | {
39
+ kind: "protocolError";
40
+ message: string;
41
+ };
42
+ export interface McpClientDeps {
43
+ /**
44
+ * Attached to the transport so cached tokens ride along (and refreshes
45
+ * are attempted). Without one, protected servers can only ever answer
46
+ * `authRequired`.
47
+ */
48
+ authProvider?: OAuthClientProvider;
49
+ /**
50
+ * DNS seam for tests. Production always resolves real addresses.
51
+ */
52
+ lookupAddresses?: AddressLookup;
53
+ /** TEST SEAM ONLY: lets loopback stub servers through the SSRF guard. Never set in production paths. */
54
+ allowLoopback?: boolean;
55
+ /** Overrides the environment's SSRF private-address policy; tests set it explicitly. */
56
+ allowPrivate?: boolean;
57
+ /** Cancels the session: outstanding requests are aborted and the call returns `unreachable`. */
58
+ signal?: AbortSignal;
59
+ /** TEST SEAM: overrides CONNECT_TIMEOUT_MS. */
60
+ connectTimeoutMs?: number;
61
+ /** TEST SEAM: overrides REQUEST_TIMEOUT_MS. */
62
+ requestTimeoutMs?: number;
63
+ }
64
+ /**
65
+ * Maps a failure to an outcome from typed signals only -- never from text a
66
+ * server controls. On streamable-http every HTTP failure arrives as an
67
+ * SdkHttpError whose message carries the response *body*, not the status,
68
+ * so the status must come from `error.status`.
69
+ */
70
+ export declare function classifyError(error: unknown): "authRequired" | "unreachable" | "protocolError";
71
+ /**
72
+ * Connects to the endpoint, completes the initialize handshake, and lists
73
+ * the server's tools. The answer to "is this discovery result real?"
74
+ */
75
+ export declare function probeMcpServer(endpoint: string, deps?: McpClientDeps): Promise<McpProbeOutcome>;
76
+ /** Connects to the endpoint and calls a single tool with the given arguments. */
77
+ export declare function callMcpTool(endpoint: string, tool: string, args: Record<string, unknown>, deps?: McpClientDeps): Promise<McpCallOutcome>;
@@ -0,0 +1,193 @@
1
+ /**
2
+ * One-shot MCP client baked into the CLI.
3
+ *
4
+ * Where `resolve-endpoint.ts` stops (a server card or endpoint URL that
5
+ * LOOKS right), this module continues: it opens a real MCP session over the
6
+ * streamable-http transport, runs the initialize handshake, and speaks the
7
+ * protocol (tools/list, tools/call). The lifecycle is deliberately
8
+ * connect -> do one thing -> close: the CLI is a one-shot process, so no
9
+ * session caching, no resumability, no notification handling.
10
+ *
11
+ * OAuth: attach an OAuthClientProvider (see mcp-auth.ts) and the transport
12
+ * authorizes with its cached tokens silently, refreshing when possible.
13
+ * Without one, a server that demands authorization is reported as
14
+ * `authRequired` so the caller can decide whether an interactive sign-in
15
+ * is wanted. All transport traffic rides guarded-fetch's SSRF guards.
16
+ */
17
+ import { Client, SdkHttpError, StreamableHTTPClientTransport, UnauthorizedError } from "@modelcontextprotocol/client";
18
+ import { GuardError, createGuardedFetch } from "./guarded-fetch.js";
19
+ import { CLI_VERSION } from "./updates.js";
20
+ const CLIENT_INFO = { name: "osd-cli", version: CLI_VERSION };
21
+ // Deliberately generous: in hosts that gate each outgoing request behind human
22
+ // approval (e.g. Muse "Allow once"), the handshake's 3+ requests each wait on a person.
23
+ // The CLI cannot tell approval wait from network delay, so this is one plain bound.
24
+ export const CONNECT_TIMEOUT_MS = 120_000;
25
+ // Separate budget, restarted after the handshake, for tools/list and tools/call.
26
+ export const REQUEST_TIMEOUT_MS = 120_000;
27
+ /** Thrown when a session phase times out or is cancelled; classified as unreachable. */
28
+ export class McpSessionError extends Error {
29
+ }
30
+ /** The JSON-RPC method of an outgoing request body, for stage reporting. Never logs the body. */
31
+ function methodOf(body) {
32
+ if (typeof body !== "string")
33
+ return undefined;
34
+ try {
35
+ const method = JSON.parse(body).method;
36
+ return typeof method === "string" ? method : undefined;
37
+ }
38
+ catch {
39
+ return undefined;
40
+ }
41
+ }
42
+ /** Runs `fn` against a fresh, closed-after-use MCP session. */
43
+ async function withClient(endpoint, deps, fn) {
44
+ // versionNegotiation 'auto': probe for the 2026-07-28 era via server/discover,
45
+ // fall back to the 2025-era initialize handshake against older servers.
46
+ const client = new Client(CLIENT_INFO, {
47
+ capabilities: {},
48
+ versionNegotiation: { mode: "auto" },
49
+ });
50
+ const guarded = createGuardedFetch(deps.lookupAddresses, {
51
+ allowLoopback: deps.allowLoopback === true,
52
+ allowPrivate: deps.allowPrivate,
53
+ });
54
+ // One controller per session: aborting it cancels every in-flight request.
55
+ const session = new AbortController();
56
+ let stage = "starting";
57
+ const transport = new StreamableHTTPClientTransport(new URL(endpoint), {
58
+ authProvider: deps.authProvider,
59
+ fetch: (input, init) => {
60
+ stage = methodOf(init?.body) ?? stage;
61
+ const signal = init?.signal ? AbortSignal.any([init.signal, session.signal]) : session.signal;
62
+ return guarded.fetchFn(input, { ...init, signal });
63
+ },
64
+ });
65
+ // Rejects when the caller cancels; attached once, raced by every phase.
66
+ const cancelled = new Promise((_, reject) => {
67
+ const onAbort = () => {
68
+ const err = new McpSessionError(`cancelled (stage: ${stage})`);
69
+ session.abort(err);
70
+ reject(err);
71
+ };
72
+ if (deps.signal?.aborted)
73
+ onAbort();
74
+ else
75
+ deps.signal?.addEventListener("abort", onAbort, { once: true });
76
+ });
77
+ cancelled.catch(() => undefined);
78
+ const run = async (phase, ms, op) => {
79
+ let timer;
80
+ const timeout = new Promise((_, reject) => {
81
+ timer = setTimeout(() => {
82
+ const err = new McpSessionError(`${phase} timed out after ${ms}ms (stage: ${stage})`);
83
+ session.abort(err);
84
+ reject(err);
85
+ }, ms);
86
+ });
87
+ timeout.catch(() => undefined);
88
+ try {
89
+ const work = op({ signal: session.signal, timeout: ms });
90
+ work.catch(() => undefined); // a late failure after losing the race must not go unhandled
91
+ return await Promise.race([work, timeout, cancelled]);
92
+ }
93
+ finally {
94
+ if (timer !== undefined)
95
+ clearTimeout(timer);
96
+ }
97
+ };
98
+ try {
99
+ await run("connection", deps.connectTimeoutMs ?? CONNECT_TIMEOUT_MS, (opts) => client.connect(transport, opts));
100
+ return await fn(client, run);
101
+ }
102
+ finally {
103
+ await client.close().catch(() => undefined);
104
+ await guarded.close().catch(() => undefined);
105
+ }
106
+ }
107
+ const NETWORK_ERROR_CODES = new Set([
108
+ "ECONNREFUSED",
109
+ "ECONNRESET",
110
+ "ENOTFOUND",
111
+ "EAI_AGAIN",
112
+ "ETIMEDOUT",
113
+ "EHOSTUNREACH",
114
+ "ENETUNREACH",
115
+ "UND_ERR_CONNECT_TIMEOUT",
116
+ "UND_ERR_SOCKET",
117
+ ]);
118
+ /** The error and its causes: the SDK wraps transport failures (e.g. in an era-negotiation SdkError). */
119
+ function* causeChain(error) {
120
+ let current = error;
121
+ for (let depth = 0; depth < 6 && current !== undefined && current !== null; depth++) {
122
+ yield current;
123
+ const next = current;
124
+ current = next.cause ?? next.data?.cause;
125
+ }
126
+ }
127
+ /**
128
+ * Maps a failure to an outcome from typed signals only -- never from text a
129
+ * server controls. On streamable-http every HTTP failure arrives as an
130
+ * SdkHttpError whose message carries the response *body*, not the status,
131
+ * so the status must come from `error.status`.
132
+ */
133
+ export function classifyError(error) {
134
+ for (const cause of causeChain(error)) {
135
+ if (cause instanceof UnauthorizedError)
136
+ return "authRequired";
137
+ if (cause instanceof SdkHttpError) {
138
+ const status = cause.status;
139
+ // 401 also covers edge auth proxies answering with a non-MCP body.
140
+ if (status === 401)
141
+ return "authRequired";
142
+ // 403: access denied; retrying the same request won't help, but neither is it a protocol fault.
143
+ if (status === 403 || status === 408 || status === 429 || status >= 500)
144
+ return "unreachable";
145
+ return "protocolError";
146
+ }
147
+ if (cause instanceof GuardError)
148
+ return "unreachable";
149
+ const code = cause.code;
150
+ if (typeof code === "string" && NETWORK_ERROR_CODES.has(code))
151
+ return "unreachable";
152
+ // undici's network-level failure (refused, reset, TLS, forbidden port).
153
+ if (cause instanceof TypeError && cause.message === "fetch failed")
154
+ return "unreachable";
155
+ if (cause instanceof McpSessionError)
156
+ return "unreachable";
157
+ }
158
+ return "protocolError";
159
+ }
160
+ function messageOf(error) {
161
+ return error instanceof Error ? error.message : String(error);
162
+ }
163
+ /**
164
+ * Connects to the endpoint, completes the initialize handshake, and lists
165
+ * the server's tools. The answer to "is this discovery result real?"
166
+ */
167
+ export async function probeMcpServer(endpoint, deps = {}) {
168
+ try {
169
+ return await withClient(endpoint, deps, async (client, run) => ({
170
+ kind: "connected",
171
+ serverInfo: client.getServerVersion(),
172
+ tools: (await run("tools/list request", deps.requestTimeoutMs ?? REQUEST_TIMEOUT_MS, (opts) => client.listTools(undefined, opts))).tools.map((tool) => ({
173
+ name: tool.name,
174
+ description: tool.description,
175
+ })),
176
+ }));
177
+ }
178
+ catch (error) {
179
+ return { kind: classifyError(error), message: messageOf(error) };
180
+ }
181
+ }
182
+ /** Connects to the endpoint and calls a single tool with the given arguments. */
183
+ export async function callMcpTool(endpoint, tool, args, deps = {}) {
184
+ try {
185
+ return await withClient(endpoint, deps, async (client, run) => ({
186
+ kind: "called",
187
+ result: await run("tools/call request", deps.requestTimeoutMs ?? REQUEST_TIMEOUT_MS, (opts) => client.callTool({ name: tool, arguments: args }, opts)),
188
+ }));
189
+ }
190
+ catch (error) {
191
+ return { kind: classifyError(error), message: messageOf(error) };
192
+ }
193
+ }
@@ -0,0 +1,66 @@
1
+ export type AddressLookup = (hostname: string) => Promise<string[]>;
2
+ /** The production lookup: every address the hostname resolves to. */
3
+ export declare const lookupAllAddresses: AddressLookup;
4
+ /**
5
+ * Who may be dialed. `allowLoopback` defaults off (test seam only);
6
+ * `allowPrivate` defaults from the environment at the composition roots
7
+ * (see {@link resolveNetPolicy}).
8
+ */
9
+ export interface NetPolicy {
10
+ /** TEST SEAM ONLY: lets loopback stub servers through. Never set in production paths. */
11
+ allowLoopback?: boolean;
12
+ /**
13
+ * Allows every private/reserved address, loopback included. Explicitly set
14
+ * in tests; production leaves it unset and the environment decides (see
15
+ * {@link resolveNetPolicy}).
16
+ */
17
+ allowPrivate?: boolean;
18
+ }
19
+ /**
20
+ * Resolves a partial policy to a full one. `allowLoopback` is explicit-only
21
+ * (test seam). Private/reserved targets are denied unless explicitly allowed
22
+ * for trusted private targets; an explicit policy value always wins over the environment.
23
+ */
24
+ export declare function resolveNetPolicy(policy?: NetPolicy): {
25
+ allowLoopback: boolean;
26
+ allowPrivate: boolean;
27
+ };
28
+ export declare function plaintextTargetError(hostname: string): string;
29
+ /** Refusal for a hostname whose every resolved address is undialable. */
30
+ export declare function privateResolutionError(hostname: string, addresses: string[]): string;
31
+ /** Refusal for an IP literal that is itself private/reserved. */
32
+ export declare function privateLiteralError(address: string): string;
33
+ /**
34
+ * Whether an address is private/loopback/link-local/reserved or otherwise
35
+ * not a plain public unicast target. IPv4-mapped/v4-compatible IPv6 and
36
+ * NAT64 forms are unwrapped and the embedded IPv4 decides.
37
+ */
38
+ export declare function isBlockedAddress(address: string): boolean;
39
+ /** Loopback only (127/8, ::1, and v4-mapped loopback). */
40
+ export declare function isLoopbackAddress(address: string): boolean;
41
+ /**
42
+ * The single allow rule: public unicast, or a blocked address the policy
43
+ * opens -- loopback only via the `allowLoopback` test seam, anything via
44
+ * the `allowPrivate` escape hatch. Pass a resolved policy (see
45
+ * {@link resolveNetPolicy}); a bare `{}` refuses everything non-unicast.
46
+ */
47
+ export declare function isAllowedAddress(address: string, policy?: NetPolicy): boolean;
48
+ export type PublicTargetResolution = {
49
+ ok: true;
50
+ addresses: string[];
51
+ } | {
52
+ ok: false;
53
+ error: string;
54
+ };
55
+ /**
56
+ * Resolves and validates a URL's host without fetching it. Fetches don't need
57
+ * this -- guarded-fetch checks the addresses each socket actually connects
58
+ * to -- but a URL the CLI hands to someone else (the remote a server card
59
+ * selects, which the MCP client then connects to) is never connected to
60
+ * here, so it is checked up front.
61
+ *
62
+ * `allowLoopback` exists ONLY as a test seam; the CLI never sets it in
63
+ * production paths.
64
+ */
65
+ export declare function resolvePublicAddresses(url: URL, lookupAddresses: AddressLookup, policy?: NetPolicy): Promise<PublicTargetResolution>;
66
+ export declare function ensurePublicTarget(url: URL, lookupAddresses: AddressLookup, policy?: NetPolicy): Promise<string | null>;
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Network target validation shared by every outbound fetch in the CLI
3
+ * (card/endpoint resolution, brand catalogs, the MCP transport, OAuth
4
+ * discovery/registration/token calls).
5
+ *
6
+ * Address classification delegates to ipaddr.js: its IPv4/IPv6 range tables
7
+ * cover the forms hand-rolled lists keep missing -- IPv4-mapped and
8
+ * v4-compatible IPv6, NAT64 (64:ff9b::/96), 6to4, Teredo, deprecated
9
+ * site-local, CGNAT, benchmarking and reserved ranges. The rule is simple:
10
+ * only "unicast" is allowed, and forms embedding an IPv4 address re-check
11
+ * the embedded address. Unparseable input fails closed.
12
+ */
13
+ import { lookup } from "node:dns/promises";
14
+ import { isIP } from "node:net";
15
+ import ipaddr from "ipaddr.js";
16
+ /** The production lookup: every address the hostname resolves to. */
17
+ export const lookupAllAddresses = async (hostname) => (await lookup(hostname, { all: true, verbatim: true })).map((entry) => entry.address);
18
+ /**
19
+ * Resolves a partial policy to a full one. `allowLoopback` is explicit-only
20
+ * (test seam). Private/reserved targets are denied unless explicitly allowed
21
+ * for trusted private targets; an explicit policy value always wins over the environment.
22
+ */
23
+ export function resolveNetPolicy(policy = {}) {
24
+ const allowPrivate = process.env.OSD_ALLOW_PRIVATE;
25
+ return {
26
+ allowLoopback: policy.allowLoopback === true,
27
+ allowPrivate: policy.allowPrivate ?? (allowPrivate === "1" || allowPrivate === "true"),
28
+ };
29
+ }
30
+ const REFUSAL_REMEDY = "private and reserved addresses are refused by default; use a public HTTPS endpoint. " +
31
+ "For trusted targets on a private network only, pass --allow-private-addresses (or set OSD_ALLOW_PRIVATE=1)";
32
+ export function plaintextTargetError(hostname) {
33
+ return `refusing to fetch ${hostname} over HTTP: HTTP is only allowed for loopback; use HTTPS`;
34
+ }
35
+ /** Refusal for a hostname whose every resolved address is undialable. */
36
+ export function privateResolutionError(hostname, addresses) {
37
+ return `refusing to fetch ${hostname}: it resolves to private address ${addresses[0]} -- ${REFUSAL_REMEDY}`;
38
+ }
39
+ /** Refusal for an IP literal that is itself private/reserved. */
40
+ export function privateLiteralError(address) {
41
+ return `refusing to fetch private address ${address} -- ${REFUSAL_REMEDY}`;
42
+ }
43
+ /**
44
+ * Whether an address is private/loopback/link-local/reserved or otherwise
45
+ * not a plain public unicast target. IPv4-mapped/v4-compatible IPv6 and
46
+ * NAT64 forms are unwrapped and the embedded IPv4 decides.
47
+ */
48
+ export function isBlockedAddress(address) {
49
+ let parsed;
50
+ try {
51
+ parsed = ipaddr.parse(address);
52
+ }
53
+ catch {
54
+ return true; // fail closed
55
+ }
56
+ if (parsed.kind() === "ipv4") {
57
+ // Everything but plain unicast: loopback, RFC-1918, CGNAT, link-local,
58
+ // multicast, broadcast, reserved, "this host".
59
+ return parsed.range() !== "unicast";
60
+ }
61
+ const v6 = parsed;
62
+ // v4-mapped (::ffff:0/96) routes to the embedded IPv4 host.
63
+ if (v6.isIPv4MappedAddress()) {
64
+ return isBlockedAddress(v6.toIPv4Address().toString());
65
+ }
66
+ const bytes = v6.toByteArray();
67
+ // Deprecated v4-compatible ::/96: ipaddr.js only recognizes the dotted
68
+ // spelling ("::127.0.0.1") as mapped, but WHATWG URL canonicalizes it to
69
+ // hex ("::7f00:1"), which reads as plain unicast. Block the whole prefix
70
+ // fail-closed; :: and ::1 land here too.
71
+ if (bytes.slice(0, 12).every((b) => b === 0))
72
+ return true;
73
+ // NAT64 (64:ff9b::/96) carries the real target in the low 32 bits.
74
+ if (v6.range() === "rfc6052" || v6.range() === "rfc6145") {
75
+ return isBlockedAddress(bytes.slice(12).join("."));
76
+ }
77
+ // Blocks loopback, link-local, unique-local, multicast, 6to4, Teredo,
78
+ // deprecated site-local, and anything reserved.
79
+ return v6.range() !== "unicast";
80
+ }
81
+ /** Loopback only (127/8, ::1, and v4-mapped loopback). */
82
+ export function isLoopbackAddress(address) {
83
+ try {
84
+ const parsed = ipaddr.process(address);
85
+ return parsed.range() === "loopback";
86
+ }
87
+ catch {
88
+ return false;
89
+ }
90
+ }
91
+ /**
92
+ * The single allow rule: public unicast, or a blocked address the policy
93
+ * opens -- loopback only via the `allowLoopback` test seam, anything via
94
+ * the `allowPrivate` escape hatch. Pass a resolved policy (see
95
+ * {@link resolveNetPolicy}); a bare `{}` refuses everything non-unicast.
96
+ */
97
+ export function isAllowedAddress(address, policy = {}) {
98
+ if (!isBlockedAddress(address))
99
+ return true;
100
+ if (policy.allowPrivate === true)
101
+ return true;
102
+ return policy.allowLoopback === true && isLoopbackAddress(address);
103
+ }
104
+ /**
105
+ * Resolves and validates a URL's host without fetching it. Fetches don't need
106
+ * this -- guarded-fetch checks the addresses each socket actually connects
107
+ * to -- but a URL the CLI hands to someone else (the remote a server card
108
+ * selects, which the MCP client then connects to) is never connected to
109
+ * here, so it is checked up front.
110
+ *
111
+ * `allowLoopback` exists ONLY as a test seam; the CLI never sets it in
112
+ * production paths.
113
+ */
114
+ export async function resolvePublicAddresses(url, lookupAddresses, policy = {}) {
115
+ const resolved = resolveNetPolicy(policy);
116
+ const hostname = url.hostname.replace(/^\[|\]$/g, "");
117
+ if (isIP(hostname) !== 0) {
118
+ if (url.protocol === "http:" && !isLoopbackAddress(hostname)) {
119
+ return { ok: false, error: plaintextTargetError(hostname) };
120
+ }
121
+ if (!isAllowedAddress(hostname, resolved)) {
122
+ return { ok: false, error: privateLiteralError(hostname) };
123
+ }
124
+ return { ok: true, addresses: [hostname] };
125
+ }
126
+ let addresses;
127
+ try {
128
+ addresses = await lookupAddresses(hostname);
129
+ }
130
+ catch (cause) {
131
+ const message = cause instanceof Error ? cause.message : String(cause);
132
+ return { ok: false, error: `could not resolve ${hostname}: ${message}` };
133
+ }
134
+ if (addresses.length === 0) {
135
+ return { ok: false, error: `could not resolve ${hostname}: no addresses` };
136
+ }
137
+ if (url.protocol === "http:" && addresses.some((address) => !isLoopbackAddress(address))) {
138
+ return { ok: false, error: plaintextTargetError(hostname) };
139
+ }
140
+ // Split-horizon DNS (private network) often answers with a private address alongside
141
+ // the public one: return the dialable subset rather than refusing the
142
+ // name. Only a name with NO dialable address is refused.
143
+ const allowed = addresses.filter((address) => isAllowedAddress(address, resolved));
144
+ if (allowed.length === 0) {
145
+ return { ok: false, error: privateResolutionError(hostname, addresses) };
146
+ }
147
+ return { ok: true, addresses: allowed };
148
+ }
149
+ export async function ensurePublicTarget(url, lookupAddresses, policy = {}) {
150
+ const resolution = await resolvePublicAddresses(url, lookupAddresses, policy);
151
+ return resolution.ok ? null : resolution.error;
152
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Proxy configuration for the CLI's outbound fetches, from the environment.
3
+ *
4
+ * The guarded fetch honors HTTPS_PROXY / HTTP_PROXY for HTTPS targets and
5
+ * respects NO_PROXY. A proxy comes only from the process environment -- never
6
+ * from registry responses, ARD documents, or service metadata -- so a
7
+ * configured proxy IS the operator's network policy: it is dialed wherever it
8
+ * resolves, private or reserved addresses included (a loopback sidecar, a
9
+ * reserved interception address such as Muse's). When one applies, the
10
+ * origin's address is never resolved locally -- the CONNECT goes to the proxy
11
+ * and the proxy enforces which destinations may be reached. The CLI's address
12
+ * guard still applies to every DIRECT connection, NO_PROXY requests included.
13
+ *
14
+ * Deliberately NOT supported: proxying plain-HTTP targets (the guard only
15
+ * allows HTTP to loopback, which belongs in NO_PROXY anyway), socks proxies,
16
+ * and silently widening OSD_ALLOW_PRIVATE to make a proxy reachable.
17
+ */
18
+ /** A proxy that applies to a request, or the reason one cannot be used. */
19
+ export type ProxyDecision = {
20
+ kind: "direct";
21
+ } | {
22
+ kind: "proxy";
23
+ url: URL;
24
+ token?: string;
25
+ } | {
26
+ kind: "invalid";
27
+ message: string;
28
+ };
29
+ /**
30
+ * Whether `hostname:port` matches a NO_PROXY/no_proxy value. Mirrors the
31
+ * widely-implemented rules (and undici's EnvHttpProxyAgent): comma- or
32
+ * whitespace-separated entries, a bare `*` matches everything, an entry is
33
+ * a hostname or domain suffix (leading dot optional), with an optional
34
+ * `:port` qualifier, and IPv6 entries may be bracketed.
35
+ */
36
+ export declare function noProxyMatches(noProxy: string, hostname: string, port: number): boolean;
37
+ /**
38
+ * Strips proxy credentials from text before it reaches an error or
39
+ * diagnostic. Proxy URLs come from the environment and may embed
40
+ * `user:password@`; neither the raw env spelling nor the percent-encoded
41
+ * form a parsed URL produces may surface in CLI output.
42
+ */
43
+ export declare function redactProxyCredentials(text: string, env?: NodeJS.ProcessEnv): string;
44
+ /**
45
+ * Decides how a request to `target` leaves the process. Only https: targets
46
+ * are proxied: HTTPS_PROXY (then HTTP_PROXY as a fallback, matching common
47
+ * tooling), unless NO_PROXY exempts the target. A proxy URL that is itself
48
+ * malformed or uses an unsupported scheme is "invalid" so the failure is
49
+ * loud rather than a silent direct connection the operator did not intend.
50
+ */
51
+ export declare function resolveProxyFor(target: URL, env?: NodeJS.ProcessEnv): ProxyDecision;