@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,147 @@
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
+ function firstEnv(env, names) {
19
+ for (const name of names) {
20
+ const value = env[name];
21
+ if (value !== undefined && value.trim() !== "")
22
+ return value.trim();
23
+ }
24
+ return undefined;
25
+ }
26
+ /**
27
+ * Whether `hostname:port` matches a NO_PROXY/no_proxy value. Mirrors the
28
+ * widely-implemented rules (and undici's EnvHttpProxyAgent): comma- or
29
+ * whitespace-separated entries, a bare `*` matches everything, an entry is
30
+ * a hostname or domain suffix (leading dot optional), with an optional
31
+ * `:port` qualifier, and IPv6 entries may be bracketed.
32
+ */
33
+ export function noProxyMatches(noProxy, hostname, port) {
34
+ const host = hostname.replace(/^\[|\]$/g, "").toLowerCase().replace(/\.$/, "");
35
+ for (const rawEntry of noProxy.split(/[,\s]/)) {
36
+ if (rawEntry === "")
37
+ continue;
38
+ let entryHost;
39
+ let entryPort = 0;
40
+ const ipv6WithPort = rawEntry.match(/^\[(.+)]:(\d+)$/);
41
+ if (ipv6WithPort) {
42
+ entryHost = ipv6WithPort[1];
43
+ entryPort = Number.parseInt(ipv6WithPort[2], 10);
44
+ }
45
+ else {
46
+ const unbracketed = rawEntry.replace(/^\[(.+)]$/, "$1");
47
+ const colonCount = (unbracketed.match(/:/g) ?? []).length;
48
+ const hostPort = colonCount === 1 ? unbracketed.match(/^(.+):(\d+)$/) : null;
49
+ entryHost = hostPort ? hostPort[1] : unbracketed;
50
+ entryPort = hostPort ? Number.parseInt(hostPort[2], 10) : 0;
51
+ }
52
+ entryHost = entryHost.replace(/^\*?\./, "").replace(/\.$/, "").toLowerCase();
53
+ if (entryHost === "")
54
+ continue;
55
+ if (entryPort !== 0 && entryPort !== port)
56
+ continue;
57
+ if (rawEntry.trim() === "*" || rawEntry.trim().startsWith("*:"))
58
+ return true;
59
+ if (host === entryHost)
60
+ return true;
61
+ if (host.endsWith(`.${entryHost}`))
62
+ return true;
63
+ }
64
+ return false;
65
+ }
66
+ const PROXY_ENV_NAMES = ["HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy"];
67
+ /**
68
+ * Strips proxy credentials from text before it reaches an error or
69
+ * diagnostic. Proxy URLs come from the environment and may embed
70
+ * `user:password@`; neither the raw env spelling nor the percent-encoded
71
+ * form a parsed URL produces may surface in CLI output.
72
+ */
73
+ export function redactProxyCredentials(text, env = process.env) {
74
+ let out = text;
75
+ for (const name of PROXY_ENV_NAMES) {
76
+ const value = env[name]?.trim();
77
+ if (value === undefined || value === "")
78
+ continue;
79
+ // The userinfo as written in the environment (possibly unparseable).
80
+ const raw = value.match(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/([^/@]*)@/)?.[1];
81
+ if (raw !== undefined && raw !== "")
82
+ out = out.split(`${raw}@`).join("<redacted>@").split(raw).join("<redacted>");
83
+ try {
84
+ const url = new URL(value);
85
+ if (url.password !== "")
86
+ out = out.split(`${url.username}:${url.password}`).join("<redacted>");
87
+ if (url.username !== "")
88
+ out = out.split(`${url.username}@`).join("<redacted>@");
89
+ }
90
+ catch {
91
+ // Malformed proxy value: the raw-spelling redaction above still applies.
92
+ }
93
+ }
94
+ return out;
95
+ }
96
+ /**
97
+ * Decides how a request to `target` leaves the process. Only https: targets
98
+ * are proxied: HTTPS_PROXY (then HTTP_PROXY as a fallback, matching common
99
+ * tooling), unless NO_PROXY exempts the target. A proxy URL that is itself
100
+ * malformed or uses an unsupported scheme is "invalid" so the failure is
101
+ * loud rather than a silent direct connection the operator did not intend.
102
+ */
103
+ export function resolveProxyFor(target, env = process.env) {
104
+ if (target.protocol !== "https:")
105
+ return { kind: "direct" };
106
+ const hostname = target.hostname.replace(/^\[|\]$/g, "");
107
+ const port = Number.parseInt(target.port, 10) || 443;
108
+ const noProxy = firstEnv(env, ["NO_PROXY", "no_proxy"]);
109
+ if (noProxy !== undefined && noProxyMatches(noProxy, hostname, port)) {
110
+ return { kind: "direct" };
111
+ }
112
+ const proxyValue = firstEnv(env, PROXY_ENV_NAMES);
113
+ if (proxyValue === undefined)
114
+ return { kind: "direct" };
115
+ let proxyUrl;
116
+ try {
117
+ proxyUrl = new URL(proxyValue);
118
+ }
119
+ catch {
120
+ return { kind: "invalid", message: `proxy URL ${redactProxyCredentials(JSON.stringify(proxyValue), env)} is not a valid URL` };
121
+ }
122
+ if (proxyUrl.protocol !== "http:" && proxyUrl.protocol !== "https:") {
123
+ return {
124
+ kind: "invalid",
125
+ message: `proxy URL ${redactProxyCredentials(JSON.stringify(proxyValue), env)} uses unsupported scheme "${proxyUrl.protocol}" (http/https only)`,
126
+ };
127
+ }
128
+ const token = proxyAuthToken(proxyUrl);
129
+ proxyUrl.username = "";
130
+ proxyUrl.password = "";
131
+ return { kind: "proxy", url: proxyUrl, ...(token === undefined ? {} : { token }) };
132
+ }
133
+ /** The Proxy-Authorization value for a proxy URL's userinfo, if any. */
134
+ function proxyAuthToken(proxyUrl) {
135
+ if (proxyUrl.username === "" && proxyUrl.password === "")
136
+ return undefined;
137
+ const decode = (value) => {
138
+ try {
139
+ return decodeURIComponent(value);
140
+ }
141
+ catch {
142
+ return value;
143
+ }
144
+ };
145
+ const credentials = `${decode(proxyUrl.username)}:${decode(proxyUrl.password)}`;
146
+ return `Basic ${Buffer.from(credentials, "utf8").toString("base64")}`;
147
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Shape of a registry search request, matching `contracts/schemas/registry-search-request`.
3
+ */
4
+ export interface SearchRequest {
5
+ query: {
6
+ text: string;
7
+ filter?: Record<string, string | string[]>;
8
+ };
9
+ federation?: "auto" | "referrals" | "none";
10
+ pageSize?: number;
11
+ pageToken?: string;
12
+ }
13
+ export interface BuildSearchRequestOptions {
14
+ text: string;
15
+ filters?: string[];
16
+ federation?: "auto" | "referrals" | "none";
17
+ pageSize?: number;
18
+ pageToken?: string;
19
+ }
20
+ /**
21
+ * Parses a CLI page-size argument without accepting partial numbers like `10abc`.
22
+ */
23
+ export declare function parsePageSize(value: string): number;
24
+ /**
25
+ * Parses `key=value` filter options into the request's structured filter map.
26
+ * Repeated keys become an array of values; a single occurrence stays a string.
27
+ */
28
+ export declare function parseFilters(filters: string[] | undefined): Record<string, string | string[]> | undefined;
29
+ /**
30
+ * Builds a `registry-search-request`-conformant request body from CLI options.
31
+ */
32
+ export declare function buildSearchRequest(options: BuildSearchRequestOptions): SearchRequest;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Parses a CLI page-size argument without accepting partial numbers like `10abc`.
3
+ */
4
+ export function parsePageSize(value) {
5
+ if (!/^-?\d+$/.test(value)) {
6
+ throw new Error(`Invalid --page-size value "${value}": expected an integer.`);
7
+ }
8
+ const pageSize = Number(value);
9
+ if (!Number.isSafeInteger(pageSize)) {
10
+ throw new Error(`Invalid --page-size value "${value}": expected a safe integer.`);
11
+ }
12
+ return pageSize;
13
+ }
14
+ /**
15
+ * Parses `key=value` filter options into the request's structured filter map.
16
+ * Repeated keys become an array of values; a single occurrence stays a string.
17
+ */
18
+ export function parseFilters(filters) {
19
+ if (!filters || filters.length === 0)
20
+ return undefined;
21
+ const result = {};
22
+ for (const entry of filters) {
23
+ const separatorIndex = entry.indexOf("=");
24
+ if (separatorIndex === -1) {
25
+ throw new Error(`Invalid --filter value "${entry}": expected "key=value".`);
26
+ }
27
+ const key = entry.slice(0, separatorIndex);
28
+ const value = entry.slice(separatorIndex + 1);
29
+ if (key.length === 0) {
30
+ throw new Error(`Invalid --filter value "${entry}": key must not be empty.`);
31
+ }
32
+ const existing = result[key];
33
+ if (existing === undefined) {
34
+ result[key] = value;
35
+ }
36
+ else if (Array.isArray(existing)) {
37
+ existing.push(value);
38
+ }
39
+ else {
40
+ result[key] = [existing, value];
41
+ }
42
+ }
43
+ return result;
44
+ }
45
+ /**
46
+ * Builds a `registry-search-request`-conformant request body from CLI options.
47
+ */
48
+ export function buildSearchRequest(options) {
49
+ const request = {
50
+ query: { text: options.text },
51
+ };
52
+ const filter = parseFilters(options.filters);
53
+ if (filter)
54
+ request.query.filter = filter;
55
+ if (options.federation)
56
+ request.federation = options.federation;
57
+ if (options.pageSize !== undefined)
58
+ request.pageSize = options.pageSize;
59
+ if (options.pageToken)
60
+ request.pageToken = options.pageToken;
61
+ return request;
62
+ }
@@ -0,0 +1,62 @@
1
+ import { type AddressLookup } from "./net-guard.js";
2
+ export type ResolveOutcome = {
3
+ kind: "endpoint";
4
+ url: string;
5
+ /** Set when the target was a server card; null when the URL itself is the endpoint. */
6
+ fromCard: {
7
+ multipleRemotes: boolean;
8
+ cardName?: string;
9
+ } | null;
10
+ /** Human-readable caveat worth surfacing (e.g. the target 403'd). */
11
+ warning?: string;
12
+ } | {
13
+ kind: "invalid";
14
+ message: string;
15
+ } | {
16
+ kind: "unreachable";
17
+ message: string;
18
+ };
19
+ type FetchImplementation = typeof fetch;
20
+ /**
21
+ * Injectable seams for tests. Production always uses the guarded fetch,
22
+ * which checks every address it connects to, redirect hops included.
23
+ */
24
+ export interface ResolveEndpointDeps {
25
+ /** Replaces the guarded fetch entirely (no SSRF checks) -- tests only. */
26
+ fetch?: FetchImplementation;
27
+ lookupAddresses?: AddressLookup;
28
+ /** TEST SEAM ONLY: lets loopback stub servers through. Never set in production paths. */
29
+ allowLoopback?: boolean;
30
+ /** Overrides the environment's SSRF private-address policy; tests set it explicitly. */
31
+ allowPrivate?: boolean;
32
+ /**
33
+ * Whether the caller will connect to the resolved endpoint itself. When
34
+ * false (--resolve-only handoff) the card-selected remote is always
35
+ * checked locally, even if a proxy would carry a real connection.
36
+ */
37
+ willConnect?: boolean;
38
+ }
39
+ /**
40
+ * Resolves a command target to a connectable MCP endpoint URL.
41
+ *
42
+ * A bounded probe (the guarded fetch validates every redirect hop), with deterministic discrimination on
43
+ * content shape:
44
+ *
45
+ * - The document parses as JSON and looks like an MCP server card (has a
46
+ * `remotes` array) → the endpoint comes from the first streamable-http
47
+ * remote. A card with no usable remote is InvalidArgument: the human gave
48
+ * us a card, so a card is what we must resolve.
49
+ * - A `text/event-stream` answer is a live streamable-http endpoint holding
50
+ * an SSE stream open -- that IS the endpoint. Draining it would burn the
51
+ * fetch timeout and misclassify a healthy server as unreachable.
52
+ * - Anything else (non-JSON body, JSON that isn't a card, even an HTTP error
53
+ * status) → the URL itself stands as the endpoint. MCP streamable-http
54
+ * endpoints rarely answer a plain GET meaningfully (often 400/405), so an
55
+ * HTTP error is not evidence the endpoint is bad; only a network-level
56
+ * failure is.
57
+ *
58
+ * This is what makes the "registered the card URL instead of the endpoint"
59
+ * bug class impossible: both forms converge here.
60
+ */
61
+ export declare function resolveEndpoint(target: string, deps?: ResolveEndpointDeps): Promise<ResolveOutcome>;
62
+ export {};
@@ -0,0 +1,172 @@
1
+ import { cardEndpoint, isServerCard, remoteCount } from "./mcp-card.js";
2
+ import { createGuardedFetch } from "./guarded-fetch.js";
3
+ import { ensurePublicTarget, lookupAllAddresses } from "./net-guard.js";
4
+ import { resolveProxyFor } from "./proxy-config.js";
5
+ const FETCH_TIMEOUT_MS = 10_000;
6
+ const MAX_RESPONSE_BYTES = 1024 * 1024;
7
+ async function readResponseText(response) {
8
+ const contentLength = response.headers.get("content-length");
9
+ if (contentLength !== null && Number(contentLength) > MAX_RESPONSE_BYTES) {
10
+ throw new Error(`response exceeds the ${MAX_RESPONSE_BYTES}-byte limit`);
11
+ }
12
+ if (response.body === null)
13
+ return "";
14
+ const reader = response.body.getReader();
15
+ const chunks = [];
16
+ let total = 0;
17
+ try {
18
+ while (true) {
19
+ const { done, value } = await reader.read();
20
+ if (done)
21
+ break;
22
+ total += value.byteLength;
23
+ if (total > MAX_RESPONSE_BYTES) {
24
+ await reader.cancel();
25
+ throw new Error(`response exceeds the ${MAX_RESPONSE_BYTES}-byte limit`);
26
+ }
27
+ chunks.push(value);
28
+ }
29
+ }
30
+ finally {
31
+ reader.releaseLock();
32
+ }
33
+ const bytes = new Uint8Array(total);
34
+ let offset = 0;
35
+ for (const chunk of chunks) {
36
+ bytes.set(chunk, offset);
37
+ offset += chunk.byteLength;
38
+ }
39
+ return new TextDecoder().decode(bytes);
40
+ }
41
+ /**
42
+ * Resolves a command target to a connectable MCP endpoint URL.
43
+ *
44
+ * A bounded probe (the guarded fetch validates every redirect hop), with deterministic discrimination on
45
+ * content shape:
46
+ *
47
+ * - The document parses as JSON and looks like an MCP server card (has a
48
+ * `remotes` array) → the endpoint comes from the first streamable-http
49
+ * remote. A card with no usable remote is InvalidArgument: the human gave
50
+ * us a card, so a card is what we must resolve.
51
+ * - A `text/event-stream` answer is a live streamable-http endpoint holding
52
+ * an SSE stream open -- that IS the endpoint. Draining it would burn the
53
+ * fetch timeout and misclassify a healthy server as unreachable.
54
+ * - Anything else (non-JSON body, JSON that isn't a card, even an HTTP error
55
+ * status) → the URL itself stands as the endpoint. MCP streamable-http
56
+ * endpoints rarely answer a plain GET meaningfully (often 400/405), so an
57
+ * HTTP error is not evidence the endpoint is bad; only a network-level
58
+ * failure is.
59
+ *
60
+ * This is what makes the "registered the card URL instead of the endpoint"
61
+ * bug class impossible: both forms converge here.
62
+ */
63
+ export async function resolveEndpoint(target, deps = {}) {
64
+ let parsed;
65
+ try {
66
+ parsed = new URL(target);
67
+ }
68
+ catch {
69
+ return { kind: "invalid", message: `not a URL: ${target}` };
70
+ }
71
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
72
+ return { kind: "invalid", message: `unsupported URL scheme "${parsed.protocol}" (http/https only)` };
73
+ }
74
+ const lookupAddresses = deps.lookupAddresses ?? lookupAllAddresses;
75
+ const policy = { allowLoopback: deps.allowLoopback === true, allowPrivate: deps.allowPrivate };
76
+ const guarded = deps.fetch === undefined ? createGuardedFetch(lookupAddresses, policy) : undefined;
77
+ const fetchImplementation = deps.fetch ?? guarded.fetchFn;
78
+ let response;
79
+ try {
80
+ try {
81
+ response = await fetchImplementation(parsed, {
82
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
83
+ redirect: "follow",
84
+ });
85
+ }
86
+ catch (cause) {
87
+ const message = cause instanceof Error ? cause.message : String(cause);
88
+ return { kind: "unreachable", message: `could not reach ${target}: ${message}` };
89
+ }
90
+ // A streamable-http endpoint may answer GET by holding an SSE stream
91
+ // open; that answer IS the endpoint. Read nothing from the body.
92
+ const contentType = response.headers.get("content-type") ?? "";
93
+ if (contentType.toLowerCase().startsWith("text/event-stream")) {
94
+ await response.body?.cancel();
95
+ const url = typeof response.url === "string" && response.url !== "" ? response.url : parsed.toString();
96
+ return { kind: "endpoint", url, fromCard: null };
97
+ }
98
+ let text;
99
+ try {
100
+ text = await readResponseText(response);
101
+ }
102
+ catch (cause) {
103
+ const message = cause instanceof Error ? cause.message : String(cause);
104
+ return { kind: "unreachable", message: `could not read the response from ${target}: ${message}` };
105
+ }
106
+ return classify(target, response, text, lookupAddresses, policy, deps.willConnect !== false);
107
+ }
108
+ finally {
109
+ if (guarded !== undefined)
110
+ await guarded.close().catch(() => undefined);
111
+ }
112
+ }
113
+ async function classify(target, response, text, lookupAddresses, policy, willConnect) {
114
+ let doc;
115
+ try {
116
+ doc = JSON.parse(text);
117
+ }
118
+ catch {
119
+ doc = undefined;
120
+ }
121
+ // 401/403 means an auth or edge layer answered instead of the resource:
122
+ // we can no longer tell card from endpoint, so say so when we guess.
123
+ const authWarning = response.status === 401 || response.status === 403
124
+ ? `target answered HTTP ${response.status} -- if this is a card URL, the card could not be fetched; registering the URL as-is`
125
+ : undefined;
126
+ if (doc !== undefined && isServerCard(doc)) {
127
+ const endpoint = cardEndpoint(doc);
128
+ if (endpoint === null) {
129
+ return {
130
+ kind: "invalid",
131
+ message: `${target} is a server card but has no streamable-http remote`,
132
+ };
133
+ }
134
+ let endpointUrl;
135
+ try {
136
+ endpointUrl = new URL(endpoint);
137
+ }
138
+ catch {
139
+ return { kind: "invalid", message: `${target} has an invalid remote URL: ${endpoint}` };
140
+ }
141
+ if (endpointUrl.protocol !== "https:" && endpointUrl.protocol !== "http:") {
142
+ return {
143
+ kind: "invalid",
144
+ message: `${target} has an unsupported remote URL scheme "${endpointUrl.protocol}" (http/https only)`,
145
+ };
146
+ }
147
+ // The card URL itself was checked while fetching, but the remote it
148
+ // selects is attacker-controlled content: a public card can point at a
149
+ // private address and turn `osd mcp` into an SSRF primitive for the
150
+ // caller. Nothing here connects to it, so check it now -- unless this
151
+ // CLI will dial the remote through a configured proxy, in which case
152
+ // local resolution is meaningless (the proxy resolves, not us; it may
153
+ // answer public names with interception addresses) and destination
154
+ // enforcement is the proxy's job. Direct, NO_PROXY, plain-HTTP (never
155
+ // proxied), and resolve-only paths keep the local check.
156
+ const proxied = willConnect && resolveProxyFor(endpointUrl).kind === "proxy";
157
+ if (!proxied) {
158
+ const remoteError = await ensurePublicTarget(endpointUrl, lookupAddresses, policy);
159
+ if (remoteError !== null) {
160
+ return { kind: "unreachable", message: `remote selected by ${target}: ${remoteError}` };
161
+ }
162
+ }
163
+ const card = doc;
164
+ return {
165
+ kind: "endpoint",
166
+ url: endpoint,
167
+ fromCard: { multipleRemotes: remoteCount(doc) > 1, cardName: card.name ?? card.displayName },
168
+ warning: authWarning,
169
+ };
170
+ }
171
+ return { kind: "endpoint", url: target, fromCard: null, warning: authWarning };
172
+ }
@@ -0,0 +1,39 @@
1
+ import { type BuildSearchRequestOptions } from "./request.js";
2
+ import type { ErrorResponse, SearchResponse } from "./format.js";
3
+ export interface RunSearchOptions extends BuildSearchRequestOptions {
4
+ /** Base URL of the registry or resolver to query, e.g. "http://localhost:4000". */
5
+ target: string;
6
+ /** Contract version sent as `OSD-Accept-Contract-Version`. */
7
+ contractVersion: string;
8
+ }
9
+ export type SearchOutcome = {
10
+ kind: "success";
11
+ response: SearchResponse;
12
+ contractVersion: string | null;
13
+ validation: string[];
14
+ } | {
15
+ kind: "error";
16
+ status: number;
17
+ error: ErrorResponse;
18
+ contractVersion: string | null;
19
+ } | {
20
+ kind: "malformed";
21
+ status: number;
22
+ body: string;
23
+ } | {
24
+ kind: "unsupportedContractVersion";
25
+ contractVersion: string;
26
+ } | {
27
+ kind: "schemasMissing";
28
+ } | {
29
+ kind: "unreachable";
30
+ message: string;
31
+ };
32
+ /**
33
+ * Sends one search request to the configured target and classifies the result.
34
+ *
35
+ * This function makes no trust or candidate-selection decision: it returns
36
+ * whatever the target sent back, tagged with enough structure for the caller
37
+ * to render or exit accordingly.
38
+ */
39
+ export declare function runSearch(options: RunSearchOptions): Promise<SearchOutcome>;
package/dist/search.js ADDED
@@ -0,0 +1,69 @@
1
+ import { httpFetch } from "./http-fetch.js";
2
+ import { isLoopbackAddress, plaintextTargetError } from "./net-guard.js";
3
+ import { buildSearchRequest } from "./request.js";
4
+ import { schemasAvailable, supportsLocalContractVersion, validateErrorResponse, validateSearchResponse } from "./contracts.js";
5
+ /**
6
+ * Sends one search request to the configured target and classifies the result.
7
+ *
8
+ * This function makes no trust or candidate-selection decision: it returns
9
+ * whatever the target sent back, tagged with enough structure for the caller
10
+ * to render or exit accordingly.
11
+ */
12
+ export async function runSearch(options) {
13
+ if (!schemasAvailable()) {
14
+ return { kind: "schemasMissing" };
15
+ }
16
+ if (!supportsLocalContractVersion(options.contractVersion)) {
17
+ return { kind: "unsupportedContractVersion", contractVersion: options.contractVersion };
18
+ }
19
+ const request = buildSearchRequest(options);
20
+ const url = new URL("search", options.target.endsWith("/") ? options.target : `${options.target}/`);
21
+ const hostname = url.hostname.replace(/^\[|\]$/g, "");
22
+ if (url.protocol === "http:" && hostname !== "localhost" && !isLoopbackAddress(hostname)) {
23
+ return { kind: "unreachable", message: plaintextTargetError(hostname) };
24
+ }
25
+ let response;
26
+ try {
27
+ response = await httpFetch(url, {
28
+ method: "POST",
29
+ headers: {
30
+ "content-type": "application/json",
31
+ "OSD-Accept-Contract-Version": options.contractVersion,
32
+ },
33
+ body: JSON.stringify(request),
34
+ });
35
+ }
36
+ catch (cause) {
37
+ const message = cause instanceof Error ? cause.message : String(cause);
38
+ return { kind: "unreachable", message: `could not reach ${url.toString()}: ${message}` };
39
+ }
40
+ const contractVersion = response.headers.get("OSD-Contract-Version");
41
+ const rawBody = await response.text();
42
+ if (rawBody.length === 0) {
43
+ // Neither a valid registry-search-response nor a valid error-response can
44
+ // legitimately be empty -- both schemas require fields. Don't invent a `{}`
45
+ // body the target never sent; classify this as malformed up front.
46
+ return { kind: "malformed", status: response.status, body: rawBody };
47
+ }
48
+ let parsedBody;
49
+ try {
50
+ parsedBody = JSON.parse(rawBody);
51
+ }
52
+ catch {
53
+ return { kind: "malformed", status: response.status, body: rawBody };
54
+ }
55
+ if (response.ok) {
56
+ const validation = validateSearchResponse(parsedBody, contractVersion ?? options.contractVersion);
57
+ return {
58
+ kind: "success",
59
+ response: parsedBody,
60
+ contractVersion,
61
+ validation: validation.valid ? (validation.skipped ? [validation.reason] : []) : validation.errors,
62
+ };
63
+ }
64
+ const errorValidation = validateErrorResponse(parsedBody, contractVersion ?? options.contractVersion);
65
+ if (!errorValidation.valid || errorValidation.skipped) {
66
+ return { kind: "malformed", status: response.status, body: rawBody };
67
+ }
68
+ return { kind: "error", status: response.status, error: parsedBody, contractVersion };
69
+ }